|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Report focused pytest guidance for changed paths under tests/.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import os |
| 8 | +import shlex |
| 9 | +import subprocess |
| 10 | +import sys |
| 11 | +from collections.abc import Iterable |
| 12 | +from pathlib import PurePosixPath |
| 13 | + |
| 14 | + |
| 15 | +def parse_paths(raw_paths: bytes) -> list[str]: |
| 16 | + """Decode the NUL-delimited output of ``git diff --name-only -z``.""" |
| 17 | + return [os.fsdecode(path) for path in raw_paths.split(b"\0") if path] |
| 18 | + |
| 19 | + |
| 20 | +def changed_paths_from_merge_base(base_sha: str, head_sha: str) -> list[str]: |
| 21 | + """Return changed ``tests/`` paths using GitHub PR three-dot semantics. |
| 22 | +
|
| 23 | + GitHub PR changed files are based on the merge base and the PR head, not a |
| 24 | + direct endpoint diff between the current base branch tip and the PR head. |
| 25 | + Using the direct endpoint diff can include files changed only on the base |
| 26 | + branch when the PR branch is stale. |
| 27 | + """ |
| 28 | + merge_base = subprocess.check_output( |
| 29 | + ["git", "merge-base", base_sha, head_sha], |
| 30 | + stderr=subprocess.DEVNULL, |
| 31 | + ).strip() |
| 32 | + raw_paths = subprocess.check_output( |
| 33 | + [ |
| 34 | + "git", |
| 35 | + "diff", |
| 36 | + "--name-only", |
| 37 | + "--diff-filter=ACMRT", |
| 38 | + "-z", |
| 39 | + os.fsdecode(merge_base), |
| 40 | + head_sha, |
| 41 | + "--", |
| 42 | + "tests/", |
| 43 | + ], |
| 44 | + ) |
| 45 | + return parse_paths(raw_paths) |
| 46 | + |
| 47 | + |
| 48 | +def select_test_paths(paths: Iterable[str]) -> list[str]: |
| 49 | + """Return unique, repository-relative paths contained by tests/.""" |
| 50 | + selected: set[str] = set() |
| 51 | + for raw_path in paths: |
| 52 | + path = PurePosixPath(raw_path) |
| 53 | + if path.is_absolute() or ".." in path.parts: |
| 54 | + continue |
| 55 | + parts = tuple(part for part in path.parts if part != ".") |
| 56 | + if len(parts) >= 2 and parts[0] == "tests": |
| 57 | + selected.add(PurePosixPath(*parts).as_posix()) |
| 58 | + return sorted(selected) |
| 59 | + |
| 60 | + |
| 61 | +def is_pytest_file(path: str) -> bool: |
| 62 | + """Return whether a changed path follows this repository's pytest naming.""" |
| 63 | + name = PurePosixPath(path).name |
| 64 | + return name.endswith(".py") and ( |
| 65 | + name.startswith("test_") or name.endswith("_test.py") |
| 66 | + ) |
| 67 | + |
| 68 | + |
| 69 | +def pytest_command(paths: Iterable[str]) -> str: |
| 70 | + """Build a copyable pytest command for changed runnable test files.""" |
| 71 | + command = ["python3", "-m", "pytest", "-q", *paths] |
| 72 | + return shlex.join(command) |
| 73 | + |
| 74 | + |
| 75 | +def format_report(paths: Iterable[str]) -> str: |
| 76 | + """Format focused guidance for CI logs and the workflow summary.""" |
| 77 | + changed_paths = select_test_paths(paths) |
| 78 | + runnable_paths = [path for path in changed_paths if is_pytest_file(path)] |
| 79 | + lines = ["## Focused test guidance (report-only)", ""] |
| 80 | + if not changed_paths: |
| 81 | + lines.append("No changed paths under `tests/`.") |
| 82 | + else: |
| 83 | + lines.extend(["Changed paths under `tests/`:", ""]) |
| 84 | + lines.extend(f"- `{path}`" for path in changed_paths) |
| 85 | + lines.extend(["", "Suggested focused validation:", ""]) |
| 86 | + if runnable_paths: |
| 87 | + lines.append(f"```sh\n{pytest_command(runnable_paths)}\n```") |
| 88 | + else: |
| 89 | + lines.append("No directly runnable pytest files changed.") |
| 90 | + lines.extend( |
| 91 | + [ |
| 92 | + "", |
| 93 | + "This guidance does not infer tests from source changes. " |
| 94 | + "Existing blocking CI remains the source of truth.", |
| 95 | + ] |
| 96 | + ) |
| 97 | + return "\n".join(lines) |
| 98 | + |
| 99 | + |
| 100 | +def _parse_args(argv: list[str]) -> argparse.Namespace: |
| 101 | + parser = argparse.ArgumentParser( |
| 102 | + description="Report focused pytest guidance for changed tests/ paths.", |
| 103 | + ) |
| 104 | + parser.add_argument("--base-sha", help="Pull request base commit SHA.") |
| 105 | + parser.add_argument("--head-sha", help="Pull request head commit SHA.") |
| 106 | + return parser.parse_args(argv) |
| 107 | + |
| 108 | + |
| 109 | +def main(argv: list[str] | None = None) -> int: |
| 110 | + args = _parse_args(sys.argv[1:] if argv is None else argv) |
| 111 | + if bool(args.base_sha) != bool(args.head_sha): |
| 112 | + raise SystemExit("--base-sha and --head-sha must be provided together") |
| 113 | + |
| 114 | + if args.base_sha and args.head_sha: |
| 115 | + paths = changed_paths_from_merge_base(args.base_sha, args.head_sha) |
| 116 | + else: |
| 117 | + paths = parse_paths(sys.stdin.buffer.read()) |
| 118 | + |
| 119 | + print(format_report(paths)) |
| 120 | + return 0 |
| 121 | + |
| 122 | + |
| 123 | +if __name__ == "__main__": |
| 124 | + raise SystemExit(main()) |
0 commit comments