gate_hygiene.py¶
scripts/gate_hygiene.py
REFUSE TO CALL THE GATE GREEN WHEN IT COULD NOT SEE THE TREE.
_report_missing_hook
None gate_hygiene._report_missing_hook(bool enforced)
Report that the commit-time hook is absent, and whether that is being enforced.
Source · 19 lines
def _report_missing_hook(enforced: bool) -> None:
"""SAYS WHICH IT DID. A check that sometimes fails and sometimes only mentions, without
stating which, teaches the reader to skim it — and then the one time it mattered reads
exactly like the times it did not.
@brief Print the missing-hook finding.
@param enforced Whether it fails the run.
@return None.
@version 1
"""
severity = "not installed" if enforced else "not installed (not enforced under CI)"
print(
f"pre-commit's commit-time hook is {severity}, so nothing gates a commit in this "
"checkout and every green is a human remembering to run one. Install it with:\n"
" .venv/bin/pre-commit install",
file=sys.stderr,
)
Activity · 2 steps
Flows
_report_unseen
None gate_hygiene._report_unseen(list[str] unseen)
Report untracked files the hooks would have covered.
Source · 19 lines
def _report_unseen(unseen: list[str]) -> None:
"""Every path is named, never a count alone. "3 files" sends the reader to `git status` to
work out which three; the whole value of the check is which.
@brief Print the unseen paths.
@param unseen The paths.
@return None.
@version 1
"""
print(
f"{len(unseen)} untracked file(s) lie inside the hooks' scope, so "
f"`pre-commit run --all-files` reports nothing about them while a commit would carry "
f"them. Stage them and re-run the gate, or exclude them deliberately:",
file=sys.stderr,
)
for path in unseen:
print(f" {path}", file=sys.stderr)
Activity · 3 steps
Flows
commit_hook_installed
bool gate_hygiene.commit_hook_installed(Path repo)
Version 2 (gh#64): the hooks directory is git's answer ( rev-parse --git-path hooks ), so a linked worktree and core.hooksPath are found where git actually runs the hook from.
Called by main, test_a_foreign_hook_does_not_count_as_the_gate, test_a_linked_worktree_sees_the_installed_hook, test_a_repository_without_the_commit_time_hook_is_reported, test_an_installed_pre_commit_hook_is_recognised, test_core_hooks_path_is_respected
Calls none
Source · 30 lines
def commit_hook_installed(repo: Path) -> bool:
"""Asks about CONTENT, not existence — see `_PRE_COMMIT_MARKERS`.
THE PATH IS ASKED OF GIT. It used to be built as `.git/hooks/pre-commit`, and in a linked
worktree `.git` is a FILE: the check failed even after `pre-commit install` — the remedy it
printed — had written the hook to git's common directory, so every commit from a worktree
failed. `git rev-parse --git-path hooks` follows the worktree to the common directory and
honours `core.hooksPath`. When git cannot answer, the answer is False: "cannot confirm".
@brief Is pre-commit's hook installed.
@param repo Repository root.
@return True when it is.
@version 2
"""
result = subprocess.run(
["git", "-C", str(repo), "rev-parse", "--git-path", "hooks"],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0 or not result.stdout.strip():
return False
hooks = Path(result.stdout.strip())
hook = (hooks if hooks.is_absolute() else repo / hooks) / "pre-commit"
if not hook.is_file():
return False
text = hook.read_text("utf-8", errors="replace")
return any(marker in text for marker in _PRE_COMMIT_MARKERS)
Activity · 9 steps
Flows
global_exclude
re.Pattern[str] | None gate_hygiene.global_exclude(Path config)
Parse the global exclude: regex out of a pre-commit config.
Called by test_the_guard_reads_this_repository_own_exclude_list, untracked_but_covered
Calls none
Source · 30 lines
def global_exclude(config: Path) -> re.Pattern[str] | None:
"""HAND-PARSED RATHER THAN VIA PYYAML, because the value wanted is the verbose `(?x)`
alternation exactly as written, and a YAML load would hand back a block scalar that still has
to be reassembled. The block is the indented run of lines after `exclude: |`, which is all
this needs to find.
Returns None when there is no `exclude:` key at all — absent, not empty. A caller that got an
empty pattern instead would silently treat an unreadable config as "nothing is excluded".
@brief Read the global exclude pattern.
@param config The config path.
@return Compiled pattern or None.
@version 1
"""
if not config.is_file():
return None
text = config.read_text("utf-8")
match = _EXCLUDE_HEADER.search(text)
if match is None:
return None
body: list[str] = []
for line in text[match.end() :].splitlines()[1:]:
## The block ends at the first line that is neither blank nor indented, which is the next
## top-level key.
if line.strip() and not line.startswith((" ", "\t")):
break
body.append(line.strip())
return re.compile("".join(body))
Activity · 12 steps
Flows
main
int gate_hygiene.main(list[str]|None argv=None, bool|None ci=None)
Print both findings and return the exit code the gate should take.
Called by test_a_missing_hook_does_not_fail_under_ci, test_an_untracked_covered_file_still_fails_under_ci, test_main_exit_code_follows_what_it_found
Calls _report_missing_hook, _report_unseen, commit_hook_installed, untracked_but_covered
Source · 39 lines
def main(argv: list[str] | None = None, ci: bool | None = None) -> int:
"""BOTH CHECKS ALWAYS RUN AND BOTH ARE ALWAYS REPORTED. Returning on the first failure would
hide the second, and these two are each other's context: an uninstalled hook is why an
untracked file reaches a commit at all.
**THE COMMIT-TIME CHECK IS NOT ENFORCED UNDER CI, AND THAT IS NOT A LOOPHOLE.** CI clones
fresh and invokes the gate explicitly, so `.git/hooks/pre-commit` is absent there by
construction and always will be. Enforcing it would fail every CI run and the check would be
deleted within a day — which is the real way a check dies. The claim it makes is about an
*interactive checkout*, where the gate runs only if something invokes it. It is still printed
under CI, so the finding never silently disappears.
The untracked check is enforced everywhere, because its claim holds everywhere: a file on disk
that git does not know about is invisible to the hooks whoever is running them.
Single exit point, by the returns-per-function limit this repository enforces.
@brief Run the hygiene checks.
@param argv Argument list.
@param ci CI override; read from the environment when None.
@return Process exit code.
@version 1
"""
args = list(sys.argv[1:] if argv is None else argv)
repo = Path(args[0]) if args else Path(__file__).resolve().parent.parent
in_ci = bool(os.environ.get("CI")) if ci is None else ci
unseen = untracked_but_covered(repo)
installed = commit_hook_installed(repo)
if unseen:
_report_unseen(unseen)
if not installed:
_report_missing_hook(enforced=not in_ci)
hook_fails = not installed and not in_ci
return 1 if (unseen or hook_fails) else 0
Activity · 11 steps
Flows
untracked_but_covered
list[str] gate_hygiene.untracked_but_covered(Path repo)
List untracked paths that the configured hooks would have covered.
Called by main, test_gitignored_file_is_not_reported, test_untracked_file_under_a_hook_covered_path_is_reported, test_untracked_file_under_the_global_exclude_is_not_reported
Calls global_exclude, untracked_paths
Source · 16 lines
def untracked_but_covered(repo: Path) -> list[str]:
"""The intersection that matters: on disk, not in the index, and not excluded. Those are the
files a `--all-files` run reports nothing about and a commit then carries.
@brief Untracked paths inside the hooks' scope.
@param repo Repository root.
@return The offending paths.
@version 1
"""
excluded = global_exclude(repo / ".pre-commit-config.yaml")
paths = untracked_paths(repo)
if excluded is None:
return paths
return [path for path in paths if not excluded.match(path)]
Activity · 5 steps
Flows
untracked_paths
list[str] gate_hygiene.untracked_paths(Path repo)
List the paths git reports as untracked, honouring ignore rules.
Source · 20 lines
def untracked_paths(repo: Path) -> list[str]:
"""`--exclude-standard` IS LOAD-BEARING. Without it this returns every ignored build artifact
and venv file, the guard becomes noise, and someone turns it off. A gitignored file is also
not a hole: the hooks never see it either, so there is no gap between what was checked and
what the commit carries.
@brief Untracked, non-ignored paths.
@param repo Repository root.
@return Repo-relative paths.
@version 1
"""
result = subprocess.run(
["git", "-C", str(repo), "ls-files", "--others", "--exclude-standard"],
capture_output=True,
text=True,
check=True,
)
return [line for line in result.stdout.splitlines() if line]