|
| 1 | +import argparse |
| 2 | +import os |
| 3 | +import shutil |
| 4 | +import subprocess |
| 5 | +import sys |
| 6 | +import tempfile |
| 7 | + |
| 8 | + |
| 9 | +def check_binary_available(binary_name): |
| 10 | + try: # Pass version arg to expect any "wait for input" situations |
| 11 | + subprocess.run([binary_name, '--version'], capture_output=True, check=True) |
| 12 | + return True |
| 13 | + except (subprocess.CalledProcessError, FileNotFoundError): |
| 14 | + return False |
| 15 | + |
| 16 | + |
| 17 | +def main(): |
| 18 | + parser = argparse.ArgumentParser(description='Compare formatted source files.') |
| 19 | + parser.add_argument('--golden-dir', required=True, help='Golden directory (e.g., ${CMAKE_CURRENT_SOURCE_DIR}/output)') |
| 20 | + parser.add_argument('--generated-dir', required=True, help='Generated directory (e.g., ${CMAKE_CURRENT_BINARY_DIR}/src)') |
| 21 | + args = parser.parse_args() |
| 22 | + |
| 23 | + if not check_binary_available('clang-format'): |
| 24 | + print("Error: clang-format is not available in PATH", file=sys.stderr) |
| 25 | + sys.exit(1) |
| 26 | + |
| 27 | + if not check_binary_available('diff'): |
| 28 | + print("Error: diff is not available in PATH", file=sys.stderr) |
| 29 | + sys.exit(1) |
| 30 | + |
| 31 | + # Create temporary directory in /tmp/ |
| 32 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 33 | + golden_copy = os.path.join(tmpdir, 'golden') |
| 34 | + generated_copy = os.path.join(tmpdir, 'generated') |
| 35 | + shutil.copytree(args.golden_dir, golden_copy) |
| 36 | + shutil.copytree(args.generated_dir, generated_copy) |
| 37 | + |
| 38 | + extensions = ('.hpp', '.cpp', '.ipp') |
| 39 | + for root, _, files in os.walk(tmpdir): |
| 40 | + for file in files: |
| 41 | + if file.lower().endswith(extensions): |
| 42 | + file_path = os.path.join(root, file) |
| 43 | + subprocess.run(['clang-format', '-i', file_path], check=True) |
| 44 | + |
| 45 | + result = subprocess.run([ |
| 46 | + 'diff', '-uNrpB', |
| 47 | + golden_copy, |
| 48 | + generated_copy |
| 49 | + ], capture_output=True, text=True) |
| 50 | + |
| 51 | + if result.returncode != 0: |
| 52 | + print(result.stdout) |
| 53 | + print(result.stderr, file=sys.stderr) |
| 54 | + |
| 55 | + sys.exit(result.returncode) # Diff returns 0 if files are the same, 1 if they differ |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == '__main__': |
| 59 | + main() |
0 commit comments