64 lines
3.7 KiB
Python
64 lines
3.7 KiB
Python
import dataclasses
|
|
import posixpath
|
|
|
|
from rule_hook.rules import Breach, file_breaches
|
|
from failure import Failure
|
|
from git_cli import git_repo
|
|
from rule_hook.git import guarded_git
|
|
from rule_hook.file_text import read
|
|
|
|
# settings.json gives rule-hook 30 seconds; a file past this size is not source code, and reading it would use them up.
|
|
MAX_BYTES = 1_000_000
|
|
|
|
|
|
def committed_file_breaches(directory: str) -> list[Breach]:
|
|
"""The breaches of file_breaches in the files a commit in directory's checkout would commit.
|
|
|
|
A file a Bash command wrote reaches no Edit or Write check, so the commit checks the file instead. The files are those that differ from HEAD in the index or the work tree, or that are untracked and not ignored: the hook runs before a `git add` earlier in the same command, so the index alone would miss those files. A tracked file is checked as the index holds it and as the work tree does, since the commit takes the index. A deleted file, or one that is not UTF-8 text, has no added text. A breach carries the lines its file adds, so a marker among them overrides it, as in a Write; a marker the file already held doesn't."""
|
|
top = guarded_git(directory, "rev-parse", "--show-toplevel")
|
|
if isinstance(top, Failure):
|
|
return []
|
|
tracked = tracked_names(top)
|
|
untracked = guarded_git(top, "ls-files", "-z", "--others", "--exclude-standard")
|
|
breaches: list[Breach] = []
|
|
for name in sorted(tracked | (set() if isinstance(untracked, Failure) else names_in(untracked))):
|
|
path = posixpath.join(top, name)
|
|
# An untracked file has neither a version in HEAD nor one in the index. A tracked file costs two git calls, about 4 ms each: a commit of 3000 changed files uses 13 of the hook's 30 seconds.
|
|
before = blob(top, "HEAD", name) if name in tracked else ""
|
|
for after in dict.fromkeys([read(path) if size(path) <= MAX_BYTES else "", blob(top, "", name) if name in tracked else ""]):
|
|
known = set(before.splitlines())
|
|
added = "\n".join(line for line in after.splitlines() if line not in known)
|
|
breaches += [dataclasses.replace(breach, marked=added) for breach in file_breaches(path, before, added, after)]
|
|
# The work-tree copy and the index copy of a file can breach the same way; the first found, the work tree's, stands.
|
|
first: dict[tuple[str, str], Breach] = {}
|
|
for breach in breaches:
|
|
first.setdefault((breach.rule, breach.detail), breach)
|
|
return list(first.values())
|
|
|
|
|
|
def tracked_names(top: str) -> set[str]:
|
|
"""The tracked files that differ from HEAD in the index or the work tree, deleted ones left out. It lists with diff-index, which neither hashes the work tree nor enters a submodule: either would run a clean filter that the checkout's config names, before the call is allowed."""
|
|
listings = [guarded_git(top, "diff-index", "-z", "--name-only", "--no-renames", "--diff-filter=d", "--ignore-submodules", *cached, "HEAD") for cached in ([], ["--cached"])]
|
|
if any(isinstance(listing, Failure) for listing in listings):
|
|
# A checkout with no commit has no HEAD: every file in its index is new.
|
|
listing = guarded_git(top, "ls-files", "-z")
|
|
return set() if isinstance(listing, Failure) else names_in(listing)
|
|
return {name for listing in listings if not isinstance(listing, Failure) for name in names_in(listing)}
|
|
|
|
|
|
def names_in(listing: str) -> set[str]:
|
|
return {name for name in listing.split("\0") if name}
|
|
|
|
|
|
def blob(top: str, commit: str, name: str) -> str:
|
|
"""name's text in the commit, or in the index where commit is empty; "" where there is none."""
|
|
shown = git_repo.git("show", f"{commit}:{name}", cwd=top, guarded=True)
|
|
return "" if isinstance(shown, Failure) or len(shown) > MAX_BYTES else shown
|
|
|
|
|
|
def size(path: str) -> int:
|
|
try:
|
|
return posixpath.getsize(path)
|
|
except OSError:
|
|
return 0
|