| 18 | |
| 19 | |
| 20 | def process_file(file, clang_format, write): |
| 21 | original_source = open(file, "r").read() |
| 22 | source = original_source |
| 23 | source = re.sub( |
| 24 | r"MGB_DEFINE(?P<r>([^\\]|\n)*?)// *{", r"class MGB_DEFINE\g<r>{", source |
| 25 | ) |
| 26 | source, count = re.subn( |
| 27 | r"(?<!#define )MGB_DEFINE(.*) +\\", r"class MGB_DEFINE\1{\\", source |
| 28 | ) |
| 29 | |
| 30 | result = subprocess.check_output( |
| 31 | [ |
| 32 | clang_format, |
| 33 | "-style=file", |
| 34 | "-verbose", |
| 35 | "-assume-filename={}".format(file), |
| 36 | # file, |
| 37 | ], |
| 38 | input=bytes(source.encode("utf-8")), |
| 39 | ) |
| 40 | |
| 41 | result = result.decode("utf-8") |
| 42 | if count: |
| 43 | result = re.sub( |
| 44 | r"class MGB_DEFINE(.*){( *)\\", r"MGB_DEFINE\1\2 \\", result |
| 45 | ) |
| 46 | result = re.sub(r"class MGB_DEFINE((.|\n)*?){", r"MGB_DEFINE\1// {", result) |
| 47 | |
| 48 | if write and original_source != result: |
| 49 | with tempfile.NamedTemporaryFile( |
| 50 | dir=os.path.dirname(file), delete=False |
| 51 | ) as tmp_file: |
| 52 | tmp_file.write(result.encode("utf-8")) |
| 53 | os.rename(tmp_file.name, file) |
| 54 | else: |
| 55 | ret_code = subprocess.run( |
| 56 | ["diff", "--color=always", file, "-"], input=bytes(result.encode("utf-8")), |
| 57 | ).returncode |
| 58 | |
| 59 | # man diff: 0 for same, 1 for different, 2 if trouble. |
| 60 | if ret_code == 2: |
| 61 | raise RuntimeError("format process (without overwrite) failed") |
| 62 | if ret_code != 0: |
| 63 | print(file) |
| 64 | global failed_files |
| 65 | failed_files.append(file) |
| 66 | |
| 67 | |
| 68 | def main(): |