import dataclasses import os import pathlib import stat import sys import typing from rule_hook.rules import Breach from git_repo import default_ref 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 LogLine: """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) -> LogLine | None: fields = line.rstrip("\n").split("\t") return LogLine(*fields) if len(fields) == len(dataclasses.fields(LogLine)) else None def this_chunks(entry: LogLine, 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 holds every commit the branch has had. So: - an override logged at c1 still counts after an amend or a rebase replaced c1 with c2; - one logged under the branch's old name counts after `git branch -m`, which carries the reflog over; - one logged on another branch, at a commit this reflog lacks, doesn't count; - one logged at a default-branch commit, such as the one the branch started from, sits in the reflogs of other branches too, so it counts only under this branch's own name; - one logged before any commit existed, with an empty commit, counts on every branch.""" if entry.commit == "": return True 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: LogLine) -> 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) -> LogLine: return LogLine(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") unread = unread_reflog(reflog, 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_ref(directory, guarded=True) 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: False) if isinstance(default, Failure) else (lambda commit: holds(directory, default, commit)) for entry in entries: if entry and this_chunks(entry, set(str(reflog).split()), branch, on_default): print(entry.line(), end="") return 0 def unread_reflog(reflog: str | Failure, head: str | Failure) -> Failure | None: if isinstance(reflog, Failure): return reflog if isinstance(head, Failure): return head # A reflog missing HEAD is off or expired, and would hide this chunk's overrides. return None if head in reflog.split() else Failure("it does not hold HEAD") def holds(directory: str, descendant: str, ancestor: str) -> bool: return bool(ancestor) and not isinstance(git(directory, "merge-base", "--is-ancestor", ancestor, descendant), Failure)