lib/checks/check-readme-edits.py

105 lines · 3533 bytes

  1"""
  2Fails if the PR directly edits the auto-generated section of the README.
  3The generated section is between <!-- awesome-privacy-start --> and <!-- awesome-privacy-end -->.
  4"""
  5
  6import argparse
  7import os
  8import re
  9import subprocess
 10import sys
 11
 12PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
 13README_PATH = ".github/README.md"
 14README_ABS = os.path.join(PROJECT_ROOT, README_PATH)
 15
 16# Exit codes
 17EXIT_PASS = 0
 18EXIT_FAIL = 1
 19EXIT_RUNTIME_ERROR = 2
 20
 21# ANSI color helpers
 22_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
 23red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
 24green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
 25
 26
 27def get_changed_files(base_ref):
 28    result = subprocess.run(
 29        ["git", "diff", "--name-only", f"{base_ref}..HEAD"],
 30        capture_output=True, text=True, check=True,
 31        cwd=PROJECT_ROOT,
 32    )
 33    return result.stdout.strip().splitlines()
 34
 35
 36def get_marker_lines():
 37    """Find the line numbers of the start/end markers in the README."""
 38    try:
 39        with open(README_ABS, "r") as f:
 40            lines = f.readlines()
 41    except FileNotFoundError:
 42        return None, None
 43
 44    start_line = None
 45    end_line = None
 46    for i, line in enumerate(lines, start=1):
 47        if "<!-- awesome-privacy-start -->" in line:
 48            start_line = i
 49        if "<!-- awesome-privacy-end -->" in line:
 50            end_line = i
 51
 52    return start_line, end_line
 53
 54
 55def get_changed_line_numbers(base_ref):
 56    """Parse git diff hunk headers to find which lines were changed in the README."""
 57    result = subprocess.run(
 58        ["git", "diff", "-U0", f"{base_ref}..HEAD", "--", README_PATH],
 59        capture_output=True, text=True, check=True,
 60        cwd=PROJECT_ROOT,
 61    )
 62
 63    changed_lines = []
 64    for line in result.stdout.splitlines():
 65        # Match hunk headers like @@ -10,5 +12,7 @@
 66        match = re.match(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line)
 67        if match:
 68            start = int(match.group(1))
 69            count = int(match.group(2)) if match.group(2) else 1
 70            for n in range(start, start + count):
 71                changed_lines.append(n)
 72
 73    return changed_lines
 74
 75def main():
 76    parser = argparse.ArgumentParser(description="Check for direct README edits to generated section")
 77    parser.add_argument("--base-ref", required=True, help="Base git ref to diff against")
 78    args = parser.parse_args()
 79
 80    # Skip if README wasn't changed
 81    changed_files = get_changed_files(args.base_ref)
 82    if README_PATH not in changed_files:
 83        print(green("README not modified, skipping."))
 84        sys.exit(EXIT_PASS)
 85
 86    # Find marker lines
 87    start_line, end_line = get_marker_lines()
 88    if start_line is None or end_line is None:
 89        print("Could not find generated-section markers in README, skipping check.")
 90        sys.exit(EXIT_PASS)
 91
 92    # Check if any changed lines fall within the generated section
 93    changed_lines = get_changed_line_numbers(args.base_ref)
 94    for line_num in changed_lines:
 95        if start_line <= line_num <= end_line:
 96            print(red("Direct edits to the generated section of the README are not allowed."), file=sys.stderr)
 97            print(red("Edit awesome-privacy.yml instead and the README will be regenerated."), file=sys.stderr)
 98            sys.exit(EXIT_FAIL)
 99
100    print(green("README changes are outside the generated section, OK."))
101    sys.exit(EXIT_PASS)
102
103
104if __name__ == "__main__":
105    main()