import dataclasses import os import pathlib import stat import sys import typing from rule_hook.rules import Breach from rule_hook.git import existing, git from failure import Failure from utc_stamp import utc LOG = "rule-overrides.tsv" @dataclasses.dataclass(frozen=True) class Entry: """One line of the log, its fields tab-separated in this order.""" at: str branch: str # The commit checked out when the override let its call through; empty on a branch with no commit yet. commit: str rule: str reason: str what: str def line(self) -> str: return "\t".join(" ".join(field.split()) for field in dataclasses.astuple(self)) + "\n" def parsed_entry(line: str) -> Entry | None: fields = line.rstrip("\n").split("\t") return Entry(*fields) if len(fields) == len(dataclasses.fields(Entry)) else None def this_chunks(entry: Entry, reflog: set[str], branch: str, on_default: typing.Callable[[str], bool]) -> bool: """Whether the override is the current branch's: its commit is in the branch's reflog, which keeps a commit an amend or a rebase replaced, follows `git branch -m`, and holds no other branch's commit.""" if entry.commit == "": return True # The default branch's commits are in every branch's reflog, so such a line counts only under the branch's own name: one logged before the branch's first commit. return entry.commit in reflog and (entry.branch == branch or not on_default(entry.commit)) @dataclasses.dataclass(frozen=True) class Log: path: pathlib.Path branch: str head: str def log_path(directory: str) -> Log | Failure | None: """Where an override in this directory is logged; None outside any git checkout.""" directory = existing(directory) if not any((parent / ".git").exists() for parent in [pathlib.Path(directory), *pathlib.Path(directory).parents]): return None common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir") branch = git(directory, "branch", "--show-current") for found in (common, branch): if isinstance(found, Failure): return found head = git(directory, "rev-parse", "--verify", "--quiet", "HEAD") return Log(pathlib.Path(str(common)) / LOG, str(branch) or "HEAD", "" if isinstance(head, Failure) else head) def write_override(log: Log, entry: Entry) -> Failure | None: try: # No symlink, and no FIFO to hang on: the checkout, and so its git directory, may come from anyone. descriptor = os.open(log.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) except OSError as failure: return Failure(str(failure)) try: if not stat.S_ISREG(os.fstat(descriptor).st_mode): return Failure(f"{log.path} is no regular file") os.write(descriptor, entry.line().encode("utf-8")) except OSError as failure: return Failure(str(failure)) finally: os.close(descriptor) return None def logged(log: Log, breach: Breach, reason: str, what: str, now: float) -> Entry: return Entry(utc(now), log.branch, log.head, breach.rule, reason, what) def print_overrides(directory: str) -> int: common = git(directory, "rev-parse", "--path-format=absolute", "--git-common-dir") if isinstance(common, Failure): print(f"rule-hook overrides runs in a git checkout: {common.reason}", file=sys.stderr) return 1 found = git(directory, "branch", "--show-current") branch = found if isinstance(found, str) and found else "HEAD" reflog = git(directory, "reflog", "show", "--format=%H", branch) head = git(directory, "rev-parse", "HEAD") # A reflog missing HEAD is off or expired, and would hide this chunk's overrides. unread = reflog if isinstance(reflog, Failure) else head if isinstance(head, Failure) else None if head in reflog.split() else Failure("it does not hold HEAD") if unread: print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {unread.reason}", file=sys.stderr) return 1 default = default_branch(directory) log = pathlib.Path(common) / LOG entries = [parsed_entry(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else [] on_default = (lambda commit: holds(directory, default, commit)) if default else (lambda commit: False) for entry in entries: if entry and this_chunks(entry, set(str(reflog).split()), branch, on_default): print(entry.line(), end="") return 0 def default_branch(directory: str) -> str | None: return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None) def holds(directory: str, descendant: str, ancestor: str) -> bool: return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)