42 lines
2.1 KiB
Python
42 lines
2.1 KiB
Python
import dataclasses
|
|
import posixpath
|
|
|
|
from failure import Failure
|
|
from rule_hook.file_text import read
|
|
from rule_hook.git import guarded_git
|
|
from rule_hook.rules import Breach, file_breaches
|
|
|
|
# settings.json gives rule-hook 30 seconds; a file past this size is no source file, and reading it would eat them.
|
|
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 stands in for it. 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 them. Deleted files and files that are no UTF-8 text have no added text. A breach carries its file's text, so a marker in the file overrides it, as in an Edit."""
|
|
top = guarded_git(directory, "rev-parse", "--show-toplevel")
|
|
if isinstance(top, Failure):
|
|
return []
|
|
changed = guarded_git(top, "diff", "-z", "--name-only", "--no-renames", "--diff-filter=d", "HEAD")
|
|
# A checkout with no commit has no HEAD: its index is what differs.
|
|
changed = guarded_git(top, "diff", "-z", "--name-only", "--cached", "--no-renames", "--diff-filter=d") if isinstance(changed, Failure) else changed
|
|
untracked = guarded_git(top, "ls-files", "-z", "--others", "--exclude-standard")
|
|
names = sorted({name for listing in (changed, untracked) if not isinstance(listing, Failure) for name in listing.split("\0") if name})
|
|
breaches = []
|
|
for name in names:
|
|
path = posixpath.join(top, name)
|
|
after = read(path) if size(path) <= MAX_BYTES else ""
|
|
before = guarded_git(top, "show", f"HEAD:{name}")
|
|
before = "" if isinstance(before, Failure) else before
|
|
known = set(before.splitlines())
|
|
added = "\n".join(line for line in after.splitlines() if line not in known)
|
|
breaches += [dataclasses.replace(breach, marked=after) for breach in file_breaches(path, before, added, after)] if added else []
|
|
return breaches
|
|
|
|
|
|
def size(path: str) -> int:
|
|
try:
|
|
return posixpath.getsize(path)
|
|
except OSError:
|
|
return 0
|