-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpolyglot.cpp
More file actions
420 lines (371 loc) · 12.9 KB
/
Copy pathpolyglot.cpp
File metadata and controls
420 lines (371 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#if 0
r'''
#endif
// main.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <array>
#include <memory>
#include <filesystem>
#include <stdexcept>
namespace fs = std::filesystem;
std::string usageStr =
"Usage: polyglot <source1> <source2> -o <outputFile>\n"
"Supported extensions:\n"
" C/C++: .cpp, .cc, .cxx, .c\n"
" Python: .py\n"
" Ruby: .rb\n"
" Bash: .sh\n"
" Perl: .pl\n";
std::string runCmd(const std::string& cmd) {
std::array<char, 256> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed!");
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
result += buffer.data();
return result;
}
static std::string shellSafePath(const std::string& path) {
std::string s = fs::path(path).generic_string();
std::string escaped;
for (char c : s) {
if (c == '"') escaped += "\\\"";
else escaped += c;
}
return "\"" + escaped + "\"";
}
std::string replace(const std::string& str, const std::string& replace, const std::string& with) {
if (replace.empty()) return str;
std::string result;
result.reserve(str.size());
std::size_t start = 0;
std::size_t pos;
while ((pos = str.find(replace, start)) != std::string::npos) {
result.append(str, start, pos - start);
result += with;
start = pos + replace.length();
}
result.append(str, start, str.size() - start);
return result;
}
bool checkSyntax(const std::string& file, const std::string& ext) {
std::string res;
std::string quoted = shellSafePath(file);
if (ext == ".cpp" || ext == ".cc" || ext == ".cxx" || ext == ".c") {
std::string flag = ext == ".c" ? "-x c " : "";
res = runCmd("g++ -fsyntax-only " + flag + quoted + " 2>&1");
if (!res.empty()) {
std::cerr << "C/C++ syntax errors in " << file << ":\n" << res;
return false;
}
return true;
} else if (ext == ".py") {
try {
res = runCmd("python3 -m pyflakes " + quoted + " 2>&1");
} catch (const std::exception& x) {
std::cerr << "\033[31m" << "Error: " << x.what() << "\033[0m" << std::endl;
res = x.what();
}
if (!res.empty()) {
std::string fallback = runCmd("python -m py_compile " + quoted + " 2>&1");
if (!fallback.empty()) {
std::cerr << "Python syntax errors in " << file << ":\n" << fallback;
std::cerr << "If pyflakes is desired, please install it or ensure it's on PATH.\n";
return false;
}
}
return true;
} else if (ext == ".rb") {
res = runCmd("ruby -c " + quoted + " 2>&1");
if (res.find("Syntax OK") == std::string::npos) {
std::cerr << "Ruby syntax errors in " << file << ":\n" << res;
return false;
}
return true;
} else if (ext == ".sh") {
res = runCmd("bash -n " + quoted + " 2>&1");
if (!res.empty()) {
std::cerr << "Bash syntax errors in " << file << ":\n" << res;
return false;
}
return true;
} else if (ext == ".pl") {
res = runCmd("perl -c " + quoted + " 2>&1");
if (res.find("syntax OK") == std::string::npos) {
std::cerr << "Perl syntax errors in " << file << ":\n" << res;
return false;
}
return true;
}
std::cerr << "\nUnsupported file extension: " << ext << "\n";
return false;
}
std::vector<std::string> readFile(const std::string& filename) {
std::ifstream in(filename);
if (!in.is_open()) throw std::runtime_error("Failed to open: " + filename);
std::vector<std::string> lines;
std::string line;
while (std::getline(in, line)) lines.push_back(line);
return lines;
}
void writeMerged(
const std::string& outFile,
const std::string& ext1, const std::vector<std::string>& content1,
const std::string& ext2, const std::vector<std::string>& content2
) {
std::ofstream out(outFile, std::ios::binary);
if (!out.is_open()) throw std::runtime_error("Failed to open output: " + outFile);
auto openFence = [](const std::string& ext) -> std::string {
if (ext == ".py") return "r\'\'\'";
if (ext == ".rb") return "=begin";
if (ext == ".sh") return ": '";
if (ext == ".pl") return "=pod";
return "";
};
auto closeFence = [](const std::string& ext) -> std::string {
if (ext == ".py") return "\'\'\'";
if (ext == ".rb") return "=end";
if (ext == ".sh") return "'";
if (ext == ".pl") return "=cut";
return "";
};
auto escapeCpp = [](const std::string& content) -> std::string {
return "#if 0\n" + content + "\n#endif\n";
};
auto writeLine = [&out](const std::string& line) {
out.write(line.c_str(), line.size());
out.put('\n');
};
auto escapeForPython = [](const std::string& line) -> std::string {
std::string out;
for (size_t i = 0; i < line.size(); i++) {
if (i + 2 < line.size() && line[i] == '\'' && line[i+1] == '\'' && line[i+2] == '\'') {
out += "\\'\\'\\'";
i += 2;
} else {
out += line[i];
}
}
return out;
};
if (ext1 == ".cpp" || ext1 == ".cc" || ext1 == ".cxx" || ext1 == ".c") {
writeLine(escapeCpp(openFence(ext2)));
for (const std::string& l : content1) {
writeLine(escapeForPython(l));
}
writeLine(escapeCpp(closeFence(ext2)));
writeLine("#if 0");
for (auto& l : content2) {
writeLine(escapeForPython(l));
}
writeLine("#endif");
}
else if (ext2 == ".cpp" || ext2 == ".cc" || ext2 == ".cxx" || ext2 == ".c") {
writeLine(escapeCpp(openFence(ext1)));
for (auto& l : content2) writeLine(l);
writeLine(escapeCpp(closeFence(ext1)));
writeLine("#if 0");
for (auto& l : content1) writeLine(l);
writeLine("#endif");
}
else {
throw std::runtime_error("No C/C++ file in pair");
}
}
int main(int argc, char* argv[]) {
std::vector<std::string> args(argv, argv + argc);
if (argc < 5) {
std::cerr << usageStr;
return 1;
}
bool verbose = false;
std::string file1, file2, outFile;
for (int i = 1; i < argc; i++) {
if (args[i] == "-o") {
if (i + 1 >= argc) {
std::cerr << "Error: -o requires an argument\n";
return 1;
}
outFile = args[++i];
} else if (file1.empty()) {
file1 = args[i];
} else if (file2.empty()) {
file2 = args[i];
} else if (args[i] == "-v" || args[i] == "--verbose") {
verbose = true;
} else {
std::cerr << "Error: unexpected argument: " << args[i] << "\n";
return 1;
}
}
if (file1.empty() || file2.empty() || outFile.empty()) {
std::cerr << usageStr;
return 1;
}
std::string ext1 = fs::path(file1).extension().string();
std::string ext2 = fs::path(file2).extension().string();
if (verbose) std::cout << "Checking syntax for " << file1 << "... ";
if (!checkSyntax(file1, ext1)) {
std::cerr << "\nSyntax error in " << file1 << "\n";
return 1;
}
if (verbose) std::cout << "OK\n";
if (verbose) std::cout << "Checking syntax for " << file2 << "... ";
if (!checkSyntax(file2, ext2)) {
std::cerr << "\nSyntax error in " << file2 << "\n";
return 1;
}
if (verbose) std::cout << "OK\n";
auto content1 = readFile(file1);
auto content2 = readFile(file2);
writeMerged(outFile, ext1, content1, ext2, content2);
if (verbose) std::cout << "Merged into " << outFile << "\n";
return 0;
}
#if 0
'''
#endif
#if 0
#!/usr/bin/env python3
import sys
import subprocess
from pathlib import Path
import argparse
import shlex
def run_cmd(cmd):
try:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.stdout
except Exception as e:
return str(e)
def shell_safe(path: str) -> str:
# Convert backslashes to forward slashes (for WSL/bash)
p = Path(path).as_posix()
# Quote the path safely for the shell
return shlex.quote(p)
def check_syntax(file_path, ext) -> bool:
file_str = str(file_path)
if ext in ['.cpp', '.cc', '.cxx', '.c']:
flag = " -x c " if ext == ".c" else ""
res = run_cmd(f"g++ -fsyntax-only {flag} {file_str} 2>&1")
if res.strip():
print(f"C++ syntax errors in {file_str}:\n{res}")
return False
return True
elif ext == '.py':
res = run_cmd(f"python3 -m pyflakes {file_str} 2>&1")
if res.strip():
res = run_cmd(f"python3 -m py_compile {file_str} 2>&1")
if res.strip():
print(f"Python syntax errors in {file_str}:\n{res}")
print("If python file does not have syntax errors, please check if pyflakes is installed.")
return False
return True
elif ext == '.rb':
res = run_cmd(f"ruby -c {file_str} 2>&1")
if "Syntax OK" not in res:
print(f"Ruby syntax errors in {file_str}:\n{res}")
return False
return True
elif ext == '.sh':
res = run_cmd(f"bash -n {shell_safe(file_str)} 2>&1")
if res.strip():
print(f"Bash syntax errors in {file_str}:\n{res}")
return False
return True
elif ext == ".pl":
res = run_cmd(f"perl -c {file_str} 2>&1")
if "syntax OK" not in res:
print(f"Perl syntax errors in {file_str}:\n{res}")
return False
return True
else:
print(f"Unsupported file extension: {ext}")
return False
verbose = None
def main():
global verbose
usage_str = """Usage: polyglot <source1> <source2> -o <outputFile>
Supported extensions:
C/C++: .cpp, .cc, .cxx, .c
Python: .py
Ruby: .rb
Bash: .sh
Perl: .pl
"""
parser = argparse.ArgumentParser(usage=usage_str)
parser.add_argument('source1', help='First source file')
parser.add_argument('source2', help='Second source file')
parser.add_argument('-o', '--output', required=True, help='Output file')
parser.add_argument('-v', '--verbose', help='verbose mode')
args = parser.parse_args()
file1 = Path(args.source1)
file2 = Path(args.source2)
out_file = Path(args.output)
verbose = args.verbose
ext1 = file1.suffix
ext2 = file2.suffix
# Check syntax
if verbose: print(f"Checking syntax for {file1}... ", end='')
if not check_syntax(file1, ext1):
print(f"Syntax error in {file1}")
return 1
if verbose: print("OK")
if verbose: print(f"Checking syntax for {file2}... ", end='')
if not check_syntax(file2, ext2):
print(f"Syntax error in {file2}")
return 1
if verbose: print("OK")
# Read files
with open(file1, 'r') as f:
content1 = f.read().splitlines()
with open(file2, 'r') as f:
content2 = f.read().splitlines()
# Determine fence tokens
def open_fence(ext):
if ext == '.py': return "r\'\'\'"
if ext == '.rb': return "=begin"
if ext == '.sh': return ": '"
if ext == '.pl': return "=pod"
return ""
def close_fence(ext):
if ext == '.py': return "\'\'\'"
if ext == '.rb': return "=end"
if ext == '.sh': return "'"
if ext == ".pl": return "=cut"
return ""
# Write merged file
with open(out_file, 'w', newline='\n') as f:
if ext1 in ['.cpp', '.cc', '.cxx', '.c']:
# Write C++ content with fence tokens for the other language
f.write(f"#if 0\n{open_fence(ext2)}\n#endif\n")
for line in content1:
f.write(line + '\n')
f.write(f"#if 0\n{close_fence(ext2)}\n#endif\n")
# Write non-C++ content within #if 0 block
f.write("#if 0\n")
for line in content2:
f.write(line + '\n')
f.write("#endif\n")
elif ext2 in ['.cpp', '.cc', '.cxx', '.c']:
# Write C++ content with fence tokens for the other language
f.write(f"#if 0\n{open_fence(ext1)}\n#endif\n")
for line in content2:
f.write(line + '\n')
f.write(f"#if 0\n{close_fence(ext1)}\n#endif\n")
# Write non-C++ content within #if 0 block
f.write("#if 0\n")
for line in content1:
f.write(line + '\n')
f.write("#endif\n")
else:
print("Error: No C/C++ file in pair")
return 1
if verbose: print(f"Merged into {out_file}")
return 0
if __name__ == "__main__":
sys.exit(main())
#endif