lib/checks/check-readme-edits.py

110 lines · 3565 bytes

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