|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import fnmatch |
| 4 | +import os |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | + |
| 8 | +CODEGEN_PHRASES = [ |
| 9 | + 'This file is generated', |
| 10 | +] |
| 11 | + |
| 12 | +IGNORE_PATTERNS = [ |
| 13 | + 'utils/*', # this script has the phrase in it |
| 14 | +] |
| 15 | + |
| 16 | +ERROR_MSG = """ |
| 17 | +ERROR: You have changed code-generated files. |
| 18 | +
|
| 19 | +If you edited these files by hand, your changes will be erased when the |
| 20 | +code-generator is run again. An SDK team member MUST update the code-gen |
| 21 | +templates with corresponding changes before merging this Pull Request. |
| 22 | +
|
| 23 | +You can ignore this error if you are in fact running the code generator. |
| 24 | +""" |
| 25 | + |
| 26 | + |
| 27 | +def main(): |
| 28 | + parser = argparse.ArgumentParser( |
| 29 | + description="Detect edits to code-generated files") |
| 30 | + parser.add_argument('--diff-branch', default='main', |
| 31 | + help="Branch/commit to diff against") |
| 32 | + parser.add_argument('--diff-repo', default='origin', |
| 33 | + help="Repository to diff against") |
| 34 | + args = parser.parse_args() |
| 35 | + |
| 36 | + # chdir to project root |
| 37 | + os.chdir(os.path.join(os.path.dirname(__file__), '..')) |
| 38 | + |
| 39 | + # get all files with diffs |
| 40 | + git_cmd = ['git', 'diff', '--name-only', |
| 41 | + f"{args.diff_repo}/{args.diff_branch}"] |
| 42 | + git_result = subprocess.run(git_cmd, check=True, stdout=subprocess.PIPE) |
| 43 | + diff_files = git_result.stdout.decode().splitlines() |
| 44 | + |
| 45 | + # figure out which files were code-generated |
| 46 | + print('Checking files with diffs...') |
| 47 | + any_codegen = False |
| 48 | + for filepath in diff_files: |
| 49 | + is_codegen = False |
| 50 | + ignore = any([fnmatch.fnmatch(filepath, pat) |
| 51 | + for pat in IGNORE_PATTERNS]) |
| 52 | + if not ignore: |
| 53 | + with open(filepath) as f: |
| 54 | + text = f.read() |
| 55 | + for phrase in CODEGEN_PHRASES: |
| 56 | + if phrase in text: |
| 57 | + is_codegen = True |
| 58 | + any_codegen = True |
| 59 | + break |
| 60 | + if is_codegen: |
| 61 | + print(f" ⛔️ GENERATED - {filepath}") |
| 62 | + elif ignore: |
| 63 | + print(f" ✅ ignored - {filepath}") |
| 64 | + else: |
| 65 | + print(f" ✅ normal - {filepath}") |
| 66 | + |
| 67 | + if any_codegen: |
| 68 | + print(ERROR_MSG) |
| 69 | + sys.exit(-1) |
| 70 | + else: |
| 71 | + print("No code-generated files were changed.") |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == '__main__': |
| 75 | + main() |
0 commit comments