|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import sys |
| 4 | +import re |
| 5 | +import os |
| 6 | +import itertools |
| 7 | +from concurrent.futures import ProcessPoolExecutor |
| 8 | +import multiprocessing |
| 9 | +import threading |
| 10 | +import subprocess |
| 11 | + |
| 12 | +from makeqstrdefs import qstr_unescape, QSTRING_BLACK_LIST |
| 13 | + |
| 14 | +re_line = re.compile(r"#[line]*\s(\d+)\s\"([^\"]+)\"", re.DOTALL) |
| 15 | +re_qstr = re.compile(r'MP_QSTR_[_a-zA-Z0-9]+', re.DOTALL) |
| 16 | +re_translate = re.compile(r'translate\(\"((?:(?=(\\?))\2.)*?)\"\)', re.DOTALL) |
| 17 | + |
| 18 | +def write_out(fname, output_dir, output): |
| 19 | + if output: |
| 20 | + for m, r in [("/", "__"), ("\\", "__"), (":", "@"), ("..", "@@")]: |
| 21 | + fname = fname.replace(m, r) |
| 22 | + with open(output_dir + "/" + fname + ".qstr", "w") as f: |
| 23 | + f.write("\n".join(output) + "\n") |
| 24 | + |
| 25 | +def process_file(fname, output_dir, content): |
| 26 | + content = content.decode('utf-8', errors='ignore') |
| 27 | + output = [] |
| 28 | + for match in re_qstr.findall(content): |
| 29 | + name = match.replace('MP_QSTR_', '') |
| 30 | + if name not in QSTRING_BLACK_LIST: |
| 31 | + output.append('Q(' + qstr_unescape(name) + ')') |
| 32 | + for match in re_translate.findall(content): |
| 33 | + output.append('TRANSLATE("' + match[0] + '")') |
| 34 | + |
| 35 | + write_out(fname, output_dir, output) |
| 36 | + |
| 37 | + |
| 38 | +def checkoutput1(args): |
| 39 | + info = subprocess.run(args, check=True, stdout=subprocess.PIPE, input='') |
| 40 | + return info.stdout |
| 41 | + |
| 42 | +def preprocess(command, output_dir, fn): |
| 43 | + try: |
| 44 | + output = checkoutput1(command + [fn]) |
| 45 | + process_file(fn, output_dir, output) |
| 46 | + except Exception as e: |
| 47 | + print(e, file=sys.stderr) |
| 48 | + |
| 49 | +def maybe_preprocess(command, output_dir, fn): |
| 50 | + if subprocess.call(["grep", "-lqE", "(MP_QSTR|translate)", fn]) == 0: |
| 51 | + preprocess(command, output_dir, fn) |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + |
| 55 | + |
| 56 | + idx1 = sys.argv.index('--') |
| 57 | + idx2 = sys.argv.index('--', idx1+1) |
| 58 | + output_dir = sys.argv[1] |
| 59 | + check = sys.argv[2:idx1] |
| 60 | + always = sys.argv[idx1+1:idx2] |
| 61 | + command = sys.argv[idx2+1:] |
| 62 | + |
| 63 | + if not os.path.isdir(output_dir): |
| 64 | + os.makedirs(output_dir) |
| 65 | + |
| 66 | + # Mac and Windows use 'spawn'. Uncomment this during testing to catch spawn-specific problems on Linux. |
| 67 | + #multiprocessing.set_start_method("spawn") |
| 68 | + executor = ProcessPoolExecutor(max_workers=multiprocessing.cpu_count() + 1) |
| 69 | + executor.map(maybe_preprocess, itertools.repeat(command), itertools.repeat(output_dir), check) |
| 70 | + executor.map(preprocess, itertools.repeat(command), itertools.repeat(output_dir), always) |
| 71 | + executor.shutdown() |
0 commit comments