import hashlib import pathlib import subprocess import sys from rule_hook.rules import Breach from failure import Failure from rule_hook.git import guarded_git from release_plan import ranking # The checkout this hook runs from: bin/rule_hook/ sits two folders below it. OWN = pathlib.Path(__file__).resolve().parents[2] # settings.json gives rule-hook 30 seconds; rank_todo.py --check takes about a tenth of one. OWN_CHECK_SECONDS = 20 def todo_breaches(directory: str, own: pathlib.Path = OWN) -> list[Breach]: top = guarded_git(directory, "rev-parse", "--show-toplevel") if isinstance(top, Failure) or not (pathlib.Path(top) / "todo.md").is_file(): return [] todo = pathlib.Path(top) / "todo.md" return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, own)] if changed(top, todo) else [] def check_failures(top: str, todo: pathlib.Path, own: pathlib.Path) -> list[str]: """Why rank_todo.py --check fails on todo. A checkout of the repo the hook runs from checks with its own bin/rank_todo.py, so a branch that changes the table's shape is held to its own rules. Any other checkout checks with the hook's ranking: running its script would run its code before every commit.""" script = pathlib.Path(top) / "bin" / "rank_todo.py" if not script.is_file() or not same_repo(top, own): return ranking.check_failures(todo) try: ran = subprocess.run([sys.executable, str(script), "--check", str(todo)], capture_output=True, cwd=top, text=True, timeout=OWN_CHECK_SECONDS) except subprocess.TimeoutExpired: return [f"{script} --check did not finish in {OWN_CHECK_SECONDS} seconds"] except OSError as failure: return [f"{script} --check could not run: {failure}"] if ran.returncode == 0: return [] return ran.stderr.splitlines() or [f"{script} --check failed with exit {ran.returncode} and printed nothing"] def same_repo(top: str, own: pathlib.Path) -> bool: """Whether the checkout's history and the hook's share a root commit.""" theirs, mine = guarded_git(top, "rev-list", "--max-parents=0", "HEAD"), guarded_git(str(own), "rev-list", "--max-parents=0", "HEAD") return not isinstance(theirs, Failure) and not isinstance(mine, Failure) and bool(set(theirs.split()) & set(mine.split())) def changed(top: str, todo: pathlib.Path) -> bool: """Whether todo.md differs from the index or the index from HEAD: any change, staged or not, since the hook runs before a `git add` earlier in the same command.""" # Hashed here, never by `git status`, which would run a clean filter the checkout's own config names before the call is allowed. staged, committed = guarded_git(top, "rev-parse", ":todo.md"), guarded_git(top, "rev-parse", "HEAD:todo.md") algorithm = guarded_git(top, "rev-parse", "--show-object-format") content = todo.read_bytes() worktree = hashlib.new("sha1" if isinstance(algorithm, Failure) else algorithm, b"blob %d\0" % len(content) + content).hexdigest() return isinstance(staged, Failure) or staged != worktree or staged != committed