"""Clean validation engine following SOLID principles.""" from __future__ import annotations import os import re import shlex import subprocess import sys import unicodedata from abc import ABC, abstractmethod from collections.abc import Iterable from dataclasses import dataclass, field from enum import IntEnum from fnmatch import fnmatchcase from typing import ClassVar from commit_check import ( DEFAULT_AI_DISCLOSURE_TRAILERS, DEPENDENCY_UPDATE_BOTS, GIT_MERGE_SUBJECT_PATTERN, GIT_REVERT_SUBJECT_PATTERN, ai_policy, ) from commit_check.ai_signatures import ( detect_ai_author, detect_ai_signatures, ) from commit_check.fixes import ( fix_branch_type, fix_conventional_header, fix_subject_case, fix_wip, signoff_trailer, strip_lines_containing, ) from commit_check.imperatives import IMPERATIVES, NON_IMPERATIVE_LOOKALIKES from commit_check.rule_builder import ValidationRule from commit_check.util import ( _print_failure, ci_source_commit, fetch_remote_ref, fetch_upstream_ref, format_size, get_branch_name, get_commit_author_identity, get_commit_files, get_commit_info, get_git_config_value, get_git_remotes, get_git_user_identity, get_pending_author_identity, get_push_commits, get_tags_at, get_upstream_branch, get_upstream_remote_sha, git_merge_base, git_rev_parse_verify, has_commits, print_error_header, print_quoted_message, read_commit_message_file, rejection_headline, ) _GIT_MERGE_SUBJECT = re.compile(GIT_MERGE_SUBJECT_PATTERN) _GIT_REVERT_SUBJECT = re.compile(GIT_REVERT_SUBJECT_PATTERN) def is_merge_subject(subject: str) -> bool: """Whether *subject* is one a merge tool wrote, not the author. The subject rules decline to judge these. A subject that merely starts with the word ("Merge lowercase parser tables") is the author's, and is judged like any other. """ return _GIT_MERGE_SUBJECT.match(subject) is not None def is_revert_subject(subject: str) -> bool: """Whether *subject* is one ``git revert`` wrote, not the author. 'Revert ""', or 'Reapply ""' for the revert of a revert. The quote is part of the match: "Revert the parser change" is the author's, and is judged like any other subject. """ return _GIT_REVERT_SUBJECT.match(subject) is not None # A work-in-progress marker at the start of the subject (CC010). "^" without # re.MULTILINE and "[ \t]*" rather than "\s*" keep the match on the first # line, so a body that merely mentions WIP is not a WIP commit. _WIP_MARKER = re.compile(r"^[ \t]*(?:\[wip\]|wip\b)", re.IGNORECASE) #: The git config key naming the person who will author the next commit. _USER_NAME = "user.name" class ValidationResult(IntEnum): """Validation result codes. ``SKIP`` means the validator declined to run — the author is on an ignore list, or there was nothing to check — as opposed to ``PASS``, which means the rule ran and found nothing to object to. Reporting a skip as a pass makes a bypassed policy indistinguishable from an enforced one, so the two are kept apart. Only ``FAIL`` is an error. ``validate_all`` returns ``PASS``/``FAIL`` explicitly rather than propagating this value, so the new member never reaches an exit code. """ PASS = 0 FAIL = 1 SKIP = 2 @dataclass(frozen=True) class ValidationContext: """Context for validation operations.""" stdin_text: str | None = None commit_file: str | None = None config: dict = field(default_factory=dict) no_banner: bool = False compact: bool = False push_upstream_fallback: bool = False # A git revision naming the commit under test. When set, message and # author checks read that commit -- the author is the commit's author, # never the local git config, because an existing commit's identity is # a fact about the commit rather than about whoever is running the # check. The CLI verifies the revision resolves before it gets here. # Last on purpose: positional construction predates it. rev: str | None = None # Per-run memo of get_commit_files() keyed by revision. The three file # rules each get their own validator, so without this they would re-run # the same git plumbing over the same commits three times. files_cache: dict[str, list[tuple[str, int]]] = field( default_factory=dict, repr=False, compare=False ) # Set when stdin_text is a piped commit message: checks with a value of # their own (branch, author, tags, push refs) then read git instead. stdin_is_message: bool = False # Set when stdin_text is the pre-push line rebuilt from pre-commit's # environment. pre-commit names one ref per push, the first that carries # commits the remote lacks, so a ref pushed alongside it -- a tag that # ``git push --follow-tags`` sends after a branch -- is not in the line. push_from_pre_commit: bool = False # Set by --ai-attribution-only and --pr-title: the text is not a commit # message (a pull request description or title), so advice must not tell # the reader to re-commit. not_a_commit: bool = False @property def piped_value(self) -> str | None: """stdin_text as a check's own value, or None when it is the message.""" return None if self.stdin_is_message else self.stdin_text @property def piped_name(self) -> str | None: """piped_value as the one name a branch or author check reads. None as well when stdin_text is the pre-push line rebuilt from pre-commit's environment: that names refs for the push checks run alongside, not a branch or an author, so these read git instead. """ return None if self.push_from_pre_commit else self.piped_value @dataclass class CheckOutcome: """Structured result of a single validation check. Returned by :meth:`ValidationEngine.validate_all_detailed` so that callers (e.g. ``--format json`` output, the Python API) can inspect individual check results without parsing human-readable terminal output. """ check: str # "pass" (the rule ran and was satisfied), "fail" (the rule ran and was # not), "warn" (the rule was not satisfied but is listed under ``warn`` # in the config, so it is reported and does not fail the run), or "skip" # (the rule never ran — ignored author, or nothing to check). A skip is # not a pass: it means the policy was bypassed, and collapsing the two # lets a run that validated nothing report success. status: str # The concrete value that was checked (subject, branch, author, ...), # populated on both pass and fail so consumers can report what was # validated even when the check succeeded. value: str = "" error: str = "" suggest: str = "" # The corrected value when the fix is unambiguous (a type's case, a WIP # marker, a missing trailer); empty when fixing it takes a judgment the # tool should not make. Consumers can offer it as a one-step correction. fix: str = "" rule_id: str = "" docs_url: str = "" # Why a skipped check did not run, when commit-check knows (the author # is on an ``ignore_authors`` list); empty otherwise. reason: str = "" def to_dict(self) -> dict[str, str]: """Serialise to a plain dict (suitable for JSON encoding).""" return { "rule_id": self.rule_id, "check": self.check, "status": self.status, "value": self.value, "error": self.error, "suggest": self.suggest, "fix": self.fix, "docs_url": self.docs_url, "reason": self.reason, } def overall_status(statuses: Iterable[str]) -> str: """Reduce per-check statuses to one of ``"pass"``/``"fail"``/``"skip"``. Takes plain status strings rather than a specific type so that every caller can share it: the CLI's ``--format json`` and the API's :class:`CheckOutcome` objects, and the API's combined paths (``validate_author`` with both inputs, ``validate_all``) which merge already-serialised check dicts. That breadth is the point. This rule had been copied into four places, and each copy defaulted to ``"pass"`` for anything that was not a failure — which is how a fully skipped run kept reporting success even after the skip status existed. ``"skip"`` requires that *every* check skipped: a single real verdict means something was actually validated. A run with no checks at all validated nothing either, so it is ``"skip"`` too, not ``"pass"``. Only ``"fail"`` is an error: a ``"warn"`` is a verdict the config asked to report without enforcing, so a run whose only findings are warnings passes. """ # all() of nothing is True, so an empty run reads as skipped. seen = list(statuses) if any(s == "fail" for s in seen): return "fail" if all(s == "skip" for s in seen): return "skip" return "pass" def count_warnings(statuses: Iterable[str]) -> int: """How many checks were reported as warnings rather than failures.""" return sum(1 for s in statuses if s == "warn") class BaseValidator(ABC): """Abstract base validator.""" def __init__(self, rule: ValidationRule): self.rule = rule # Set to True by the engine to suppress human-readable terminal # output while still collecting failure details: validate_all_detailed # never prints, validate_all prints the collected blocks itself once # every rule has run. self._suppress_output: bool = False # Used by _print_failure() when this validator prints for itself. self._no_banner: bool = False self._compact: bool = False # Populated by _print_failure() on every failure, regardless of mode. self._last_failure: dict[str, str] | None = None # The failure blocks as the printer takes them, (rule dict, value), # kept so the engine can print them after the header. self._failure_blocks: list[tuple[dict, str]] = [] # Populated by subclasses on every validation (pass or fail) with the # concrete value that was checked (subject, branch, author, ...), so # structured consumers (--format json, validate_all_detailed) can # report what was checked even when the check passed. self._checked_value: str = "" # Set by ValidationEngine.validate_all_detailed() to opt into value # collection. Text-mode validation skips the extra lookups (e.g. a # git subprocess for the branch name) and keeps values empty. self._collect_value: bool = False # Why the rule declined to run, when the reason is something the # user configured (an ignored author). A bare "skipped" leaves the # reader guessing whether the policy was bypassed on purpose. self._skip_reason: str = "" @abstractmethod def validate(self, context: ValidationContext) -> ValidationResult: """Perform validation and return result.""" @staticmethod def _resolve_current_author( context: ValidationContext, pending: bool = False ) -> str: """Resolve the relevant author identity based on validation mode. Two distinct modes: *Prospective message* (``stdin_text`` or ``commit_file`` is set, or *pending* is passed by a check that judges the next commit): the user is about to create a new commit. The last commit's author is unrelated — the relevant identity is the one git would record: ``GIT_AUTHOR_NAME`` when set (how a tool commits under its own name, and how the Action passes on the author of a commit it pipes in), else ``author.name``, else ``user.name``. *Existing commit* (no ``stdin_text``, no ``commit_file``): the last commit is the one being validated. Use its own author (``get_commit_info("an")``), not the local git config which may belong to a different person. """ if context.rev is not None: # An explicit revision names an existing commit; its author is a # fact about that commit, so the config never enters into it. return get_commit_info("an", context.rev) if pending or context.stdin_text is not None or context.commit_file is not None: return ( os.environ.get("GIT_AUTHOR_NAME", "").strip() or get_git_config_value("author.name") or get_git_config_value(_USER_NAME) or get_commit_info("an") ) return get_commit_info("an") or get_git_config_value(_USER_NAME) @staticmethod def _message_was_supplied(context: ValidationContext) -> bool: """Whether the caller named a message source rather than leaving it to git. Distinguishes "you asked me about this empty message" from "git had nothing to give me", which decide opposite answers: the first is a message that fails, the second is nothing to check. A commit_file that cannot be read counts as named even though the text then comes from git. That stays correct where it matters: the only way to reach an empty message from there is a HEAD commit whose message is genuinely empty, and rejecting that under allow_empty_commits = false is the verdict the rule exists to give. """ return ( context.stdin_text is not None or context.commit_file is not None or context.rev is not None ) @staticmethod def _get_commit_message(context: ValidationContext) -> str: """Get commit message from context or git.""" if context.stdin_text is not None: return context.stdin_text.strip() if context.commit_file: try: return read_commit_message_file(context.commit_file).strip() except FileNotFoundError: pass # Fallback to git log if context.rev is not None: subject = get_commit_info("s", context.rev) body = get_commit_info("b", context.rev) else: subject = get_commit_info("s") body = get_commit_info("b") return f"{subject}\n\n{body}".strip() def _author_in_ignore_list( self, context: ValidationContext, pending: bool = False ) -> bool: """Check if the current author or any co-author is in the ignore list.""" ignore_authors = context.config.get("commit", {}).get("ignore_authors", []) if not ignore_authors: return False current_author = self._resolve_current_author(context, pending) if current_author and current_author in ignore_authors: self._skip_reason = f"author {current_author} is in [commit].ignore_authors" return True # Check co-authors from the commit message body message = self._get_commit_body(context) if not message: return False co_authors = re.findall( r"^Co-authored-by:\s*([^<\n]+)\s*(?:<|$)", message, re.MULTILINE, ) for co_author in co_authors: if co_author.strip() in ignore_authors: self._skip_reason = ( f"co-author {co_author.strip()} is in [commit].ignore_authors" ) return True return False @staticmethod def _get_commit_body(context: ValidationContext) -> str: """Retrieve the commit message body from context or git.""" # An empty string is a message the caller supplied, not an absent one. # Reading it as absent sends the check off to the repository's HEAD # commit instead, so a caller asking about "" is answered about # whatever was committed last. The skip logic above already draws the # line at None; this follows it. if context.stdin_text is not None: return context.stdin_text if context.commit_file: try: return read_commit_message_file(context.commit_file) except OSError: pass if context.rev is not None: return get_commit_info("b", context.rev) return get_commit_info("b") def _should_skip_commit_validation(self, context: ValidationContext) -> bool: """ Determine if commit validation should be skipped. Skip if the current author or any co-author is in the ignore_authors list for commits, or if no stdin_text, no commit_file, and no commits exist. """ if self._author_in_ignore_list(context): return True return ( context.stdin_text is None and context.commit_file is None and context.rev is None and not has_commits() ) def _should_skip_branch_validation(self, context: ValidationContext) -> bool: """ Determine if branch validation should be skipped. Skip if the current author is in the ignore_authors list for branches, or if no branch name was supplied and no commits exist. """ ignore_authors = context.config.get("branch", {}).get("ignore_authors", []) if ignore_authors: current_author = self._resolve_current_author(context) if current_author and current_author in ignore_authors: self._skip_reason = ( f"author {current_author} is in [branch].ignore_authors" ) return True return context.piped_name is None and not has_commits() def _print_failure( self, actual_value: str, *, error: str | None = None, fix: str | None = None, suggest: str | None = None, ) -> None: """Record and (unless suppressed) print a standardised failure message. ``error`` replaces the rule's static explanation when the validator knows more than the rule does at build time: the measured length, the tools it detected, whether the message under test is a commit yet. ``fix`` is the corrected value when the validator can name it without guessing; it replaces the rule's generic suggestion with a concrete one (``suggest`` overrides the wording) and travels to structured consumers as its own field. """ rule_dict = self.rule.to_dict() if error is not None: rule_dict["error"] = error if fix or suggest: rule_dict["suggest"] = suggest or f'Use "{fix}"' if fix: rule_dict["fix"] = fix # Always store structured failure details for programmatic consumers. self._last_failure = { "check": self.rule.check, "value": actual_value, "error": rule_dict["error"], "suggest": rule_dict.get("suggest") or self.rule.suggest or "", "fix": fix or "", } self._failure_blocks.append((rule_dict, actual_value)) if not self._suppress_output: _print_failure( rule_dict, actual_value, no_banner=self._no_banner, compact=self._compact, ) class CommitMessageValidator(BaseValidator): """Validates commit messages against conventional commit standards.""" def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_commit_validation(context): return ValidationResult.SKIP message = self._get_commit_message(context) if not message: return ValidationResult.PASS self._checked_value = message if self.rule.regex and re.match(self.rule.regex, message): return ValidationResult.PASS # Name the correction only when it is mechanical: a type's case or a # one-letter slip, a colon that went missing. The corrected header # has to satisfy the rule itself, or it is no fix at all. subject, newline, rest = message.partition("\n") fixed_subject = fix_conventional_header(subject, self.rule.allowed) fix = suggest = None if ( fixed_subject and self.rule.regex and re.match(self.rule.regex, fixed_subject) ): fix = fixed_subject + newline + rest suggest = f'Use "{fixed_subject}"' self._print_failure(message, fix=fix, suggest=suggest) return ValidationResult.FAIL class SubjectValidator(BaseValidator): """Validates commit subject lines.""" def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_commit_validation(context): return ValidationResult.SKIP subject = self._get_subject(context) if not subject: return ValidationResult.PASS self._checked_value = subject return self._validate_subject(subject) def _get_subject(self, context: ValidationContext) -> str: """Extract subject from commit message.""" if context.stdin_text is not None: return context.stdin_text.strip().split("\n")[0] if context.commit_file: try: message = read_commit_message_file(context.commit_file).strip() return message.split("\n")[0] except FileNotFoundError: pass if context.rev is not None: return get_commit_info("s", context.rev) return get_commit_info("s") def _validate_subject(self, _subject: str) -> ValidationResult: """Override in subclasses for specific validation logic.""" return ValidationResult.PASS def _description(self, subject: str) -> str: """*subject* past its Conventional Commits ``type(scope)!:`` prefix. The rule's ``allowed`` list says which words are types: the builder sets it to ``allow_commit_types`` under Conventional Commits and to an empty list without them, where "Added: support" or "oops: x" is not a type but the subject itself. ``None``, from a rule built by hand, keeps the old reading of any ``word:`` as a type. """ match = re.match(r"^(\w+)(?:\([^)]*\))?!?:\s*(.*)", subject) if not match: return subject allowed = self.rule.allowed if allowed is not None and match.group(1) not in allowed: return subject return match.group(2) class SubjectCapitalizationValidator(SubjectValidator): """Validates that subject starts with capital letter.""" def _validate_subject(self, subject: str) -> ValidationResult: # A merge subject is machine-written; the rule declines to judge it. # Only the subjects merge tools write count, so anything else is # author prose. if is_merge_subject(subject): return ValidationResult.SKIP if self._is_capitalized(subject): return ValidationResult.PASS # The corrected subject has to pass this same check, or it is no fix. fix = fix_subject_case(subject, capitalize=True) if fix and not self._is_capitalized(fix): fix = None self._print_failure(subject, fix=fix) return ValidationResult.FAIL def _is_capitalized(self, subject: str) -> bool: """Whether the description starts upper-case, after any Conventional Commits prefix. Only a prefix that ends in a colon is a type. Without one, the first word is the description itself, so "Add feature" is judged on its "A" and not on the "f" that follows, and "Update" alone is judged at all. """ description = self._description(subject).strip() return bool(description) and description[0].isupper() class SubjectImperativeValidator(SubjectValidator): """Validates that subject uses imperative mood. Decides on the first word's form rather than its membership in a vocabulary: a past tense ("fixed"), a gerund ("adding") or a third person ("fixes") is not imperative, and nothing else disqualifies. A list can only reject correct subjects wherever it falls short, and it always does: on 59k strictly imperative subjects from git.git it rejected 45%, against 1% here. See #526. The loosening is deliberate: a noun-led subject ("parser improvements") now passes, where the list rejected it by accident of vocabulary. """ _INFLECTED = ("ed", "ing") def _validate_subject(self, subject: str) -> ValidationResult: # Merge and fixup subjects are machine-written; decline to judge them. # Only the subjects merge tools write, and git's exact "fixup! ", # count, so anything else is author prose. if is_merge_subject(subject) or subject.startswith("fixup! "): return ValidationResult.SKIP # Extract first word, past a Conventional Commits prefix (including # a breaking "feat!:") when there is one. match = re.match(r"(\w+)", self._description(subject)) if not match: return ValidationResult.PASS first_word = match.group(1).lower() if self._is_inflected(first_word): self._print_failure(subject) return ValidationResult.FAIL return ValidationResult.PASS @classmethod def _is_inflected(cls, word: str) -> bool: """Whether *word* carries past-tense, gerund or third-person marking.""" if word in NON_IMPERATIVE_LOOKALIKES: return False if word.endswith(cls._INFLECTED): return True return cls._is_third_person(word) @classmethod def _is_third_person(cls, word: str) -> bool: """Whether *word* is a verb wearing the third-person singular -s. Unlike -ed and -ing, a trailing -s is weak evidence on its own -- plural nouns wear one too ("status report") -- so it asks for corroboration: the stem has to be a verb we already know. "tests" is genuinely both, and this reads it as the verb. """ # "address" and "process" end in -ss without being third person. if not word.endswith("s") or word.endswith("ss"): return False stems = {word[:-1]} if word.endswith("es"): stems.add(word[:-2]) if word.endswith("ies"): stems.add(word[:-3] + "y") return any(stem in IMPERATIVES for stem in stems) # GitHub ends the subject of a squash merge with the pull request's number, # " (#123)". Like a merge subject's length, those characters are GitHub's # doing, not the author's: a title that fit the limit on the pull request # must not fail once it lands on the branch. A title that already ends in # a number, such as a backport's " (#12)", gets a second one, so the whole # run is left out. [0-9], not \d, which also matches other scripts' digits. _SQUASH_PR_NUMBER = re.compile(r"(?: \(#[0-9]+\))+$") def _characters(count: int) -> str: """``count`` with its unit, singular or plural as the number demands.""" return f"{count} character{'' if count == 1 else 's'}" def _dependency_bot(context: ValidationContext) -> str: """The dependency update bot that wrote the commit, or "" for anyone else. The length rules let these bots through: they write the subject from the package name and versions, and the body from the release notes. """ if context.rev is not None: author = get_commit_info("an", context.rev) elif context.stdin_text is not None or context.commit_file is not None: # A message not yet committed is a bot's only when the caller says # so through git's author variable, as the Action does for each # pull request commit. Bots do not commit through a local hook, # so the local git config is not asked. author = os.environ.get("GIT_AUTHOR_NAME", "").strip() else: author = get_commit_info("an") return author if author in DEPENDENCY_UPDATE_BOTS else "" class SubjectLengthValidator(SubjectValidator): """Validates subject line length constraints.""" def validate(self, context: ValidationContext) -> ValidationResult: # Kept for _written_by_dependency_bot, which asks only once a subject # is out of bounds, so a passing subject costs no author lookup. self._context = context return super().validate(context) def _written_by_dependency_bot(self) -> bool: author = _dependency_bot(self._context) if not author: return False self._skip_reason = ( f"{author} writes the subject from the package name and versions" ) return True def _validate_subject(self, subject: str) -> ValidationResult: # A merge or revert subject's length is git's doing, not the # author's: 'Revert "..."' adds nine characters to a subject that # already fit. if is_merge_subject(subject) or is_revert_subject(subject): return ValidationResult.SKIP suffix = _SQUASH_PR_NUMBER.search(subject) length = suffix.start() if suffix else len(subject) limit = self.rule.value if ( (self.rule.check == "subject_max_length" and length <= limit) or (self.rule.check == "subject_min_length" and length >= limit) or self.rule.check not in ["subject_max_length", "subject_min_length"] ): return ValidationResult.PASS if self._written_by_dependency_bot(): return ValidationResult.SKIP # Name the suffix left out, so the count matches what the author sees. uncounted = f', not counting "{suffix.group().strip()}"' if suffix else "" # "At most 20" states the rule; the measured length says how far off # the subject is, and the difference is what decides between trimming # a word and rewriting the line. if self.rule.check == "subject_max_length": error = f"Subject is {_characters(length)}{uncounted}; it must be at most {_characters(limit)}" suggest = f"Shorten the subject by {_characters(length - limit)}, to {limit} or fewer" else: error = f"Subject is {_characters(length)}{uncounted}; it must be at least {_characters(limit)}" suggest = f"Write a subject of at least {_characters(limit)} ({limit - length} more)" self._print_failure(subject, error=error, suggest=suggest) return ValidationResult.FAIL class AuthorValidator(BaseValidator): """Validates author information.""" def validate(self, context: ValidationContext) -> ValidationResult: if self._author_in_ignore_list(context): return ValidationResult.SKIP # With no message and no --rev the commit checks skip a repository # that has no commits. The author checks do not: the value under # test is the identity the next commit will carry, and git knows # that before the first commit exists. ignore_authors then reads # that identity too, there being no commit author to read. has_head: bool | None = None if not self._message_was_supplied(context): has_head = has_commits() if not has_head and self._author_in_ignore_list(context, pending=True): return ValidationResult.SKIP author_value = self._get_author_value(context, has_head) if author_value is None: return ValidationResult.SKIP if not author_value: return ValidationResult.PASS self._checked_value = author_value return self._validate_author(author_value) def _get_author_value( self, context: ValidationContext, has_head: bool | None = None ) -> str | None: """Get author value based on rule type. Reads the identity git would record for a new commit first (for pre-commit validation), then falls back to the last commit's author. ``None`` when neither exists: no identity is configured and the repository has no commit yet. *has_head* is whether it has one, when the caller already knows. """ supplied = context.piped_name if supplied is not None: return supplied.strip() git_config_map = { "author_name": _USER_NAME, "author_email": "user.email", } git_log_map = { "author_name": "an", "author_email": "ae", } # An explicit revision names an existing commit, whose identity is a # fact about the commit: read it from the commit and never from the # config, which describes whoever happens to be running the check. if context.rev is not None: format_str = git_log_map.get(self.rule.check, "") return get_commit_info(format_str, context.rev) if format_str else "" # The identity git would record for the next commit, in git's order: # GIT_AUTHOR_NAME / GIT_AUTHOR_EMAIL (set for the hooks by # ``git commit --author``, and by tools that commit under their own # name), then author.name / author.email, then user.name / user.email. config_key = git_config_map.get(self.rule.check, "") if config_key: field = config_key.split(".")[1] from_env = os.environ.get(f"GIT_AUTHOR_{field.upper()}", "").strip() if from_env: return from_env for key in (f"author.{field}", config_key): config_value = get_git_config_value(key) if config_value: return config_value # Fall back to the last commit's author. Before the first commit # there is none, and git would answer with an error message. format_str = git_log_map.get(self.rule.check, "") if not format_str: return "" if has_head is None: has_head = has_commits() if not has_head: return None return get_commit_info(format_str) def _validate_author(self, author_value: str) -> ValidationResult: """Validate author against rule constraints.""" if self.rule.regex: if re.match(self.rule.regex, author_value): return ValidationResult.PASS self._print_failure(author_value) return ValidationResult.FAIL if self.rule.allowed and author_value not in self.rule.allowed: self._print_failure(author_value) return ValidationResult.FAIL if self.rule.ignored and author_value in self.rule.ignored: # An ignored author is a deliberate bypass, not a verdict. return ValidationResult.SKIP return ValidationResult.PASS class BranchValidator(BaseValidator): """Validates branch names.""" def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_branch_validation(context): return ValidationResult.SKIP supplied = context.piped_name branch_name = supplied.strip() if supplied is not None else get_branch_name() self._checked_value = branch_name if not self.rule.regex: return ValidationResult.PASS if re.match(self.rule.regex, branch_name): return ValidationResult.PASS fixed = fix_branch_type(branch_name, self.rule.allowed) fix = suggest = None if fixed and re.match(self.rule.regex, fixed): fix = fixed suggest = ( f'Rename the branch to "{fixed}" (git branch -m {shlex.quote(fixed)})' ) self._print_failure(branch_name, fix=fix, suggest=suggest) return ValidationResult.FAIL class TagValidator(BaseValidator): """Validates tag names. Checks every tag pointing at the revision under test (``--rev``, or ``HEAD``). A commit with no tag is a skip, not a failure: the rule validates how tags are named, and the absence of one is not a naming violation. Piped input (or an API-supplied value) names the tags to check directly, one per line, without consulting git. In a pre-push hook the tags under push are checked instead; under pre-commit, which names only one ref of a push, a branch push checks the tags on the commits it pushes. """ @staticmethod def _tags_from_stdin(text: str) -> list[str]: """Extract tag names from piped input. Two shapes arrive here: bare tag names (API callers, ``echo v1 |``), and the four-field `` `` lines a pre-push hook receives. For push lines the tags under push are the ``refs/tags/*`` refs — a push carrying no tag ref yields nothing to validate, and a deletion (all-zero local sha) removes a tag rather than naming a new one, so neither can fail the check. The remote ref is the name checked, because it is the one the remote receives: ``git push origin v1.0.0:refs/tags/anything`` creates ``anything``. The local ref stands in only when the remote side is not a tag. """ lines = [ln.strip() for ln in text.splitlines() if ln.strip()] push_lines = [ln for ln in lines if len(ln.split()) == 4 and "refs/" in ln] if push_lines and len(push_lines) == len(lines): tags = [] for ln in push_lines: local_ref, local_sha, remote_ref, _ = ln.split() if set(local_sha) == {"0"}: continue for ref in (remote_ref, local_ref): if ref.startswith("refs/tags/"): tags.append(ref.removeprefix("refs/tags/")) break return list(dict.fromkeys(tags)) return lines @staticmethod def _tags_on_pushed_commits(text: str) -> list[str]: """The tags pointing at any commit pre-push lines carry. Every commit of the push counts, not only the tip: a release commit is often followed by another before the push, and ``git push --follow-tags`` still sends the tag on the earlier one. """ tags = [] for ln in text.splitlines(): fields = ln.split() if len(fields) == 4 and set(fields[1]) != {"0"}: for rev in get_push_commits(fields[1], fields[3]): tags.extend(get_tags_at(rev)) return list(dict.fromkeys(tags)) def validate(self, context: ValidationContext) -> ValidationResult: supplied = context.piped_value if supplied is not None: tags = self._tags_from_stdin(supplied) if not tags and context.push_from_pre_commit: # A branch push, as pre-commit tells it: any tag pushed with # the branch is missing from the line, so the tags on the # pushed commits stand in for it. Reading HEAD instead would # judge whatever is checked out, which need not be pushed. tags = self._tags_on_pushed_commits(supplied) else: tags = get_tags_at(context.rev or "HEAD") if not tags: return ValidationResult.SKIP self._checked_value = ", ".join(tags) if not self.rule.regex: return ValidationResult.PASS for tag in tags: if not re.match(self.rule.regex, tag): self._checked_value = tag self._print_failure(tag) return ValidationResult.FAIL return ValidationResult.PASS class FilesValidator(BaseValidator): """Validates metadata about the files a commit touches. One class serves the three file rules — size limit, prohibited path patterns, path length — branching on the rule's check name. Only the paths and sizes recorded in the commit are read, never file contents: content scanning is a different tool's job. A commit touching no files (or an unresolvable revision) is a skip. """ @staticmethod def _push_revs_from_stdin(text: str) -> list[str] | None: """Extract the commits a pre-push hook is being asked to approve. A native pre-push hook receives `` `` lines naming what is being pushed; validating HEAD there would check the wrong commit whenever another ref is pushed. Both ends of each line matter: a push usually carries several commits, and checking only the tip would wave through a file added by any earlier commit in the same push. Deletions are skipped: an all-zero local sha removes content rather than adding it. Tags go through the same range as branches rather than being skipped. What matters is not whether a ref is a tag but whether it carries commits the remote lacks: a tag on already-pushed history resolves to an empty range, so ``git push --follow-tags`` is not rejected over a file committed long before, while a tag that is the only thing carrying a commit to the remote still gets that commit checked. Tag *names* remain CC401's business. Input of any other shape is not push metadata and returns ``None``, so the validator falls back to the revision under test. """ lines = [ln.strip() for ln in text.splitlines() if ln.strip()] push_lines = [ln for ln in lines if len(ln.split()) == 4 and "refs/" in ln] if not push_lines or len(push_lines) != len(lines): return None revs: list[str] = [] for ln in push_lines: _local_ref, local_sha, _remote_ref, remote_sha = ln.split() if set(local_sha) == {"0"}: continue revs.extend(get_push_commits(local_sha, remote_sha)) return list(dict.fromkeys(revs)) def _files_for_rev( self, context: ValidationContext, rev: str ) -> list[tuple[str, int]]: """Files touched by *rev*, computed once per run and shared.""" if rev not in context.files_cache: context.files_cache[rev] = get_commit_files(rev) return context.files_cache[rev] def _revs_to_check(self, context: ValidationContext) -> list[str] | None: """Revisions this run should police. ``None`` means the push carried nothing to police — only deletions, or commits the remote already has — which the caller reports as a skip rather than a pass. """ supplied = context.piped_value if supplied is not None: revs = self._push_revs_from_stdin(supplied) if revs is not None: return revs or None return [context.rev or "HEAD"] def _collect_files( self, context: ValidationContext, revs: list[str] ) -> list[tuple[str, int]]: """Files across *revs*, each one counted once. A file touched by several commits of the same push is one offender, not one per commit. """ files: list[tuple[str, int]] = [] seen: set[tuple[str, int]] = set() for rev in revs: for item in self._files_for_rev(context, rev): if item not in seen: seen.add(item) files.append(item) return files def validate(self, context: ValidationContext) -> ValidationResult: revs = self._revs_to_check(context) if revs is None: return ValidationResult.SKIP files = self._collect_files(context, revs) if not files: return ValidationResult.SKIP self._checked_value = f"{len(files)} file(s)" if self.rule.check == "file_size": return self._validate_sizes(files) if self.rule.check == "file_pattern": return self._validate_patterns(files) if self.rule.check == "path_length": return self._validate_path_lengths(files) return ValidationResult.PASS def _fail(self, offenders: list[str]) -> ValidationResult: """Report the first offender, with a count when there are more.""" value = offenders[0] if len(offenders) > 1: value += f" (+{len(offenders) - 1} more)" self._checked_value = value self._print_failure(value) return ValidationResult.FAIL def _validate_sizes(self, files: list[tuple[str, int]]) -> ValidationResult: limit = self.rule.value offenders = [ f"{path} ({format_size(size)})" for path, size in files if size > limit ] if offenders: return self._fail(offenders) return ValidationResult.PASS def _validate_patterns(self, files: list[tuple[str, int]]) -> ValidationResult: # fnmatch() folds case through os.path.normcase, which would make # "*.pem" catch KEY.PEM on Windows and miss it everywhere else -- # one config, two policies. fnmatchcase() is the same on every # platform, and case-sensitive is what git pathspecs already are. patterns = self.rule.value or [] offenders = [] for path, _ in files: basename = path.rsplit("/", 1)[-1] hit = next( ( pattern for pattern in patterns # A bare pattern like *.pem should catch the file at any # depth, so the basename is matched alongside the full # path. if fnmatchcase(path, pattern) or fnmatchcase(basename, pattern) ), None, ) if hit: offenders.append(f"{path} (pattern {hit})") if offenders: return self._fail(offenders) return ValidationResult.PASS def _validate_path_lengths(self, files: list[tuple[str, int]]) -> ValidationResult: limit = self.rule.value offenders = [ f"{path} ({len(path)} characters)" for path, _ in files if len(path) > limit ] if offenders: return self._fail(offenders) return ValidationResult.PASS class MergeBaseValidator(BaseValidator): """Validates merge base ancestry.""" def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_branch_validation(context): return ValidationResult.SKIP current_branch = get_branch_name() target_pattern = self.rule.regex self._checked_value = current_branch if not target_pattern: return ValidationResult.PASS # Find target branch matching the pattern target_branch = self._find_target_branch(target_pattern) if not target_branch: # A target that resolves to no ref (a typo, or a shallow CI clone # without origin/) leaves nothing to compare. That is a # skip, not a pass: the branch was never judged against it. name = target_pattern.lstrip("^").rstrip("$").strip() self._skip_reason = f"rebase target '{name}' not found" return ValidationResult.SKIP source = ci_source_commit() if source and git_rev_parse_verify(source): # A CI build of a merge (Bitbucket's pull request step, GitLab's # merged results pipeline): HEAD, and on Bitbucket the local # branch too, already contain the target, so only the commit the # author pushed says whether the branch was rebased. result = git_merge_base(target_branch, source) else: result = git_merge_base(target_branch, current_branch) if result == 128: # 128 is git failing to resolve a name, not an answer about # ancestry. A CI checkout of a pull request leaves a detached HEAD # with no local branch created, while get_branch_name() still # reports a name from GITHUB_HEAD_REF — so the name here refers to # nothing on disk. The remote-tracking ref is the real branch. result = git_merge_base(target_branch, f"origin/{current_branch}") if result == 128: # Last resort, when the branch is unresolvable under either name. # On a pull_request event HEAD is GitHub's synthetic merge commit, # whose first parent IS the target tip, so asking about HEAD would # pass every branch, rebased or not. Its *second* parent is the # pull request head — the commit actually under review — so ask # about that instead whenever HEAD is a merge. Where HEAD has a # single parent it is the branch commit itself (a push event, or a # branch that was never pushed) and answers for itself. source = "HEAD^2" if git_rev_parse_verify("HEAD^2") else "HEAD" result = git_merge_base(target_branch, source) if result == 0: return ValidationResult.PASS self._print_failure(current_branch) return ValidationResult.FAIL def _find_target_branch(self, pattern: str) -> str | None: """Find target branch by verifying refs directly. Uses ``git rev-parse --verify`` for exact ref resolution instead of scanning ``git branch -a`` output with a regex. Strips common regex anchors (``^``, ``$``) from the pattern to obtain a branch name, then attempts to verify it as a local ref first, falling back to the remote tracking ref under ``origin/``. :param pattern: The raw regex pattern from the rule config (e.g. ``"^main$"`` or ``"main"``). :returns: The resolved branch name if verified, ``None`` otherwise. """ # Strip common regex anchors to obtain a clean branch name branch_name = pattern.lstrip("^").rstrip("$").strip() if not branch_name: return None # Try local branch first (refs/heads/ avoids ambiguity with tags) try: subprocess.run( ["git", "rev-parse", "--verify", f"refs/heads/{branch_name}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, ) return branch_name except subprocess.CalledProcessError: pass # Try remote tracking branch under origin/ try: subprocess.run( ["git", "rev-parse", "--verify", f"refs/remotes/origin/{branch_name}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, ) # Qualified with the remote, because that is the ref that was just # verified. Returning the bare name here made the caller run # ``git merge-base --is-ancestor main HEAD`` in a checkout that has # only ``origin/main``; git exits 128 on the unresolvable name and # the branch was reported as "not rebased onto target branch" when # it was correctly based all along. A CI checkout of a pull request # is exactly that shape. return f"origin/{branch_name}" except subprocess.CalledProcessError: pass return None class SignoffValidator(BaseValidator): """Validates that commit messages contain required signoff trailer.""" def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_commit_validation(context): return ValidationResult.SKIP message = self._get_commit_message(context) if not message: return ValidationResult.PASS self._checked_value = message if self.rule.regex and re.search(self.rule.regex, message): return ValidationResult.PASS # In a commit-msg hook "the latest commit" is the previous one, which # does carry a sign-off, so name what was actually read: the message # under test, or the commit it came from. error = ( "Signed-off-by trailer not found in the commit message" if self._is_pending_message(context) else "Signed-off-by trailer not found in the latest commit" ) trailer = signoff_trailer(*self._resolve_author_identity(context)) fix = suggest = None if trailer: fix = f"{message.rstrip()}\n\n{trailer}" suggest = f'Add the trailer "{trailer}" (git commit --signoff, or --amend --signoff for an existing commit)' self._print_failure(message, error=error, fix=fix, suggest=suggest) return ValidationResult.FAIL @staticmethod def _is_pending_message(context: ValidationContext) -> bool: """Whether the message describes a commit that does not exist yet.""" return context.stdin_text is not None or context.commit_file is not None @classmethod def _resolve_author_identity(cls, context: ValidationContext) -> tuple[str, str]: """The (name, email) the sign-off would carry, by the same modes as the author. This runs only on a failure, but a hook still waits on it, so each mode asks git once and falls back to a second call only when the first left a part blank. """ if context.rev is not None: return get_commit_author_identity(context.rev) pending = cls._is_pending_message(context) name, email = ( get_git_user_identity() if pending else get_commit_author_identity() ) if not name or not email: fallback_name, fallback_email = ( get_commit_author_identity() if pending else get_git_user_identity() ) name, email = name or fallback_name, email or fallback_email return name, email #: A trailer line: a key with a hyphen (``Signed-off-by``, ``Change-Id``) #: or one of the common one-word keys, then a colon. A one-word key such as #: ``Note:`` is left as body text, since a sentence can start that way. _BODY_TRAILER_LINE = re.compile( r"^(?:[a-z]\w*-[\w-]+|Fixes|Closes|Resolves|Refs|Link|Cc|Bug)[ \t]*:", re.IGNORECASE, ) def _body_without_trailers(message: str) -> str: """The body of *message*: what follows the subject, minus the trailer block. ``git commit -s`` adds a ``Signed-off-by:`` line, so a message with only trailers after its subject used to count as having a body. """ paragraphs = [ p.strip() for p in re.split(r"\n[ \t]*\n", message.strip()) if p.strip() ] # The subject is the first line, even when the body follows it directly. rest = paragraphs[0].partition("\n")[2] if paragraphs else "" body = ([rest.strip()] if rest.strip() else []) + paragraphs[1:] if body and all( _BODY_TRAILER_LINE.match(ln.strip()) for ln in body[-1].splitlines() ): body = body[:-1] return "\n\n".join(body).strip() class BodyValidator(BaseValidator): """Validates that commit messages contain a body when required.""" def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_commit_validation(context): return ValidationResult.SKIP message = self._get_commit_message(context) if not message: return ValidationResult.PASS self._checked_value = message if _body_without_trailers(message): return ValidationResult.PASS self._print_failure(message) return ValidationResult.FAIL #: A line that holds an address with a scheme (https://, ftp://, ssh://). It #: cannot be wrapped, so the body line length rule does not count it, as #: commitlint and checkpatch do not. Schemes are case-insensitive. There is #: no word boundary before it: Chinese and Japanese text runs straight into #: an address (参见https://...), with no space or punctuation between. The #: lookbehind starts the scheme where a run of scheme characters starts, so a #: long run with no ``://`` is scanned once, not once per character. _URL = re.compile(r"(? list[int]: """The numbers of *message*'s body lines longer than *limit*, from 0. Counted in the message as given, so the numbers point into the quoted message. The subject is CC004's, and three kinds of line are left out because wrapping them breaks them: a line with a web address, a single word with no space in it (a path, a hash), and the trailer block at the end, where a ``Co-authored-by:`` line is as long as the name and address in it. Chinese, Japanese and Korean prose has no spaces between words, so a line with one of their characters is counted even without a space. """ # Trailing blank lines change no line's number, and are never long. lines = message.rstrip().split("\n") # The trailer block is the last paragraph when every line in it is one. trailers: set[int] = set() end = len(lines) start = end while start > 1 and lines[start - 1].strip(): start -= 1 # git lets a trailer's value continue on an indented line. if ( start > 1 and _BODY_TRAILER_LINE.match(lines[start].strip()) and all( _BODY_TRAILER_LINE.match(line.strip()) or line[:1] in (" ", "\t") for line in lines[start:end] ) ): trailers = set(range(start, end)) return [ number for number, line in enumerate(lines) if number > 0 and number not in trailers and len(line.rstrip()) > limit and not _one_word(line) and not _URL.search(line) ] def _one_word(line: str) -> bool: """Whether *line* is one word that wrapping would break: a path, a hash. A line of Chinese, Japanese or Korean has no spaces either, yet it is prose that wraps anywhere, so a wide character makes it more than a word. """ text = line.strip() return " " not in text and not any( unicodedata.east_asian_width(char) in ("W", "F") for char in text ) def _line_numbers(numbers: list[int]) -> str: """``Line 3``, ``Lines 3 and 5``, ``Lines 3, 5, 8 and 2 more``, from 1.""" shown = [str(number + 1) for number in numbers[:3]] if len(numbers) == 1: return f"Line {shown[0]}" rest = len(numbers) - len(shown) if rest: return f"Lines {', '.join(shown)} and {rest} more" return f"Lines {', '.join(shown[:-1])} and {shown[-1]}" class BodyLineLengthValidator(BaseValidator): """Validates that no line of the commit body is longer than the limit.""" def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_commit_validation(context): return ValidationResult.SKIP message = self._get_raw_message(context) if not message: return ValidationResult.PASS self._checked_value = message # git writes a merge commit's body (the conflict list) itself. subject = message.split("\n", 1)[0] if is_merge_subject(subject): return ValidationResult.SKIP limit = self.rule.value long_lines = long_body_lines(message, limit) if not long_lines: return ValidationResult.PASS bot = _dependency_bot(context) if bot: self._skip_reason = f"{bot} writes the body from the release notes" return ValidationResult.SKIP lines = message.split("\n") longest = max(len(lines[number].rstrip()) for number in long_lines) # The numbers count the subject as line 1, as an editor does, and # point into the message quoted above the failure. where = _line_numbers(long_lines) if len(long_lines) == 1: error = ( f"{where} is {_characters(longest)}; " f"body lines must be at most {_characters(limit)}" ) else: error = ( f"{where} are longer than {_characters(limit)}, " f"the longest {_characters(longest)}" ) suggest = f"Wrap the body at {limit} characters" self._print_failure(message, error=error, suggest=suggest) return ValidationResult.FAIL def _get_raw_message(self, context: ValidationContext) -> str: """The message with its line breaks as committed. ``%s`` joins a first paragraph into one line, so a body line written right under the subject would vanish into it; ``%B`` keeps it. """ if context.stdin_text is not None or context.commit_file: return self._get_commit_message(context) if context.rev is not None: return get_commit_info("B", context.rev).strip() return get_commit_info("B").strip() class ForcePushValidator(BaseValidator): """Validates that no force push is being performed. Reads pushed ref information from stdin (provided by git's pre-push hook) in the format:: A force push is detected when the remote SHA is not an ancestor of the local SHA, meaning local history would overwrite the remote. With nothing to compare -- no ref lines, only blank or malformed ones, or no upstream to fall back on -- the check reports SKIP rather than PASS: it examined nothing, and a pass would read as a push that was judged safe. """ ZERO_SHA = "0000000000000000000000000000000000000000" def validate(self, context: ValidationContext) -> ValidationResult: # Emptiness, not absence, is the question here: unlike a message or a # branch name, stdin_text carries a *list* of refs, and no refs means # there is nothing to check either way. So this one stays a truth test # while the single-value readers above distinguish "" from None. push_refs = context.piped_value if not push_refs: if context.push_upstream_fallback: return self._check_current_branch_against_upstream() return ValidationResult.SKIP checked_any = False for line in push_refs.splitlines(): line = line.strip() # A blank or malformed line names no ref, so it judges nothing. if len(line.split()) < 4: continue checked_any = True if self._check_push_line(line) == ValidationResult.FAIL: return ValidationResult.FAIL return ValidationResult.PASS if checked_any else ValidationResult.SKIP def _check_current_branch_against_upstream(self) -> ValidationResult: """Check whether pushing HEAD to its upstream would require force.""" upstream_ref = get_upstream_branch() if not upstream_ref: # No upstream means no remote history to compare HEAD with. return ValidationResult.SKIP if self._collect_value: branch = get_branch_name() self._checked_value = f"{branch} -> {upstream_ref}" target_ref = get_upstream_remote_sha(upstream_ref) or upstream_ref returncode = git_merge_base(target_ref, "HEAD") if ( returncode == 128 and target_ref != upstream_ref and fetch_upstream_ref(upstream_ref) ): returncode = git_merge_base(target_ref, "HEAD") if returncode == 1: self._print_failure(f"{get_branch_name()} -> {upstream_ref}") return ValidationResult.FAIL return ValidationResult.PASS def _check_push_line(self, line: str) -> ValidationResult: """Check a single pushed ref line for force push.""" if not line: return ValidationResult.PASS parts = line.split() if len(parts) < 4: return ValidationResult.PASS local_ref, local_sha, remote_ref, remote_sha = ( parts[0], parts[1], parts[2], parts[3], ) pair = f"{local_ref} -> {remote_ref}" # Accumulate every checked ref pair: a pre-push stdin may carry # several refs, and each one is validated individually. self._checked_value = ( f"{self._checked_value}\n{pair}" if self._checked_value else pair ) # Zero SHA for remote means a new branch push (not a force push) if remote_sha == self.ZERO_SHA: return ValidationResult.PASS # Check if the remote SHA is an ancestor of the local SHA. # returncode 0 -> remote is ancestor of local (fast-forward push, OK) # returncode 1 -> not an ancestor (force push detected) # returncode 128 -> SHA may be unknown locally; fetch remote ref and retry returncode = git_merge_base(remote_sha, local_sha) if returncode == 128: for remote in self._remote_candidates_for_push(remote_ref): if not fetch_remote_ref(remote, remote_ref): continue returncode = git_merge_base(remote_sha, local_sha) if returncode != 128: break if returncode == 1: self._print_failure(f"{local_ref} -> {remote_ref}") return ValidationResult.FAIL return ValidationResult.PASS def _remote_candidates_for_push(self, remote_ref: str) -> list[str]: """Return remotes worth fetching for a pushed branch ref.""" if not remote_ref.startswith("refs/heads/"): return [] remotes: list[str] = [] upstream_ref = get_upstream_branch() upstream_parts = upstream_ref.split("/", 1) remote_branch = remote_ref.removeprefix("refs/heads/") if len(upstream_parts) == 2 and upstream_parts[1] == remote_branch: remotes.append(upstream_parts[0]) remotes.extend(remote for remote in get_git_remotes() if remote not in remotes) return remotes class CommitTypeValidator(BaseValidator): """Base validator for special commit types (merge, revert, fixup, WIP, empty).""" def validate(self, context: ValidationContext) -> ValidationResult: if self.rule.check == "ignore_authors": # The ignore_authors rule is about the commit author, not the # message; record it before the skip check so non-ignored # authors still carry the checked identity. An ignored author # means nothing was checked, so the value stays empty. The # author lookup only runs when structured consumers opt in. if self._collect_value: self._checked_value = self._resolve_current_author(context) if self._should_skip_commit_validation(context): self._checked_value = "" return ValidationResult.SKIP elif self._should_skip_commit_validation(context): return ValidationResult.SKIP message = self._get_commit_message(context) # allow_empty_commits is the rule that exists to judge an empty # message, so returning early on one made it unreachable: the branch # in _is_empty_commit_allowed that rejects an empty message could # never run. A message the caller supplied goes to the rule even when # it is empty; an empty one from git is still nothing to check. if not message and not self._message_was_supplied(context): # ignore_authors delivered its verdict above -- it judges the # author, so an absent message is no reason to disown it, and a # SKIP here would wrongly read as "author was bypassed". return ( ValidationResult.PASS if self.rule.check == "ignore_authors" else ValidationResult.SKIP ) self._checked_value = message # Check if this commit type is allowed based on rule configuration is_allowed = self._is_commit_type_allowed(message) if not is_allowed: fix = suggest = None if self.rule.check == "allow_wip_commits": fix = fix_wip(message) if fix: suggest = f'Drop the WIP marker: "{fix.splitlines()[0]}"' self._print_failure(message, fix=fix, suggest=suggest) return ValidationResult.FAIL return ValidationResult.PASS def _is_commit_type_allowed(self, message: str) -> bool: """Check if the commit type is allowed based on the rule check.""" check = self.rule.check if check == "allow_merge_commits": return self._is_merge_commit_allowed(message) elif check == "allow_revert_commits": return self._is_revert_commit_allowed(message) elif check == "allow_empty_commits": return self._is_empty_commit_allowed(message) elif check == "allow_fixup_commits": return self._is_fixup_commit_allowed(message) elif check == "allow_wip_commits": return self._is_wip_commit_allowed(message) return True def _is_merge_commit_allowed(self, message: str) -> bool: """Check if merge commits are allowed.""" is_merge = message.startswith("Merge ") # If rule value is True, allow merge commits. If False, reject them. return not is_merge or self.rule.value def _is_revert_commit_allowed(self, message: str) -> bool: """Check if revert commits are allowed.""" # 'Reapply "..."' is git's subject for reverting a revert, so it is # one too. is_revert = message.lower().startswith("revert ") or is_revert_subject(message) return not is_revert or self.rule.value def _is_empty_commit_allowed(self, message: str) -> bool: """Check if empty commits are allowed.""" is_empty = not message.strip() return not is_empty or self.rule.value def _is_fixup_commit_allowed(self, message: str) -> bool: """Check if fixup commits are allowed. ``git commit --fixup`` writes ``fixup!``, ``--squash`` writes ``squash!`` and ``--fixup=amend:``/``--fixup=reword:`` write ``amend!``. ``git rebase --autosquash`` folds all three away, so all three are the commits this rule is about. """ is_fixup = message.startswith(("fixup!", "squash!", "amend!")) return not is_fixup or self.rule.value def _is_wip_commit_allowed(self, message: str) -> bool: """Check if WIP commits are allowed.""" # [wip] or the word "wip" opening the subject, in any case and # whatever follows it: "WIP:", "WIP add", "WIP-", "WIP\t", or "WIP" # alone on the subject line. The word boundary keeps "wipe ..." out; # this is the marker fix_wip knows how to drop. is_wip = _WIP_MARKER.match(message) is not None return not is_wip or self.rule.value def _or_list(items: list[str]) -> str: """``a``, ``a or b``, ``a, b or c``.""" if len(items) <= 1: return "".join(items) return f"{', '.join(items[:-1])} or {items[-1]}" def _first_of(lines: list[str]) -> str: """The first line, with a count when there are more.""" if len(lines) > 1: return f"{lines[0]} (+{len(lines) - 1} more)" return lines[0] def _added_lines(before: str, after: str) -> list[str]: """The lines *after* carries that *before* did not, blank ones aside.""" seen = set(before.splitlines()) return [line for line in after.splitlines() if line.strip() and line not in seen] def _tools(signatures: list[dict[str, str]]) -> str: """The tools *signatures* name, once each, in a stable order.""" return ", ".join(sorted({s["tool"] for s in signatures})) #: The two rules about a tool taking a person's place, by check: the report #: lines that offend, what the tool did, what to call the line in the advice, #: and what the author still owes once it is gone. _PERSON_ROLES = { "ai_co_author": ( "co_author_lines", "is credited as a co-author", "the co-author line", "", ), "ai_signoff": ( "signoff_lines", "signed off the commit", "the AI sign-off", ", then sign off yourself (git commit --signoff)", ), } class AiAttributionValidator(BaseValidator): """Judges a commit message against the AI attribution policy. One class serves the four AI checks, by the rule's check name. ``ai_attribution`` is the ``forbid`` policy: any known AI signature fails. ``ai_disclosure``, ``ai_co_author`` and ``ai_signoff`` are the three conditions of ``disclose``, one rule each so a project can warn on one while enforcing the rest. The whole message is read, subject included, so a fix is a message that can be committed as it is. """ def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_commit_validation(context): return ValidationResult.SKIP message = self._get_commit_message(context) if not message: return ValidationResult.PASS if self.rule.check != "ai_attribution": self._checked_value = message return self._judge_under_disclose(message) if self.rule.value != "forbid": # No-op policy: nothing is checked, so no value is recorded. return ValidationResult.PASS self._checked_value = message return self._judge_under_forbid(message, context.not_a_commit) def _judge_under_forbid(self, message: str, not_a_commit: bool) -> ValidationResult: signatures = detect_ai_signatures(message) if not signatures: return ValidationResult.PASS fix = strip_lines_containing(message, [s["matched_text"] for s in signatures]) if not_a_commit: suggest = ( "This project does not accept AI attribution. Remove the AI lines." ) else: action = ( "Remove the AI trailer lines and re-commit." if fix else "Remove AI trailers and re-commit." ) suggest = ( "This project does not accept AI attribution in commit messages. " + action ) self._print_failure( _tools(signatures), error=f"AI attribution is forbidden in this project — detected: {_tools(signatures)}", suggest=suggest, fix=fix, ) return ValidationResult.FAIL def _judge_under_disclose(self, message: str) -> ValidationResult: accepted = self.rule.allowed or list(DEFAULT_AI_DISCLOSURE_TRAILERS) pattern = self.rule.regex or "" report = ai_policy.analyze(message, accepted, pattern) if self.rule.check == "ai_disclosure": return self._judge_disclosure(message, report, accepted, pattern) return self._judge_person_role(message, report, accepted, pattern) def _judge_disclosure( self, message: str, report: ai_policy.AiPolicyReport, accepted: list[str], pattern: str, ) -> ValidationResult: if report.malformed: # The accepted trailer is there but discloses nothing usable. It # is the author's to rewrite, so there is no fix. bad = report.malformed[0] if bad.problem == "empty": error = f"{bad.key}: discloses nothing: the trailer has no value" suggest = f"Name the tool after {bad.key}:" else: error = f"The {bad.key} value does not match the required pattern: {pattern}" suggest = ( f"Write the {bad.key} value so that it matches {pattern} " "(set by ai_disclosure_pattern in the [commit] config)" ) self._print_failure( _first_of([d.line for d in report.malformed]), error=error, suggest=suggest, ) return ValidationResult.FAIL if not report.undisclosed: return ValidationResult.PASS fix = ai_policy.propose_fix(message, report, accepted, pattern) added = _added_lines(message, fix) if fix else [] self._print_failure( _first_of([s["matched_text"] for s in report.evidence]), error=( f"AI assistance is not disclosed with {_or_list(accepted)} " f"— detected: {_tools(report.evidence)}" ), suggest=f'Disclose the tool with "{added[0]}"' if added else None, fix=fix, ) return ValidationResult.FAIL def _judge_person_role( self, message: str, report: ai_policy.AiPolicyReport, accepted: list[str], pattern: str, ) -> ValidationResult: lines, did, what, then = _PERSON_ROLES[self.rule.check] offenders: list[dict[str, str]] = getattr(report, lines) if not offenders: return ValidationResult.PASS fix = ai_policy.propose_fix(message, report, accepted, pattern) suggest = None if fix: added = _added_lines(message, fix) suggest = ( f'Use "{added[0]}" in place of {what}{then}' if added else f"Remove {what}{then or ': the tool is already disclosed'}" ) self._print_failure( _first_of([s["matched_text"] for s in offenders]), error=f"An AI tool {did}: {_tools(offenders)}", suggest=suggest, fix=fix, ) return ValidationResult.FAIL def _author_identity(context: ValidationContext) -> tuple[str, str]: """The author of the commit under test, as ``(name, email)``. An existing commit (``--rev``, or HEAD) by its recorded author; a message not yet committed by the author git would record for it. """ if _is_pending(context): return get_pending_author_identity() return get_commit_author_identity(context.rev or "HEAD") def _is_pending(context: ValidationContext) -> bool: """Whether the message under test is not committed yet (stdin or a file).""" return context.rev is None and ( context.stdin_text is not None or context.commit_file is not None ) def ai_tools_in(context: ValidationContext, *, author: bool) -> list[str]: """The AI tools the message under test names, sorted, whatever the policy. With *author*, a tool in the commit author's place counts too. This is a finding, not a verdict: it is what a pull request is labelled on, so it is reported under ``ai_attribution = "ignore"`` as well. """ message = BaseValidator._get_commit_message(context) tools = {s["tool"] for s in detect_ai_signatures(message)} if author: tool = detect_ai_author(*_author_identity(context)) if tool is not None: tools.add(tool) return sorted(tools) class AiAuthorValidator(BaseValidator): """Rejects a commit whose author is an AI tool (CC017). Under both ``forbid`` and ``disclose``: a tool in the author's place, with the person behind it at most a ``Co-authored-by:`` line, is the strongest attribution a commit can make. An existing commit (``--rev``, or HEAD) is judged by its recorded author; a message not yet committed by the author git would record for it, which honours ``GIT_AUTHOR_NAME`` and ``GIT_AUTHOR_EMAIL`` the way ``git commit`` does. """ def validate(self, context: ValidationContext) -> ValidationResult: if self._should_skip_commit_validation(context): return ValidationResult.SKIP name, email = _author_identity(context) identity = f"{name} <{email}>" if email else name self._checked_value = identity tool = detect_ai_author(name, email) if tool is None: return ValidationResult.PASS if _is_pending(context): # Usually no commit exists yet (a hook, a piped message): --amend # would rewrite the one before it, and --reset-author on its own # records this same identity again. The Action pipes existing # pull request commits this way too, hence the last clause. # author.name and author.email outrank user.name and user.email, # so a tool named there survives setting the user.* pair alone. suggest = ( "Commit as yourself: set git config user.name and user.email " "to your own, and unset author.name, author.email, " "GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL if a tool set them; a " "commit that already exists then needs " "git commit --amend --reset-author" ) else: suggest = "Author the commit yourself: git commit --amend --reset-author" if self.rule.value == "disclose": trailers = self.rule.allowed or list(DEFAULT_AI_DISCLOSURE_TRAILERS) suggest += f', and disclose the tool with "{trailers[0]}: {tool}"' self._print_failure( identity, error=f"An AI tool is the commit author: {tool}", suggest=suggest, ) return ValidationResult.FAIL #: A task-list item, as GitHub renders one: a bullet or a number, a box, #: and the item's text. The box holds a space, ``x`` or ``X``. _CHECKBOX = re.compile(r"^ {0,3}(?:[-*+]|\d{1,9}[.)])[ \t]+\[([ xX])\][ \t]+(\S.*)") #: The opening line of a fenced code block: its run of backticks or tildes. _FENCE_OPEN = re.compile(r"^ {0,3}(`{3,}|~{3,})") #: A closing fence: the same mark, at least as many times, and nothing after. _FENCE_CLOSE = re.compile(r"^ {0,3}(`{3,}|~{3,})[ \t]*$") #: Markdown emphasis and code marks, which change how a box's text looks but #: not what it says: ``**No AI tools were used**`` is the box "No AI tools #: were used". _EMPHASIS = re.compile(r"[*_`~]") def _plain(text: str) -> str: """*text* without emphasis marks, in one case, spaces collapsed.""" return " ".join(_EMPHASIS.sub("", text).split()).casefold() def _without_comments(line: str, in_comment: bool) -> tuple[str, bool]: """*line* with its HTML comments left out, and whether one is still open. GitHub does not show a comment, and one left open hides the rest of the text, as it does on the page. """ shown = "" while line: if in_comment: end = line.find("-->") if end < 0: return shown, True line, in_comment = line[end + 3 :], False else: start = line.find("