93 lines
5.2 KiB
Python
93 lines
5.2 KiB
Python
import functools
|
|
import hashlib
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
|
|
from rule_hook.rules import Breach
|
|
from failure import Failure
|
|
from plan_store.stores import file_plan
|
|
from git_cli.git_repo import git
|
|
from rule_hook.git import guarded_git
|
|
from project_config.settings import held, ProjectConfig
|
|
from project_config.main import located
|
|
|
|
|
|
# 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, home: pathlib.Path, own: pathlib.Path = OWN, seconds: float = OWN_CHECK_SECONDS) -> list[Breach]:
|
|
"""Why the plan of directory's project is not ranked, where the plan has changed; the plan is the todo.md its config names. directory may also be in a config's folder, a git repo of its own."""
|
|
top = guarded_git(directory, "rev-parse", "--show-toplevel")
|
|
if isinstance(top, Failure):
|
|
return []
|
|
held_here = held(pathlib.Path(top), home)
|
|
if held_here is not None:
|
|
return folder_breaches(top, held_here, own, seconds)
|
|
config = located(top, home, functools.partial(git, guarded=True))
|
|
if isinstance(config, Failure):
|
|
# A checkout whose todo.md changes with no config is one whose config is still to write. An unchanged todo.md may be a third party's, whose clone needs no config.
|
|
unconfigured = pathlib.Path(top) / "todo.md"
|
|
return [Breach("todo-rank-check", config.reason, top)] if unconfigured.is_file() and changed(top, unconfigured, "todo.md") else []
|
|
todo, tracked = config.plan_file, config.tracked("plan")
|
|
# A plan in Jira is no file, and Jira's backlog ranks it.
|
|
if todo is None or not todo.is_file():
|
|
return []
|
|
# A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call.
|
|
if tracked is not None and not changed(top, todo, tracked):
|
|
return []
|
|
return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, config, own, seconds)]
|
|
|
|
|
|
def folder_breaches(top: str, config: ProjectConfig | Failure, own: pathlib.Path, seconds: float) -> list[Breach]:
|
|
"""Why the plan kept in top, a config's folder, is not ranked, where the plan has changed in that folder's repo; ranked as for a commit in the project's checkout.
|
|
|
|
A config that fails to load doesn't block anything here, so that the commit that fixes it goes through."""
|
|
if isinstance(config, Failure):
|
|
return []
|
|
todo = config.plan_file
|
|
if todo is None or not todo.is_relative_to(config.folder):
|
|
return []
|
|
if not todo.is_file() or not changed(str(config.folder), todo, todo.relative_to(config.folder).as_posix()):
|
|
return []
|
|
return [Breach("todo-rank-check", line, top) for line in check_failures(str(config.top), todo, config, own, seconds)]
|
|
|
|
|
|
def check_failures(top: str, todo: pathlib.Path, config: ProjectConfig, own: pathlib.Path, seconds: float) -> 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 file_plan(config, todo).check()
|
|
try:
|
|
ran = subprocess.run([sys.executable, str(script), "--check", str(todo)], capture_output=True, cwd=top, text=True, timeout=seconds)
|
|
except subprocess.TimeoutExpired:
|
|
return [f"{script} --check did not finish in {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 no output"]
|
|
|
|
|
|
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, tracked: str) -> bool:
|
|
"""Whether todo, which git names tracked, 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", f":{tracked}"), guarded_git(top, "rev-parse", f"HEAD:{tracked}")
|
|
algorithm = guarded_git(top, "rev-parse", "--show-object-format")
|
|
try:
|
|
content = todo.read_bytes()
|
|
except OSError:
|
|
# An unreadable plan counts as changed, so the check runs and its breach says why the plan cannot be read. Raising here would end the hook with an exit that lets the commit through unchecked.
|
|
return True
|
|
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
|