|
| 1 | +"""Hook to check for patterns in staged changes.""" |
| 2 | + |
| 3 | +import argparse |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +from collections.abc import Sequence |
| 7 | +from pathlib import Path |
| 8 | +from typing import Union |
| 9 | + |
| 10 | + |
| 11 | +def main(argv: Union[Sequence[str], None] = None) -> int: |
| 12 | + """Function to check for patterns in staged changes.""" |
| 13 | + parser = argparse.ArgumentParser() |
| 14 | + parser.add_argument("filenames", nargs="*", help="Filenames to check") |
| 15 | + args = parser.parse_args(argv) |
| 16 | + |
| 17 | + # Path to current script |
| 18 | + script_dir = Path(__file__).resolve().parent |
| 19 | + pattern_file = script_dir / "patterns.txt" |
| 20 | + |
| 21 | + # Get patterns |
| 22 | + with pattern_file.open("r") as f: |
| 23 | + lines = [ |
| 24 | + line.partition("#")[0].rstrip() |
| 25 | + for line in f |
| 26 | + if line.partition("#")[0].rstrip() |
| 27 | + ] |
| 28 | + COMPILED_PATTERN = [(line, re.compile(line)) for line in lines] |
| 29 | + |
| 30 | + violations = [] |
| 31 | + for filename in args.filenames: |
| 32 | + with open(filename, "r", encoding="utf-8", errors="ignore") as f: |
| 33 | + for lineno, line in enumerate(f, 1): |
| 34 | + for pattern_str, pattern in COMPILED_PATTERN: |
| 35 | + if pattern.search(line): |
| 36 | + violations.append((filename, lineno, pattern_str, line.strip())) |
| 37 | + |
| 38 | + violations_commiter = [] |
| 39 | + # Get commit metadata |
| 40 | + metadata_fields = { |
| 41 | + "Author Name": subprocess.getoutput("git config user.name"), |
| 42 | + "Author Email": subprocess.getoutput("git config user.email"), |
| 43 | + } |
| 44 | + |
| 45 | + for label, value in metadata_fields.items(): |
| 46 | + for pattern_str, pattern in COMPILED_PATTERN: |
| 47 | + if pattern.search(value): |
| 48 | + violations_commiter.append(f"[{label}] {value.strip()}") |
| 49 | + break |
| 50 | + |
| 51 | + if violations or violations_commiter: |
| 52 | + print("--") |
| 53 | + print("Pattern(s) found:") |
| 54 | + print("--") |
| 55 | + for filename, lineno, pattern_str, line in violations: |
| 56 | + print(f"Match in {filename}:{lineno} -> pattern: '{pattern_str}'") |
| 57 | + print(f"Line: {line}") |
| 58 | + print("--") |
| 59 | + for v in violations_commiter: |
| 60 | + print(f"Match in commit metadata -> {v}") |
| 61 | + return 1 |
| 62 | + else: |
| 63 | + return 0 |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + raise SystemExit(main()) |
0 commit comments