From bfb00578add877599fb5a0a5c373f72948043d27 Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:15:08 +0000 Subject: [PATCH] refactor: move main.py's code into an action package main.py held all 3,037 lines of the action. Its code now lives in action/, one module per part of the work, and main.py keeps only main() and the two helpers it calls: - escape: escaping text for the step log and workflow commands - inputs: the inputs, read from the environment action.yml sets - model: ScopeResult and the run's overall status - context: the event, the pull request and its commits - base_config: config-source: base - cli: running commit-check and turning its JSON into scopes - render: the step log and the Markdown report - publish: job summary, result output, PR comment, AI label Nothing changed in what the action does. Every function, class and constant is moved as is; a name used from another module is now written as module.name, so a test patches it in one place. action.yml still runs main.py, and the action's output is byte for byte the same. The tests change only where they reach the code: main.X becomes module.X and patch("main.X") becomes patch("action.module.X"). Coverage now measures main.py and action/, and stays at 100%. --- .github/workflows/ci.yml | 2 +- action/__init__.py | 1 + action/base_config.py | 225 +++ action/cli.py | 610 ++++++++ action/context.py | 360 +++++ action/escape.py | 46 + action/inputs.py | 114 ++ action/model.py | 135 ++ action/publish.py | 353 +++++ action/render.py | 1212 +++++++++++++++ main.py | 3012 +------------------------------------ tests/base_config_test.py | 91 +- tests/cli_test.py | 619 ++++---- tests/context_test.py | 288 ++-- tests/helpers.py | 26 +- tests/inputs_test.py | 116 +- tests/integration_test.py | 31 +- tests/log_test.py | 34 +- tests/main_test.py | 95 +- tests/model_test.py | 26 +- tests/publish_test.py | 271 ++-- tests/report_test.py | 356 ++--- 22 files changed, 4078 insertions(+), 3945 deletions(-) create mode 100644 action/__init__.py create mode 100644 action/base_config.py create mode 100644 action/cli.py create mode 100644 action/context.py create mode 100644 action/escape.py create mode 100644 action/inputs.py create mode 100644 action/model.py create mode 100644 action/publish.py create mode 100644 action/render.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fb07eb9..3a67b12 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,7 +61,7 @@ jobs: pip install pytest pytest-cov - name: Run tests with coverage run: | - pytest --cov=main --cov-report=xml --cov-report=term-missing tests + pytest --cov=main --cov=action --cov-report=xml --cov-report=term-missing tests - name: Upload coverage to Codecov uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: diff --git a/action/__init__.py b/action/__init__.py new file mode 100644 index 0000000..584dd41 --- /dev/null +++ b/action/__init__.py @@ -0,0 +1 @@ +"""The code behind main.py, split by what each part does.""" diff --git a/action/base_config.py b/action/base_config.py new file mode 100644 index 0000000..ed4ab3c --- /dev/null +++ b/action/base_config.py @@ -0,0 +1,225 @@ +"""config-source: base, which checks a pull request against its base branch's config.""" + +import os +import subprocess +import tempfile +import tomllib + +from action import context, escape, inputs + +#: The config files commit-check looks for, in its order. +CONFIG_PATHS = ( + "cchk.toml", + "commit-check.toml", + ".github/cchk.toml", + ".github/commit-check.toml", +) + +#: Passed to every commit-check run: ``--config`` and the base branch's +#: config, when ``config-source`` is ``base``; empty otherwise. +CONFIG_ARGS: list[str] = [] + + +class BaseConfigError(Exception): + """The base branch's config is there but cannot be used as it is.""" + + +def _base_blob(sha: str, path: str) -> bytes | None: + """The file at ``path`` in commit ``sha``, or ``None`` when it has none. + + Absence is read from the commit's tree, so a file that is there but + cannot be read -- a blob a partial clone could not fetch -- is an error, + never taken for no config. A symbolic link is refused: its blob is the + target's path, not the config. + + :raises BaseConfigError: If the file is there but cannot be read. + """ + try: + listed = subprocess.run( + ["git", "ls-tree", "--full-tree", sha, "--", path], + capture_output=True, + check=False, + ) + if listed.returncode != 0: + raise BaseConfigError(f"git could not list {path} in the base commit") + if not listed.stdout: + return None + mode, kind, _rest = listed.stdout.split(b" ", 2) + if kind != b"blob": + return None # a folder of that name is no config file + if mode == b"120000": + raise BaseConfigError( + f"{path} is a symbolic link on the base branch, which " + "config-source: base does not follow" + ) + result = subprocess.run( + ["git", "cat-file", "blob", f"{sha}:{path}"], + capture_output=True, + check=False, + ) + except OSError as e: + raise BaseConfigError(f"git could not run: {e}") from e + if result.returncode != 0: + raise BaseConfigError(f"{path} could not be read from the base commit") + return result.stdout + + +def _checked_out_config() -> tuple[str, bytes] | None: + """The config file the checkout holds, as (path, contents), or ``None``.""" + for path in CONFIG_PATHS: + if os.path.isfile(path): + with open(path, "rb") as f: + return path, f.read() + return None + + +def _local_parent(data: bytes) -> str | None: + """A config's ``inherit_from`` when it names a local file. + + A ``github:`` or HTTPS parent is fetched from where it names, whichever + branch the config came from; only a local file could be read from the + pull request. + """ + try: + parent = tomllib.loads(data.decode("utf-8")).get("inherit_from") + except (UnicodeDecodeError, tomllib.TOMLDecodeError): + return None # commit-check reports the broken file itself + if not isinstance(parent, str) or not parent: + return None + if parent.startswith(("github:", "https://", "http://")): + return None + return parent + + +def _repo_path(work: str, path: str) -> str | None: + """``path`` under ``work`` as a repository path, or ``None`` outside it.""" + path = os.path.normpath(path) + if os.path.commonpath([work, path]) != work: + return None + return os.path.relpath(path, work).replace(os.sep, "/") + + +def _config_error(text: str) -> bool: + print(f"::error title=commit-check::{escape._annotation_escape(text)}") + return False + + +def use_base_config() -> bool: + """With ``config-source: base``, point every check at the base config. + + The base branch's config file is written under ``RUNNER_TEMP`` at its + path in the repository, and ``CONFIG_ARGS`` names it. A parent it names + by local path (``inherit_from``) is copied from the base branch too, to + the path commit-check tries first, next to the config; otherwise + commit-check would go on to find the pull request's copy. Without a + config on the base branch the checks run on the defaults. + + Fails closed: if the base branch cannot be read, the step fails rather + than check against a config the pull request may have changed. + + Returns whether the checks can run. + """ + if inputs.CONFIG_SOURCE != "base": + return True + if not context.is_pr_event(): + print( + "::notice title=commit-check::config-source: base applies to pull " + "requests; this run reads the checked-out config" + ) + return True + sha = context.get_pr_base_sha() + if not sha or not (context._rev_resolves(sha) or context._fetch_commit(sha)): + return _config_error( + "config-source is base, but the base branch commit could not be " + f"read ({context.checkout_hint()}); nothing was checked, so that a config " + "the pull request changes cannot apply" + ) + try: + return _stage_base_config(sha) + except BaseConfigError as e: + return _config_error(f"config-source is base, but {e}; nothing was checked") + + +def _stage_base_config(sha: str) -> bool: + """Write the base commit's config under ``RUNNER_TEMP``; see above.""" + found = None + for path in CONFIG_PATHS: + data = _base_blob(sha, path) + if data is not None: + found = (path, data) + break + path, data = found or ("cchk.toml", b"") + work = os.path.realpath( + tempfile.mkdtemp(prefix="commit-check-config-", dir=os.getenv("RUNNER_TEMP")) + ) + target = os.path.join(work, *path.split("/")) + os.makedirs(os.path.dirname(target), exist_ok=True) + with open(target, "wb") as f: + f.write(data) + + parent = _local_parent(data) + if parent is not None: + if os.path.isabs(parent) or parent.startswith(("/", "\\")): + return _config_error( + f"config-source is base, but the base branch config {path} " + f'inherits from "{parent}", an absolute path the base branch ' + "cannot vouch for; nothing was checked" + ) + # The path as commit-check builds it, next to the config. Checked + # with this platform's separators, so "..\\x" cannot climb out on + # Windows. + dest = os.path.join(os.path.dirname(target), parent) + beside = _repo_path(work, dest) + if beside is None: + return _config_error( + f"config-source is base, but the base branch config {path} " + f'inherits from "{parent}", outside the repository; nothing ' + "was checked" + ) + # commit-check looks next to the config first, then from the top of + # the repository; whichever the base branch holds is copied to the + # first place, so the second is never reached. + top = _repo_path(work, os.path.join(work, parent)) + parent_data = None + for candidate in [beside] + ([top] if top else []): + parent_data = _base_blob(sha, candidate) + if parent_data is not None: + break + if parent_data is None: + # As on the base branch itself, a parent that is missing leaves + # the config in force; the empty copy keeps the pull request's + # file, if it adds one, from being read in its place. + print( + "::notice title=commit-check::" + + escape._annotation_escape( + f'inherit_from "{parent}" in {path} is not on the base ' + "branch; checking with that config alone" + ) + ) + parent_data = b"" + # A parent that names a folder ("." or the config's own folder) is + # no file: commit-check says so and keeps the config, as it would on + # the base branch. + if not os.path.isdir(os.path.normpath(dest)): + # The folders of the path as written, so that "policies/../x" + # resolves here too, not from the checkout. + os.makedirs(os.path.dirname(dest), exist_ok=True) + with open(os.path.normpath(dest), "wb") as f: + f.write(parent_data) + + CONFIG_ARGS[:] = ["--config", target] + if _checked_out_config() != found: + if found is None: + text = ( + "This pull request adds a commit-check config. The checks " + "use the defaults, as the base branch has no config; the new " + "config takes effect after it merges" + ) + else: + text = ( + f"This pull request changes the commit-check config. The " + f"checks use {path} from the base branch; the change takes " + "effect after it merges" + ) + print(f"::notice title=commit-check::{escape._annotation_escape(text)}") + return True diff --git a/action/cli.py b/action/cli.py new file mode 100644 index 0000000..ad78dc5 --- /dev/null +++ b/action/cli.py @@ -0,0 +1,610 @@ +"""Running commit-check and turning its JSON into scopes.""" + +import json +import os +import subprocess +import sys +import tempfile +from typing import Any + +from action import base_config, context, escape, inputs, model + +#: Human-readable labels for the non-message CLI flags. +CHECK_LABELS = { + "--branch": "Branch", + "--author-name": "Author name", + "--author-email": "Author email", +} + +#: Label of the scopes that check the files a commit changes (``files: true``). +FILES_LABEL = "Files" + +#: The AI attribution rules: what ``message-ai-attribution: true`` keeps. +AI_RULE_IDS = frozenset({"CC013", "CC014", "CC015", "CC016", "CC017"}) + +#: The checks whose subject is a commit's recorded author. +AUTHOR_FLAGS = ("--author-name", "--author-email") + +#: The rule each author check runs, for a scope that had to be skipped. +AUTHOR_RULES = { + "--author-name": ("CC101", "author_name"), + "--author-email": ("CC102", "author_email"), +} + + +def skipped_author_scope(flag: str) -> model.ScopeResult: + """A scope recording that an author check could not run at all. + + Reported as ``skip``, never as a pass: nothing was validated, and the + one commit the clone does hold (HEAD) has the wrong author for a pull + request, GitHub's merge commit or the base branch. + """ + rule_id, check = AUTHOR_RULES[flag] + return model.ScopeResult( + label=CHECK_LABELS[flag], + checks=[ + { + "rule_id": rule_id, + "check": check, + "status": "skip", + "value": "", + "error": "", + "suggest": "", + "docs_url": "", + "reason": "the pull request's head commit could not be resolved", + } + ], + ) + + +#: Why a files scope checked nothing. +FILES_UNCONFIGURED = "no rule is set in the [files] section of the config" + +FILES_NOT_IN_CLONE = "the checkout lacks the commit or its parent" + +FILES_UNLISTED = "the pull request's commits could not be listed" + +FILES_NOTHING_CHANGED = "the commit adds or changes no file" + + +def skipped_files_scope(reason: str, sha: str = "") -> model.ScopeResult: + """A scope recording that the files of a commit, or of all, went unchecked. + + Reported as ``skip``, never as a pass: nothing was validated. + """ + return model.ScopeResult( + label=FILES_LABEL, + sha=sha, + checks=[ + { + "rule_id": "", + "check": "files", + "status": "skip", + "value": "", + "error": "", + "suggest": "", + "docs_url": "", + "reason": reason, + } + ], + ) + + +#: Why an AI-only scope ran no rule: under the default policy there is none to run. +AI_POLICY_IGNORED = 'ai_attribution is "ignore": set it to "forbid" or "disclose"' + + +def skip_when_no_ai_rule_ran(scope: model.ScopeResult) -> model.ScopeResult: + """Report an AI-only scope that ran no rule as skipped, not passed. + + Under the default ``ai_attribution = "ignore"`` the CLI builds none of + the AI rules, so it returns an empty list of checks. Shown as a pass, that + read as "checked, nothing found" to someone who turned the input on and + forgot the policy. + """ + if scope.checks or scope.raw_text: + return scope + scope.checks = [ + { + "rule_id": "CC013", + "check": "ai_attribution", + "status": "skip", + "value": "", + "error": "", + "suggest": "", + "docs_url": "", + "reason": AI_POLICY_IGNORED, + } + ] + return scope + + +def _message_value(scope: model.ScopeResult) -> str: + """The whole commit message, as the CLI's ``message`` rule reports it.""" + return next( + ( + str(c.get("value") or "") + for c in scope.checks + if c.get("check") == "message" + ), + "", + ) + + +def keep_ai_rules(scope: model.ScopeResult) -> model.ScopeResult: + """Narrow a commit message scope to the AI rules (CC013 to CC017). + + ``message-ai-attribution: true`` does this whatever ``message`` says: + ``message`` defaults to true, so asking for the AI rules alone must not + need it turned off as well. The CLI runs every message rule and the + format rules' verdicts are dropped here, so the CLI needs no flag of + its own for it. A scope left with no rule, under the default + ``ai_attribution = "ignore"``, is reported as skipped. + """ + if not inputs.MESSAGE_AI_ATTRIBUTION_ENABLED or scope.raw_text: + return scope + # The message rule's value is the whole message: keep it for the report + # before the rule itself is dropped (outside a PR nothing was piped in). + scope.text = scope.text or _message_value(scope) + scope.checks = [c for c in scope.checks if c.get("rule_id") in AI_RULE_IDS] + return skip_when_no_ai_rule_ran(scope) + + +def _rule_key(check: dict[str, str]) -> str: + """What names a rule within one scope: its ID, or its name without one.""" + return check.get("rule_id") or check.get("check", "") + + +def lines_removed(text: str, fixed: str) -> list[str]: + """The non-blank lines of ``text`` that ``fixed`` no longer has, in order. + + A line repeated in ``text`` counts once per copy ``fixed`` dropped. + """ + kept: dict[str, int] = {} + for line in fixed.splitlines(): + kept[line] = kept.get(line, 0) + 1 + removed = [] + for line in text.splitlines(): + if kept.get(line, 0): + kept[line] -= 1 + elif line.strip(): + removed.append(line.strip()) + return removed + + +def name_the_line_changes(scope: model.ScopeResult, body: str) -> None: + """Name the lines to change instead of repeating the description. + + For a message the CLI's ``fix`` is the corrected text, short enough to + paste. A description can run to a page, and the summary, the comment and + the annotation would each repeat it in full; the lines to delete or add + are what its author needs. + """ + for check in scope.checks: + fixed = check.get("fix") or "" + if not fixed: + continue + removed = lines_removed(body, fixed) + added = lines_removed(fixed, body) + scope.edits[_rule_key(check)] = (removed, added) + parts = [] + if removed: + parts.append("remove " + "; ".join(f'"{line}"' for line in removed)) + if added: + parts.append("add " + "; ".join(f'"{line}"' for line in added)) + if parts: + check["suggest"] = "In the description, " + ", and ".join(parts) + check["fix"] = "" + + +#: The AI tools found in the pull request description when it was read for +#: the label only (``ai-label`` without ``pr-body-ai-attribution``), so it is no scope. +PR_BODY_AI_TOOLS: list[str] = [] + +#: Notices already relayed, so one repeated across every scope is shown once. +_RELAYED_NOTICES: set[str] = set() + + +def _relay_cli_notices(text: str) -> None: + """Put the CLI's stderr in the job log, without repeating it. + + The Action runs commit-check once per scope and once per commit in the + pull request, and a notice about the configuration is the same every + time; printed on each run it would bury the findings. + """ + for line in text.splitlines(): + line = line.strip() + if line and line not in _RELAYED_NOTICES: + _RELAYED_NOTICES.add(line) + print(f"commit-check: {escape._log_safe(line)}", file=sys.stderr) + + +def run_check_json( + args: list[str], + input_text: str | None = None, + env: dict[str, str] | None = None, +) -> tuple[int, dict[str, Any] | None, str]: + """Run ``commit-check --format json`` and return (exit code, parsed JSON, raw output). + + The CLI's contract is that stdout holds the JSON and nothing else, while + stderr carries what it has to say to a person: a parent config it could + not fetch, a flag whose every rule the config switched off, a dry run + that softened its own verdict. Those lines are not JSON, so they are + read separately and relayed to the job log rather than handed to the + parser -- merged into stdout they turned a passing run into an + unparsable one, which ScopeResult reports as a failure. + + The parsed JSON is ``None`` when the CLI did not produce valid JSON; the + raw output is kept so callers can fall back to showing it as text, and + in that case it carries both streams so nothing the CLI said is lost. + """ + command = ["commit-check", "--format", "json", *base_config.CONFIG_ARGS] + args + result = subprocess.run( + command, + input=input_text, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + env={**os.environ, **env} if env else None, + ) + out = result.stdout or "" + err = result.stderr or "" + _relay_cli_notices(err) + try: + return result.returncode, json.loads(out), out + except json.JSONDecodeError: + # Whatever went wrong, the operator needs everything the CLI said, + # so stderr joins stdout here -- and only here, where there is no + # JSON left to protect. It is often the whole story: a config the + # CLI refused leaves stdout empty and prints "Error: ..." on stderr, + # and dropping it would leave an empty raw_text that reads as a pass. + if not err.strip(): + return result.returncode, None, out + parts = [part for part in (out.strip(), err.strip()) if part] + return result.returncode, None, "\n".join(parts) + + +def check_scope( + label: str, + args: list[str], + input_text: str | None = None, + sha: str = "", + env: dict[str, str] | None = None, +) -> model.ScopeResult: + """Run commit-check for one scope and wrap the outcome in a ScopeResult. + + ``sha`` names the commit a message scope checked; it rides along on both + outcomes so an unparsable CLI response still says which commit it was. + """ + _rc, data, raw = run_check_json(args, input_text=input_text, env=env) + if isinstance(data, dict): + tools = data.get("ai_tools") + return model.ScopeResult( + label=label, + checks=data.get("checks", []), + sha=sha, + ai_tools=[str(t) for t in tools] if isinstance(tools, list) else [], + text=input_text or "", + ) + return model.ScopeResult(label=label, raw_text=raw, sha=sha) + + +def run_pr_message_checks(pr_commits: list[model.Commit]) -> list[model.ScopeResult]: + """Check each PR commit individually via commit-check --message. + + The raw message is piped in, so every commit is read the same way + whether the clone holds it or only the API listed it. Its own author + goes with it as git's author variables, which is where the CLI reads the + author of a piped message: the AI author rule (CC017) and + ``ignore_authors`` then judge that commit's author, not whoever HEAD or + the runner's git config names. + """ + results: list[model.ScopeResult] = [] + total = len(pr_commits) + for index, (sha, msg) in enumerate(pr_commits, start=1): + label = f"Commit {index}/{total}" + author = context.API_AUTHORS.get(sha) or ( + context._local_author(sha) if sha else None + ) + env = None + if author: + names = ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL") + env = {key: value for key, value in zip(names, author) if value} or None + if msg.strip(): + scope = check_scope(label, ["--message"], input_text=msg, sha=sha, env=env) + else: + scope = check_empty_message(label, sha, env) + results.append(keep_ai_rules(scope)) + return results + + +def run_pr_author_checks( + flags: list[str], pr_commits: list[model.Commit] +) -> list[model.ScopeResult]: + """Run the author checks on every author of the pull request's commits. + + Checking only the branch tip let an earlier commit by another author, + say a GitHub noreply address that ``author_email_pattern`` forbids, go + through. Each distinct author is checked once, on the newest commit + that carries it, so a one-person pull request still reports one scope + per check. A commit the clone lacks is fetched without its history. + + Returns ``[]`` when no author can be read, or a commit cannot be had + even by fetching it, so the caller falls back to the branch tip as before. + """ + newest: dict[tuple[str, str], str] = {} + for sha, _msg in pr_commits: + author = context.API_AUTHORS.get(sha) or ( + context._local_author(sha) if sha else None + ) + if author: + newest.pop(author, None) + newest[author] = sha + revs = [ + sha + for sha in newest.values() + if context._rev_resolves(sha) or context._fetch_commit(sha) + ] + if len(revs) != len(newest): + return [] + authors = {sha: author for author, sha in newest.items()} + scopes: list[model.ScopeResult] = [] + for flag in flags: + for sha in revs: + scope = check_scope(CHECK_LABELS[flag], [flag, "--rev", sha], sha=sha) + name, email = authors[sha] + scope.subject = name if flag == "--author-name" else email + scopes.append(scope) + return scopes + + +def _shallow_boundary() -> set[str]: + """The commits a shallow clone holds without their parents. + + Git lists them, one hash per line, in the repository's ``shallow`` file; + a complete clone has none. Such a commit looks like a root commit, so a + diff of it names every file in the repository as changed. + """ + try: + located = subprocess.run( + ["git", "rev-parse", "--git-path", "shallow"], + capture_output=True, + encoding="utf-8", + check=False, + ) + if located.returncode != 0: + return set() + with open(located.stdout.strip(), encoding="utf-8") as f: + return set(f.read().split()) + except OSError: + return set() + + +def run_files_checks(shas: list[str]) -> list[model.ScopeResult]: + """Check the files each commit changes, via ``commit-check --files --rev``. + + One scope per commit, so a finding names the commit that has to change: + a file added in one commit and removed in the next is still in the + history. A commit is only checked when the checkout holds it together + with its parent, since the files it changes are a diff against that + parent. The others are reported as skipped, never guessed at. + + With no rule set in ``[files]`` the CLI runs none, for any commit, and + one skipped scope says so in place of a row of empty passes. + """ + boundary = _shallow_boundary() + readable = { + sha + for sha in shas + if sha and sha not in boundary and context._rev_resolves(sha) + } + if not readable: + # Whether a rule is set at all, asked of HEAD: only the list of + # checks is read, never a verdict on HEAD itself. + probe = check_scope(FILES_LABEL, ["--files"]) + if not (probe.checks or probe.raw_text): + return [skipped_files_scope(FILES_UNCONFIGURED)] + context.warn_shallow_checkout( + "The checkout holds no commit to check together with its parent", + "the files check was skipped", + ) + return [skipped_files_scope(FILES_NOT_IN_CLONE)] + + results: list[model.ScopeResult] = [] + for sha in shas: + if sha not in readable: + results.append(skipped_files_scope(FILES_NOT_IN_CLONE, sha)) + continue + scope = check_scope(FILES_LABEL, ["--files", "--rev", sha], sha=sha) + if not (scope.checks or scope.raw_text): + return [skipped_files_scope(FILES_UNCONFIGURED)] + if scope.status == "skip" and not scope.skip_reason: + # The file rules skip a commit that only deletes, or merges + # without bringing a file along, and do not say why. + for check in scope.checks: + check["reason"] = FILES_NOTHING_CHANGED + results.append(scope) + missing = sum(1 for sha in shas if sha not in readable) + if missing: + context.warn_shallow_checkout( + f"{missing} of {len(shas)} commits are not in the checkout " + "together with their parent", + "their files were not checked", + ) + return results + + +def run_pr_files_checks(pr_commits: list[model.Commit]) -> list[model.ScopeResult]: + """Check the files of every commit of the pull request.""" + if not pr_commits: + context.warn_shallow_checkout( + "Could not list the pull request's commits", + "the files check was skipped", + ) + return [skipped_files_scope(FILES_UNLISTED)] + return run_files_checks([sha for sha, _msg in pr_commits]) + + +def check_empty_message( + label: str, sha: str, env: dict[str, str] | None +) -> model.ScopeResult: + """Check a commit whose message is empty, from an empty file. + + Piped, an empty message reads to the CLI as no input at all, and it + checks HEAD in its place: the merge commit, which passes. A file names + the message, so the empty one is judged (``allow_empty_commits``). + """ + fd, path = tempfile.mkstemp(prefix="commit-msg-", dir=os.getenv("RUNNER_TEMP")) + os.close(fd) + try: + return check_scope(label, ["--message", path], sha=sha, env=env) + finally: + os.unlink(path) + + +def run_other_checks( + args: list[str], rev: str | None = None +) -> list[model.ScopeResult]: + """Run each non-message check (branch, author) once, as its own scope. + + ``rev`` goes to the author checks only: it names the commit whose + recorded author is validated (commit-check >= 2.16.0), which in a PR is + the branch tip rather than GitHub's merge commit. The branch check has + no commit to point at, so it never takes it. + """ + results: list[model.ScopeResult] = [] + for flag in args: + label = CHECK_LABELS.get(flag) + if label: + cli_args = [flag] + if rev and flag in AUTHOR_FLAGS: + cli_args += ["--rev", rev] + results.append(check_scope(label, cli_args)) + return results + + +def build_check_args() -> list[str]: + """Map enabled validation switches to commit-check CLI arguments.""" + flags = [ + ("--message", inputs.MESSAGE_ENABLED or inputs.MESSAGE_AI_ATTRIBUTION_ENABLED), + ("--branch", inputs.BRANCH_ENABLED), + ("--author-name", inputs.AUTHOR_NAME_ENABLED), + ("--author-email", inputs.AUTHOR_EMAIL_ENABLED), + ] + return [flag for flag, enabled in flags if enabled] + + +def run_commit_check() -> tuple[int, list[model.ScopeResult]]: + """Runs all enabled checks and returns the overall exit code and results. + + Checks are evaluated in order: + 1. PR title (when ``pr-title: true`` and in a PR event) + 2. PR description, AI rules only (when ``pr-body-ai-attribution: true`` and in a PR + event; with only ``ai-label`` set it is read for the label, and no + scope is reported) + 3. Individual PR commit messages (when ``message: true`` and in a PR event; + AI rules only with ``message-ai-attribution: true``) + 4. The files each PR commit changes (when ``files: true``; outside a PR, + the files of the HEAD commit) + 5. Author checks on every PR commit's author, then the remaining checks + (branch; outside a PR, the HEAD commit and its author) + + Outside of a PR event all enabled checks are handed to the CLI at once. + """ + args = build_check_args() + results: list[model.ScopeResult] = [] + + # ---- 1. PR title check ------------------------------------------------ + if inputs.PR_TITLE_ENABLED and context.is_pr_event(): + pr_title = context.get_pr_title() + if pr_title: + # --pr-title runs the --message rules a one-line title can meet: + # none needing a body (CC011), a sign-off (CC012) or an author + # (CC017), and its advice does not say to re-commit. + results.append(check_scope("PR title", ["--pr-title"], input_text=pr_title)) + + # ---- 2. PR description ------------------------------------------------ + if ( + inputs.PR_BODY_AI_ATTRIBUTION_ENABLED or inputs.ai_label_name() + ) and context.is_pr_event(): + pr_body = context.get_pr_body() + if inputs.PR_BODY_AI_ATTRIBUTION_ENABLED: + # An empty description is checked too: it has no AI declaration, + # which CC501 fails when [pull_request] ai_declaration_checkboxes + # names the boxes. The attribution rules pass empty text. + scope = check_scope( + "PR description", ["--ai-attribution-only"], input_text=pr_body or "" + ) + name_the_line_changes(scope, pr_body or "") + results.append(skip_when_no_ai_rule_ran(scope)) + elif pr_body: + scope = check_scope( + "PR description", ["--ai-attribution-only"], input_text=pr_body + ) + PR_BODY_AI_TOOLS[:] = scope.ai_tools + + # ---- 3. Commit message checks ----------------------------------------- + pr_commits: list[model.Commit] | None = None + if inputs.MESSAGE_ENABLED or inputs.MESSAGE_AI_ATTRIBUTION_ENABLED: + pr_commits = context.get_pr_commit_messages() + if pr_commits: + # In PR context: check each commit individually to avoid + # only validating the synthetic merge commit at HEAD. + results.extend(run_pr_message_checks(pr_commits)) + args = [a for a in args if a != "--message"] + elif context.is_pr_event(): + # Falling through to HEAD validates the synthetic merge commit, + # "Merge X into Y", which passes CC001 by default: a shallow + # clone used to turn every pull request green without a word. + context.warn_shallow_checkout( + "Could not list the pull request's commits", "only HEAD was checked" + ) + + # Outside a PR, check the HEAD commit message directly. + if "--message" in args: + results.append( + keep_ai_rules( + check_scope("Commit message", ["--message"], sha=context.head_sha()) + ) + ) + args = [a for a in args if a != "--message"] + + # ---- 4. Files of each commit ------------------------------------------ + if inputs.FILES_ENABLED: + if context.is_pr_event(): + if pr_commits is None: + pr_commits = context.get_pr_commit_messages() + results.extend(run_pr_files_checks(pr_commits)) + else: + results.extend(run_files_checks([context.head_sha()])) + + # ---- 5. Remaining checks (branch, author, etc.) ----------------------- + rev = None + author_flags = [flag for flag in args if flag in AUTHOR_FLAGS] + if context.is_pr_event() and author_flags: + if pr_commits is None: + pr_commits = context.get_pr_commit_messages() + author_scopes = run_pr_author_checks(author_flags, pr_commits) + if author_scopes: + results.extend(author_scopes) + args = [a for a in args if a not in AUTHOR_FLAGS] + if context.is_pr_event() and any(flag in AUTHOR_FLAGS for flag in args): + rev = context.pr_head_rev() + if rev is None: + # HEAD's author is GitHub's merge commit on a pull_request + # checkout and the base branch on pull_request_target: checking + # it would grade the wrong person either way. Say so, and skip. + context.warn_shallow_checkout( + "Could not resolve the pull request's head commit for the " + "author checks", + "they were skipped", + ) + for flag in args: + if flag in AUTHOR_FLAGS: + results.append(skipped_author_scope(flag)) + args = [a for a in args if a not in AUTHOR_FLAGS] + results.extend(run_other_checks(args, rev=rev)) + + exit_code = model.exit_code_for(results) + return exit_code, results diff --git a/action/context.py b/action/context.py new file mode 100644 index 0000000..35b5eab --- /dev/null +++ b/action/context.py @@ -0,0 +1,360 @@ +"""The event, the pull request and its commits, read from git or the API.""" + +import json +import os +import subprocess +import sys +from typing import Any + +from action import escape, model + +COMMIT_MESSAGE_DELIMITER = "\x00" + +#: AI coding agents that open pull requests from their own GitHub App, by +#: login, with the tool each one is. The same list as the GitHub App's. +AI_AGENT_BOTS = { + "amazon-q-developer[bot]": "Amazon Q Developer", + "chatgpt-codex-connector[bot]": "OpenAI Codex", + "claude[bot]": "Claude Code", + "copilot-swe-agent[bot]": "GitHub Copilot", + "cursor[bot]": "Cursor", + "devin-ai-integration[bot]": "Devin", + "factory-droid[bot]": "Factory Droid", + "google-labs-jules[bot]": "Jules", +} + + +def is_pr_event() -> bool: + """Return whether the workflow was triggered by a PR-style event.""" + return os.getenv("GITHUB_EVENT_NAME", "") in {"pull_request", "pull_request_target"} + + +#: The one fix for every "history is too shallow" finding below. +SHALLOW_CHECKOUT_HINT = "is actions/checkout using fetch-depth: 0?" + +#: On pull_request_target the default checkout is the base branch, which +#: holds none of the pull request at any depth; the fix is to check the +#: pull request out. +TARGET_CHECKOUT_HINT = ( + "is the workflow checking out the pull request, e.g. " + "ref: refs/pull//merge with fetch-depth: 0?" +) + + +def checkout_hint() -> str: + """The fix for a checkout that does not hold the pull request.""" + if os.getenv("GITHUB_EVENT_NAME") == "pull_request_target": + return TARGET_CHECKOUT_HINT + return SHALLOW_CHECKOUT_HINT + + +#: The pull request branch tip. On ``refs/pull/N/merge`` HEAD is a merge +#: commit that GitHub authored, so its recorded author is +#: ``GitHub `` whatever the contributor configured; +#: HEAD^2 is the commit the contributor actually made. +PR_HEAD_REV = "HEAD^2" + + +def warn_shallow_checkout(problem: str, consequence: str) -> None: + """Annotate a PR run whose clone is too shallow to do what was asked. + + ``actions/checkout`` defaults to ``fetch-depth: 1``, which leaves the + synthetic merge commit as the only commit in the clone. Every caller + hits that same root cause, so they share one message shape that names + the fix rather than only the symptom. + """ + text = f"{problem} ({checkout_hint()}); {consequence}" + print(f"::warning title=commit-check::{escape._annotation_escape(text)}") + + +def get_pr_event() -> dict[str, Any]: + """The ``pull_request`` object from the event payload, or ``{}``.""" + if not is_pr_event(): + return {} + event_path = os.getenv("GITHUB_EVENT_PATH") + if not event_path: + return {} + try: + with open(event_path, "r", encoding="utf-8") as f: + event = json.load(f) + return event.get("pull_request") or {} + except Exception as e: # noqa: BLE001 - a bad payload warns, never fails the step + print(f"::warning::Failed to read the PR from the event: {e}", file=sys.stderr) + return {} + + +def get_pr_head_sha() -> str | None: + """The pull request's head commit, from the event payload.""" + return get_pr_event().get("head", {}).get("sha") or None + + +def get_pr_base_sha() -> str | None: + """The base branch tip the pull request targets, from the event payload.""" + return get_pr_event().get("base", {}).get("sha") or None + + +def _rev_resolves(rev: str) -> bool: + """Whether ``rev`` names a commit the clone actually has.""" + try: + result = subprocess.run( + ["git", "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"], + capture_output=True, + encoding="utf-8", + check=False, + ) + except OSError: + return False + return result.returncode == 0 + + +def _local_author(sha: str) -> tuple[str, str] | None: + """Author (name, email) of a commit the clone holds, or ``None``.""" + try: + result = subprocess.run( + ["git", "show", "-s", "--format=%an%x1f%ae", sha], + capture_output=True, + encoding="utf-8", + check=False, + ) + except OSError: + return None + name, sep, email = result.stdout.strip("\n").partition("\x1f") + if result.returncode != 0 or not sep: + return None + return name, email + + +def _fetch_commit(sha: str) -> bool: + """Fetch one commit, without its history, into a clone that lacks it.""" + try: + result = subprocess.run( + ["git", "fetch", "--no-tags", "--quiet", "--depth=1", "origin", sha], + capture_output=True, + encoding="utf-8", + check=False, + ) + except OSError: + return False + return result.returncode == 0 and _rev_resolves(sha) + + +def pr_head_rev() -> str | None: + """The commit whose recorded author the PR's author checks read. + + First choice is ``pull_request.head.sha`` from the event payload: it + names the branch tip for ``pull_request`` and ``pull_request_target`` + alike, whatever was checked out, as long as the clone has it. Failing + that, ``HEAD^2`` on a ``pull_request`` checkout, where HEAD is the + merge ref and its second parent is that same tip. Never ``HEAD^2`` on + ``pull_request_target``: there HEAD is the base branch, so ``HEAD^2`` + is nothing, or the parent of some unrelated merge on it. A shallow clone + that lacks the tip gets it fetched, without its history. + + ``None`` when neither can be had. + """ + sha = get_pr_head_sha() + if sha and (_rev_resolves(sha) or _fetch_commit(sha)): + return sha + if os.getenv("GITHUB_EVENT_NAME") == "pull_request" and _rev_resolves(PR_HEAD_REV): + return PR_HEAD_REV + return None + + +def get_pr_title() -> str | None: + """Read PR title from GitHub event payload.""" + if not is_pr_event(): + return None + event_path = os.getenv("GITHUB_EVENT_PATH") + if not event_path: + return None + try: + with open(event_path, "r", encoding="utf-8") as f: + event = json.load(f) + return event.get("pull_request", {}).get("title") + except Exception as e: # noqa: BLE001 - a bad payload warns, never fails the step + print(f"::warning::Failed to read PR title from event: {e}", file=sys.stderr) + return None + + +def get_pr_body() -> str | None: + """Read the pull request description from the event payload. + + GitHub sends ``null`` for a pull request opened with no description. + """ + body = get_pr_event().get("body") + return body if isinstance(body, str) and body.strip() else None + + +def get_pr_opener_tool() -> str | None: + """The AI tool that opened the pull request from its own app, if any.""" + login = (get_pr_event().get("user") or {}).get("login") or "" + return AI_AGENT_BOTS.get(str(login).lower()) + + +#: ``git log`` format that yields, per commit, the full hash and the raw +#: message as two NUL-terminated fields (``%x00`` is git's spelling of +#: COMMIT_MESSAGE_DELIMITER; a literal NUL cannot be passed as an argument). +#: NUL cannot appear in a hash or a message, so the split is unambiguous +#: however many blank lines the message holds. +COMMIT_LOG_FORMAT = "--pretty=format:%H%x00%B%x00" + + +def parse_commit_messages(output: str) -> list[model.Commit]: + """Split ``git log`` output (see ``COMMIT_LOG_FORMAT``) into commits. + + The fields alternate hash, message, hash, message; git puts a newline + between commits, which lands on the front of the next hash and is + stripped along with the message's trailing newline. A commit with an + empty message is kept, as ``(sha, "")``: it is a commit of the pull + request like any other, and ``allow_empty_commits`` is the rule that + judges it. + """ + fields = [f.strip("\n") for f in output.split(COMMIT_MESSAGE_DELIMITER)] + return [(sha, message) for sha, message in zip(fields[0::2], fields[1::2]) if sha] + + +def _messages_in_range(revision_range: str) -> list[model.Commit]: + """Commits in ``revision_range`` as ``(sha, message)``, oldest first, or ``[]``.""" + result = subprocess.run( + ["git", "log", COMMIT_LOG_FORMAT, "--reverse", revision_range], + capture_output=True, + encoding="utf-8", + check=False, + ) + if result.returncode == 0 and result.stdout: + return parse_commit_messages(result.stdout) + return [] + + +def head_sha() -> str: + """The full hash of HEAD, or ``""`` when git cannot say. + + Only decoration for the non-PR ``Commit message`` scope, so a failure + here never fails the run: the message is still checked, just unlabelled. + """ + try: + result = subprocess.run( + ["git", "rev-parse", "HEAD"], + capture_output=True, + encoding="utf-8", + check=False, + ) + except OSError: + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def get_messages_from_event_range() -> list[model.Commit]: + """Read PR commit messages between the payload's base and head commits. + + ``pull_request.base.sha`` and ``pull_request.head.sha`` name the pull + request whatever the workflow checked out, for ``pull_request`` and + ``pull_request_target`` alike; the range is usable whenever the clone + holds both commits. + """ + base_sha, head_sha = get_pr_base_sha(), get_pr_head_sha() + if not (base_sha and head_sha): + return [] + if not (_rev_resolves(head_sha) and _rev_resolves(base_sha)): + return [] + return _messages_in_range(f"{base_sha}..{head_sha}") + + +def get_messages_from_merge_ref() -> list[model.Commit]: + """Read PR commit messages from GitHub's synthetic merge commit. + + Only meaningful on a ``pull_request`` checkout, where HEAD is + ``refs/pull/N/merge``. On ``pull_request_target`` HEAD is the base + branch: ``HEAD^2`` is then nothing, or the parent of some unrelated + merge on it, whose commits are not the pull request's. + """ + if os.getenv("GITHUB_EVENT_NAME") != "pull_request": + return [] + return _messages_in_range("HEAD^1..HEAD^2") + + +def get_messages_from_head_ref(base_ref: str) -> list[model.Commit]: + """Read PR commit messages when the workflow checks out the head SHA.""" + return _messages_in_range(f"origin/{base_ref}..HEAD") + + +#: The most commits GitHub's pull request commits endpoint returns. +API_COMMIT_LIMIT = 250 + +#: Author (name, email) of each commit listed by the API, by hash. Those +#: commits are not in the clone, so this is the only record of who wrote them. +API_AUTHORS: dict[str, tuple[str, str]] = {} + + +def get_messages_from_api() -> list[model.Commit]: + """The pull request's commits from the REST API, for a clone without them. + + The default ``actions/checkout`` clone holds only GitHub's merge commit. + Deepening it cannot list a pull request that merged its base branch in; + the API lists any pull request exactly. It stops at 250 commits, so a + longer one is left unlisted rather than checked in part. + """ + pr = get_pr_event() + number, total = pr.get("number"), pr.get("commits", 0) + token, repo = os.getenv("GITHUB_TOKEN"), os.getenv("GITHUB_REPOSITORY") + if not (number and token and repo) or total > API_COMMIT_LIMIT: + return [] + from github import Auth, Github # type: ignore + + api_url = os.getenv("GITHUB_API_URL", "https://api.github.com") + pull = ( + Github(auth=Auth.Token(token), base_url=api_url).get_repo(repo).get_pull(number) + ) + listed = list(pull.get_commits()) + commits = [(c.sha, c.commit.message) for c in listed] + for c in listed: + author = c.commit.author + if author is not None: + API_AUTHORS[c.sha] = (author.name or "", author.email or "") + # A force push after the event can leave the same count but other commits. + head = get_pr_head_sha() + if len(commits) != total or (head and commits[-1][0] != head): + return [] + return commits + + +def get_pr_commit_messages() -> list[model.Commit]: + """Get all commits, as ``(sha, message)``, for the current PR workflow. + + The event payload's ``base.sha..head.sha`` is tried first: it names the + pull request exactly, whatever was checked out. On a ``pull_request`` + checkout HEAD is the synthetic merge commit, so ``HEAD^1..HEAD^2`` is + the same range. If the workflow checks out the PR head SHA instead, + diff against ``origin/`` when that ref is available locally. + A clone that holds none of these, or only part of the pull request (a + shallow boundary ends a range early), asks the API. + """ + if not is_pr_event(): + return [] + + try: + base_ref = os.getenv("GITHUB_BASE_REF", "") + messages = ( + get_messages_from_event_range() + or get_messages_from_merge_ref() + or (get_messages_from_head_ref(base_ref) if base_ref else []) + ) + total = get_pr_event().get("commits") + if messages and (not total or len(messages) == total): + return messages + from_api = get_messages_from_api() + if from_api: + return from_api + if messages: + warn_shallow_checkout( + f"Only {len(messages)} of the pull request's {total} commits " + "could be listed", + "the others were not checked", + ) + return messages + except Exception as e: # noqa: BLE001 - warn, then check what we have + print( + f"::warning::Failed to retrieve PR commit messages: {e}", + file=sys.stderr, + ) + return [] diff --git a/action/escape.py b/action/escape.py new file mode 100644 index 0000000..ea71c29 --- /dev/null +++ b/action/escape.py @@ -0,0 +1,46 @@ +"""Escaping text the action prints into the step log or a workflow command.""" + +import re + + +def _annotation_escape(text: str) -> str: + """Escape text for a workflow command payload. + + A newline would end the command and leave the rest of the message as a + stray log line, and a bare ``%`` can be read as the start of an escape. + """ + return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + + +#: C0 and C1 control characters, and DEL, except the newline and tab that a +#: multi-line commit message legitimately carries. +_CONTROL_CHARS = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]") + + +def _log_safe(text: str) -> str: + """Make commit-controlled text inert before it is printed to the step log. + + The tree prints values from the CLI's JSON, and those are whoever wrote + the commit, branch or pull request title: a multi-line value (a whole + message on a failing rule, a sign-off fix) prints each further line on a + line of its own. The runner reads any log line beginning with ``::`` as a + workflow command, after skipping leading whitespace, so indenting it is + not enough; and it reads the older ``##[command]`` form anywhere in a + line. Left as they are, such lines can forge annotations or mask log + text. So such a line gets a backslash before its ``::``, ``##[`` is broken + up, and control characters are shown as ``\\xNN`` escapes. This is the + CLI's own ``printable()`` (commit-check#620), which covers its text + output but not the JSON this action renders itself. + + Only the step log needs it: the Markdown report and the annotation + payloads are not read as commands. It runs before the log's own colours + are added, so an escape sequence in the log is always the action's. + """ + if text.isprintable() and "::" not in text and "##[" not in text: + return text # nothing to escape: the common case + text = _CONTROL_CHARS.sub(lambda m: f"\\x{ord(m.group()):02x}", text) + text = text.replace("##[", "#\\#[") + return "\n".join( + line.replace("::", "\\::", 1) if line.lstrip().startswith("::") else line + for line in text.split("\n") + ) diff --git a/action/inputs.py b/action/inputs.py new file mode 100644 index 0000000..a6306ba --- /dev/null +++ b/action/inputs.py @@ -0,0 +1,114 @@ +"""The action's inputs, read from the environment action.yml sets.""" + +import os +import sys + +from action import escape + +GITHUB_STEP_SUMMARY = os.getenv("GITHUB_STEP_SUMMARY", "") + +#: Boolean inputs whose value was neither true nor false, as ``(name, value)``. +#: ``main`` fails the step on them before any check runs. +INVALID_FLAGS: list[tuple[str, str]] = [] + + +def env_flag(name: str, default: str = "false") -> bool: + """Read a GitHub Action boolean input: ``true`` or ``false``, any case. + + Anything else (``yes``, ``on``, a typo) used to read as false and turn + the check off without a word. It is now recorded in ``INVALID_FLAGS``, + and the step fails with the input's name. + """ + value = os.getenv(name, default).strip().lower() + if value not in ("true", "false"): + INVALID_FLAGS.append((name, os.getenv(name, default))) + return value == "true" + + +MESSAGE_ENABLED = env_flag("MESSAGE") + +BRANCH_ENABLED = env_flag("BRANCH") + +AUTHOR_NAME_ENABLED = env_flag("AUTHOR_NAME") + +AUTHOR_EMAIL_ENABLED = env_flag("AUTHOR_EMAIL") + +FILES_ENABLED = env_flag("FILES") + +DRY_RUN_ENABLED = env_flag("DRY_RUN") + +JOB_SUMMARY_ENABLED = env_flag("JOB_SUMMARY") + +PR_COMMENTS_ENABLED = env_flag("PR_COMMENTS") + +PR_TITLE_ENABLED = env_flag("PR_TITLE") + +PR_BODY_AI_ATTRIBUTION_ENABLED = env_flag("PR_BODY_AI_ATTRIBUTION") + +MESSAGE_AI_ATTRIBUTION_ENABLED = env_flag("MESSAGE_AI_ATTRIBUTION") + +#: Where the checks read the config: ``head``, the files the workflow +#: checked out, or ``base``, the pull request's base branch, so that a pull +#: request cannot loosen the rules it is checked against. +CONFIG_SOURCES = ("head", "base") + +CONFIG_SOURCE = os.getenv("CONFIG_SOURCE", "head").strip().lower() or "head" + +#: The label ``ai-label: true`` puts on a pull request that an AI tool wrote. +DEFAULT_AI_LABEL = "ai-assisted" + + +def ai_label_name() -> str | None: + """The label to put on an AI-written pull request, or ``None`` for none. + + ``ai-label: true`` means the default label; any other value but + ``false`` is the label's own name. + """ + value = os.getenv("AI_LABEL", "false").strip() + if not value or value.lower() == "false": + return None + return DEFAULT_AI_LABEL if value.lower() == "true" else value + + +def log_env_vars(): + """Logs the environment variables for debugging purposes. + + Uses the ``::debug::`` workflow command so these only appear in the + action log when ``ACTIONS_STEP_DEBUG`` is set to ``true``. + """ + for name in ( + "MESSAGE", + "BRANCH", + "AUTHOR_NAME", + "AUTHOR_EMAIL", + "FILES", + "DRY_RUN", + "JOB_SUMMARY", + "PR_COMMENTS", + "PR_TITLE", + "PR_BODY_AI_ATTRIBUTION", + "MESSAGE_AI_ATTRIBUTION", + "AI_LABEL", + ): + value = os.getenv(name, "false") + print(f"::debug::{name}={value}") + print(f"::debug::CONFIG_SOURCE={CONFIG_SOURCE}") + + +def fail_on_invalid_flags() -> None: + """Stop with an error when an input holds a value it does not take.""" + invalid = CONFIG_SOURCE not in CONFIG_SOURCES + if not INVALID_FLAGS and not invalid: + return + for name, value in INVALID_FLAGS: + input_name = name.lower().replace("_", "-") + print( + f"::error::Input {input_name} must be true or false, got " + f"{escape._log_safe(repr(value))}" + ) + if invalid: + print( + "::error::Input config-source must be head or base, got " + f"{escape._log_safe(repr(os.getenv('CONFIG_SOURCE', '')))}" + ) + sys.exit(1) diff --git a/action/model.py b/action/model.py new file mode 100644 index 0000000..94a1d4f --- /dev/null +++ b/action/model.py @@ -0,0 +1,135 @@ +"""ScopeResult, the one shape every check result takes, and the run's overall status.""" + +from dataclasses import dataclass, field + + +@dataclass +class ScopeResult: + """Result of running commit-check against one scope (PR title, one commit, + branch, author, ...). + + ``checks`` holds the parsed JSON check outcomes (only set when the CLI + produced valid JSON); ``raw_text`` holds the raw CLI output when parsing + failed (a defensive fallback so unexpected output is never swallowed). + + ``sha`` is the full hash of the commit a message scope checked, or ``""`` + for scopes that have no commit (PR title, branch, author). It is kept + apart from ``label`` on purpose: ``label`` ("Commit 2/3") is what the + ``result`` output has always carried, so downstream steps can keep + matching on it, and the hash is appended only where a person reads it. + """ + + label: str + checks: list[dict[str, str]] = field(default_factory=list) + raw_text: str = "" + sha: str = "" + #: The AI tools the CLI found in what this scope checked (``ai_tools``). + ai_tools: list[str] = field(default_factory=list) + #: The text this scope checked (a commit message, the PR title), when the + #: action piped it in. The report compares it with a rule's ``fix`` to name + #: the lines to change. Never part of the ``result`` output. + text: str = "" + #: ``(removed, added)`` lines per rule, for a text too long to carry as a + #: ``fix`` (the PR description). Keyed by ``_rule_key``. + edits: dict[str, tuple[list[str], list[str]]] = field(default_factory=dict) + #: What an author check looked at (the name or the email), which the CLI + #: does not report for a skipped one; the listing shows it in that row. + subject: str = "" + + @property + def display_label(self) -> str: + """The label as a reader sees it: ``Commit 2/3 (5584f46)``. + + Seven characters, like ``git log --oneline``; the full hash goes + into the link and the ``result`` output, where it is not read by eye. + """ + return f"{self.label} ({self.sha[:7]})" if self.sha else self.label + + @property + def status(self) -> str: + """Overall status: ``pass``, ``fail``, ``warn``, or ``skip``. + + ``skip`` means every rule in this scope declined to run — the author + is on an ``ignore_authors`` list, or there was nothing to check. It + is reported separately from ``pass`` because a skipped scope + validated nothing, and rendering the two identically let a bypassed + policy read as an enforced one. + + ``warn`` means a rule found something but is listed under the + config's top-level ``warn``, so commit-check reports it without + failing the run. A real failure still outranks a warning in the same + scope (CC202 stands in for ``branch`` when the two disagree), and a + single real verdict — failing or warning — outranks the skips: a + scope is ``skip`` only when *all* of its checks skipped. + """ + if self.raw_text and not self.checks: + return "fail" + if any(c["status"] == "fail" for c in self.checks): + return "fail" + if any(c["status"] == "warn" for c in self.checks): + return "warn" + if self.checks and all(c["status"] == "skip" for c in self.checks): + return "skip" + return "pass" + + @property + def skip_reason(self) -> str: + """Why a skipped scope did not run, or ``""`` when nobody said. + + Newer commit-check releases name the reason on each skipped check (e.g. + "author dependabot[bot] is in [commit].ignore_authors"). A bare + "skipped" left the reader unable to tell a deliberate bypass from a + broken setup. + """ + if self.status != "skip": + return "" + return next((c["reason"] for c in self.checks if c.get("reason")), "") + + @property + def failures(self) -> list[dict[str, str]]: + """The checks that failed in this scope.""" + return [c for c in self.checks if c["status"] == "fail"] + + @property + def warnings(self) -> list[dict[str, str]]: + """The checks reported as warnings in this scope.""" + return [c for c in self.checks if c["status"] == "warn"] + + +def overall_status(results: list[ScopeResult]) -> str: + """Reduce scope statuses to one of ``pass``/``fail``/``warn``/``skip``. + + One function, used by every completion path, because the alternative + is what this replaced: four separate ``all(... == "pass")`` tests, each + correct only while exactly two statuses existed. The moment ``skip`` + appeared they all silently reclassified a skipped run as a failure. + + Precedence is fail, then skip, then warn, then pass. ``skip`` requires + at least one scope and all of them skipped: nothing was validated, and a + warning cannot have been found where nothing ran. ``warn`` means at + least one scope carries a finding the config listed under ``warn`` and + nothing failed. It is distinct from ``pass`` so a downstream step can + act on a bent-but-not-broken policy without walking every scope; the + exit code does not distinguish the two (see ``exit_code_for``), because + the whole point of ``warn`` is that it never fails the workflow. + """ + if any(scope.status == "fail" for scope in results): + return "fail" + if results and all(scope.status == "skip" for scope in results): + return "skip" + if any(scope.status == "warn" for scope in results): + return "warn" + return "pass" + + +def exit_code_for(results: list[ScopeResult]) -> int: + """Only a failure is an error. + + A skipped run validated nothing, but it violated no policy either, so + it must not fail the workflow. + """ + return 1 if overall_status(results) == "fail" else 0 + + +#: One commit to check: ``(full sha, message)``. +Commit = tuple[str, str] diff --git a/action/publish.py b/action/publish.py new file mode 100644 index 0000000..67972a1 --- /dev/null +++ b/action/publish.py @@ -0,0 +1,353 @@ +"""Where results go: the job summary, the result output, the PR comment and +the AI label.""" + +import json +import os +import sys +import uuid +from typing import Any + +from action import cli, context, inputs, model, render + +#: Prefixes of report bodies written by earlier versions, kept so the first run +#: after upgrading adopts the existing comment instead of posting a second one. +#: Drop these once a release has been out long enough. +LEGACY_TITLES = ("# Commit Check", "# Commit-Check") + +#: The colour a label gets when the Action has to create it. +AI_LABEL_COLOR = "8250df" + + +def add_job_summary(results: list[model.ScopeResult]) -> int: + """Adds the commit check result to the GitHub job summary.""" + if not inputs.JOB_SUMMARY_ENABLED or not inputs.GITHUB_STEP_SUMMARY: + return 0 + + with open(inputs.GITHUB_STEP_SUMMARY, "a", encoding="utf-8") as summary_file: + summary_file.write(render.render_job_summary(results)) + + return model.exit_code_for(results) + + +def set_result_output(results: list[model.ScopeResult]) -> None: + """Expose the structured results as the ``result`` action output. + + Written through :func:`_write_output`, whose per-write random delimiter + keeps a line of user text (a commit subject reading ``EOF``, say) from + closing the heredoc early. + """ + output_path = os.getenv("GITHUB_OUTPUT") + if not output_path: + return + payload = { + "status": model.overall_status(results), + "ai_tools": ai_tools_found(results), + "scopes": [ + { + "label": scope.label, + "sha": scope.sha, + "status": scope.status, + "checks": scope.checks, + } + for scope in results + ], + } + with open(output_path, "a", encoding="utf-8") as f: + _write_output(f, "result", json.dumps(payload, indent=2)) + + +def _write_output(f: Any, name: str, value: str) -> None: + """Append one multi-line output in the heredoc form ``GITHUB_OUTPUT`` takes. + + The runner reads lines up to the first one equal to the delimiter and + rejects the whole file if it never finds one, which fails the step and + drops every output written after the bad one. A fixed ``EOF`` delimiter + is therefore unsafe: the JSON quotes commit subjects and error text as + they are, and a subject reading ``EOF`` is legal. So the delimiter is + random per write, the shape actions/github-script uses. + """ + delimiter = f"ghadelimiter_{uuid.uuid4()}" + while delimiter in value: # pragma: no cover - 122 random bits + delimiter = f"ghadelimiter_{uuid.uuid4()}" + f.write(f"{name}<<{delimiter}\n{value}\n{delimiter}\n") + + +def is_fork_pr() -> bool: + """Returns True when the triggering PR originates from a forked repository.""" + event_path = os.getenv("GITHUB_EVENT_PATH") + if not event_path: + return False + try: + with open(event_path, "r", encoding="utf-8") as f: + event = json.load(f) + pr = event.get("pull_request", {}) + head_full_name = pr.get("head", {}).get("repo", {}).get("full_name", "") + base_full_name = pr.get("base", {}).get("repo", {}).get("full_name", "") + return bool( + head_full_name and base_full_name and head_full_name != base_full_name + ) + except Exception: # noqa: BLE001 - an unreadable payload is not a fork PR + return False + + +def is_fork_pr_with_readonly_token() -> bool: + """Returns True when the PR is from a fork AND the event has a read-only token. + + Under the pull_request event, GITHUB_TOKEN is read-only for fork PRs. + Under pull_request_target, GITHUB_TOKEN has the workflow's configured + permissions regardless of whether the PR is from a fork. + """ + return is_fork_pr() and os.getenv("GITHUB_EVENT_NAME", "") != "pull_request_target" + + +def get_pr_number() -> int: + """Extract the pull request number from event payload or GITHUB_REF. + + For pull_request: GITHUB_REF is refs/pull//merge + For pull_request_target: GITHUB_REF is refs/heads/ (not useful), + so we fall back to the event payload. + """ + ref = os.getenv("GITHUB_REF", "") + parts = ref.split("/") + if len(parts) >= 4 and parts[1] == "pull": + return int(parts[2]) + # Fallback: read PR number from event payload + event_path = os.getenv("GITHUB_EVENT_PATH") + if event_path: + try: + with open(event_path, "r", encoding="utf-8") as f: + event = json.load(f) + number = event.get("number") or (event.get("pull_request", {}) or {}).get( + "number" + ) + if number: + return int(number) + except Exception: # noqa: BLE001, S110 - fall through to the error below + pass + raise ValueError( + "Unable to determine PR number from GITHUB_REF or GITHUB_EVENT_PATH" + ) + + +def _is_bot(comment: Any) -> bool: + """Whether a comment was posted by a bot account rather than a person.""" + try: + return comment.user.type == "Bot" + except Exception: # noqa: BLE001 - an unknown author is not a bot + return False + + +def _find_own_comments(comments: list[Any]) -> tuple[Any | None, list[Any]]: + """Pick the comment to update and the ones to delete. + + Returns ``(target, stale)``. Only comments a bot posted with + ``COMMENT_MARKER`` in them are ever edited or deleted: a person can paste + the marker too (quoting a report, say), and their comment is theirs. A comment from an earlier + version has no marker, so it is adopted (edited, which adds the marker) + when there is no marked comment yet, and only if a bot posted it: the + legacy signal is a title prefix, which a person can type by accident, and + editing someone's comment out from under them is not recoverable. + """ + marked = [c for c in comments if render.COMMENT_MARKER in c.body and _is_bot(c)] + if marked: + return marked[-1], marked[:-1] + + legacy = [c for c in comments if c.body.startswith(LEGACY_TITLES) and _is_bot(c)] + return (legacy[-1], []) if legacy else (None, []) + + +def add_pr_comments(results: list[model.ScopeResult]) -> int: + """Posts the commit check result as a comment on the pull request.""" + if not inputs.PR_COMMENTS_ENABLED: + return 0 + + # A push has no pull request to comment on. This used to fall through to + # get_pr_number(), which raised, and every push run carried a warning. + if not context.is_pr_event(): + print("Skipping PR comment: not a pull request event.") + return 0 + + # Fork PRs triggered by the pull_request event receive a read-only token; + # the GitHub API will always reject comment writes with 403. + # pull_request_target events always have the configured token permissions. + if is_fork_pr_with_readonly_token(): + # Name only the surfaces this run actually produced: with + # job-summary: false there is no summary to send the reader to. + where = "in the annotations on the run page" + if render._summary_written(): + where = f"in this job's summary and {where}" + msg = ( + "Skipping PR comment: pull requests from forked repositories " + "cannot write comments via the pull_request event (GITHUB_TOKEN is " + f"read-only for forks). The findings are {where}. " + "See https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md" + ) + print(f"::warning::{msg}") + if inputs.JOB_SUMMARY_ENABLED and inputs.GITHUB_STEP_SUMMARY: + with open(inputs.GITHUB_STEP_SUMMARY, "a", encoding="utf-8") as f: + f.write( + "\n---\n" + "### \u2139\ufe0f PR Comment Skipped\n\n" + "Pull requests from forked repositories cannot write comments " + "using the `pull_request` event because `GITHUB_TOKEN` has " + "read-only permissions. The report above and the annotations " + "on the run page are unaffected.\n\n" + "> **\U0001f4a1 Tip:** see " + "[Fork pull requests]" + "(https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md).\n" + ) + return 0 + + try: + from github import Auth, Github, GithubException # type: ignore + except ImportError as e: + # Imported here, so it has to be caught here. Leaving it inside the + # try below would bind GithubException only on success — and an + # ImportError would then make the `except GithubException` clause + # itself raise NameError, which propagates past the `except Exception` + # underneath it and kills a step that is meant to be non-fatal. + print(f"::warning::Unable to post PR comment: {e}", file=sys.stderr) + return 0 + + try: + token = os.getenv("GITHUB_TOKEN") + repo_name = os.getenv("GITHUB_REPOSITORY") + pr_number = get_pr_number() + + if not token: + raise ValueError("GITHUB_TOKEN is not set") + if not repo_name: + raise ValueError("GITHUB_REPOSITORY is not set") + + api_url = os.getenv("GITHUB_API_URL", "https://api.github.com") + g = Github(auth=Auth.Token(token), base_url=api_url) + repo = g.get_repo(repo_name) + pull_request = repo.get_issue(pr_number) + + pr_comment_body = render.render_pr_comment(results) + + target, stale = _find_own_comments(list(pull_request.get_comments())) + + if target is not None: + if target.body == pr_comment_body: + print(f"PR comment already up-to-date for PR #{pr_number}.") + return model.exit_code_for(results) + print(f"Updating the last comment on PR #{pr_number}.") + target.edit(pr_comment_body) + for comment in stale: + print(f"Deleting an old comment on PR #{pr_number}.") + comment.delete() + else: + print(f"Creating a new comment on PR #{pr_number}.") + pull_request.create_comment(body=pr_comment_body) + + return model.exit_code_for(results) + except GithubException as e: + if e.status == 403: + # GithubException.data is whatever the response decoded to, which + # is None for an empty body and a str for a non-JSON one. Reaching + # for .get unguarded would raise inside this handler and escape the + # function, turning the best-effort path into a step failure. + detail = e.data.get("message") if isinstance(e.data, dict) else None + print( + "::warning::Unable to post PR comment (403 Forbidden). " + "Ensure your workflow grants 'pull-requests: write' permission. " + f"Error: {detail or e}", + file=sys.stderr, + ) + return 0 + # Annotated, not just printed: posting the comment is best-effort and + # never fails the step, so without an annotation the run is green, the + # comment is absent, and nothing says why. + print(f"::warning::Unable to post PR comment: {e}", file=sys.stderr) + return 0 + except Exception as e: # noqa: BLE001 - the comment is best-effort + print(f"::warning::Unable to post PR comment: {e}", file=sys.stderr) + return 0 + + +def ai_tools_found(results: list[model.ScopeResult]) -> list[str]: + """Every AI tool found in the pull request, sorted. + + In the checked commits (messages and authors), the title, the + description, and the app that opened the pull request. + """ + tools = {tool for scope in results for tool in scope.ai_tools} + tools.update(cli.PR_BODY_AI_TOOLS) + if context.is_pr_event(): + opener = context.get_pr_opener_tool() + if opener: + tools.add(opener) + return sorted(tools) + + +def add_ai_label(results: list[model.ScopeResult]) -> None: + """Label the pull request when an AI tool wrote any of it (``ai-label``). + + The label is only ever added, never removed: a maintainer may have put + it there by hand. Best-effort, like the comment: a failure warns and + never fails the step. + """ + name = inputs.ai_label_name() + if not name or not context.is_pr_event(): + return + tools = ai_tools_found(results) + if not tools: + print("No AI tool found in the pull request; no label added.") + return + found = ", ".join(tools) + if is_fork_pr_with_readonly_token(): + print( + f"::warning::AI tools found ({found}), but the label '{name}' was " + "not added: pull requests from forked repositories get a read-only " + "GITHUB_TOKEN under the pull_request event. " + "See https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md" + ) + return + + try: + from github import Auth, Github, GithubException # type: ignore + except ImportError as e: + print(f"::warning::Unable to add the AI label: {e}", file=sys.stderr) + return + + try: + token = os.getenv("GITHUB_TOKEN") + repo_name = os.getenv("GITHUB_REPOSITORY") + if not token: + raise ValueError("GITHUB_TOKEN is not set") + if not repo_name: + raise ValueError("GITHUB_REPOSITORY is not set") + pr_number = get_pr_number() + api_url = os.getenv("GITHUB_API_URL", "https://api.github.com") + repo = Github(auth=Auth.Token(token), base_url=api_url).get_repo(repo_name) + issue = repo.get_issue(pr_number) + if any(label.name == name for label in issue.labels): + print(f"PR #{pr_number} already has the label '{name}' ({found}).") + return + try: + repo.get_label(name) + except GithubException as e: + if e.status != 404: + raise + try: + repo.create_label( + name, AI_LABEL_COLOR, "Written with the help of an AI tool" + ) + except GithubException as created: + # 422: another run created it in the meantime; use that one. + if created.status != 422: + raise + issue.add_to_labels(name) + print(f"Added the label '{name}' to PR #{pr_number}: {found}.") + except GithubException as e: + hint = ( + " Ensure your workflow grants 'pull-requests: write' permission." + if e.status == 403 + else "" + ) + print( + f"::warning::Unable to add the AI label.{hint} Error: {e}", file=sys.stderr + ) + except Exception as e: # noqa: BLE001 - the label is best-effort + print(f"::warning::Unable to add the AI label: {e}", file=sys.stderr) diff --git a/action/render.py b/action/render.py new file mode 100644 index 0000000..eca1d9c --- /dev/null +++ b/action/render.py @@ -0,0 +1,1212 @@ +"""Rendering results: the step log, and the Markdown report the job summary +and the PR comment share.""" + +import os +import re + +from action import cli, escape, inputs, model + +# --------------------------------------------------------------------------- +# Output specification +# +# The Markdown report shared by the job summary and the PR comment renders +# as follows (values are filled from ScopeResult data; stands for an +# of that status mark, see _status_mark). +# +# Every body opens with COMMENT_MARKER, which is invisible when rendered and is +# how the action recognises its own PR comment on the next run. +# +# Failure: +# +# +# ## Commit Check failed +# +# Pull request: passed
Commits: 2 of 3 failed
Branch: failed +# (one source line: see _group_lines) +# +# ```diff +# @@ 5584f46 @@ +# - bad msg +# + fix: bad msg +# @@ 37d6def @@ +# feat: add OAuth providers +# - Co-authored-by: Claude +# @@ Branch @@ +# - login-page +# # Use / with an allowed type +# ``` +# +# Commits: [`5584f46`](…) [`37d6def`](…)  |  Rules: [CC001](…) · [CC013](…) · [CC201](…) +# +#
+# How to fix +# +# **With an AI coding agent.** Paste this prompt: +# +# ```text +# Fix these Commit Check findings without changing any code: +# - Commit 5584f46: change "bad msg" to "fix: bad msg" +# - Commit 37d6def "feat: add OAuth providers": remove "Co-authored-by: Claude " +# - Branch "login-page": Use / with an allowed type +# ``` +# +# **Commit messages.** Reword them, then force-push: +# +# ```bash +# git rebase -i 5584f46~1 # change "pick" to "reword" on the commits above +# git push --force-with-lease +# ``` +# +# **Branch name.** Rename the branch and push it. … +# +# **Next time.** The [pre-commit hook](…) runs the same rules before you push. +# +#
+# +#
+# All 5 checks +# +# ```text +# Pull request +# ✔ title feat: add login page +# Commits +# ✔ d87faca feat: add login page +# ✖ 5584f46 bad msg +# CC001 message +# value: bad msg +# The commit message should follow Conventional Commits. +# Fix: fix: bad msg +# ✖ 37d6def feat: add OAuth providers +# CC013 ai-attribution +# value: Claude Code +# AI attribution is forbidden in this project — detected: Claude Code +# Suggest: … +# Fix: feat: add OAuth providers +# Branch +# ✖ branch login-page +# CC201 branch +# value: login-page +# The branch should follow Conventional Branch. +# Suggest: Use / with an allowed type, or … +# ``` +# +#
+# +# Checked by [Commit Check](https://commit-check.com) 2.22.0 · [Rules](…) · [Check before you push](…) +# +# Success: the heading reads " Commit Check passed", then the +# group lines, the folded listing and the footer. No diff, no "How to fix". +# +# Warning (the repository's config lists a rule under the top-level `warn`): +# " Commit Check passed with warnings", the group lines (a warned +# group reads " Branch: 1 warning"), then **Warnings** and +# the same diff block built from the warnings. A warned scope is reported +# exactly like a failing one except the mark is ⚠ rather than ✖, it counts +# toward "passed" rather than "failed", and it never turns the workflow red. +# A real failure elsewhere still fails the run; both diff blocks then appear. +# +# Skipped (every rule declined to run — e.g. the author is in ignore_authors): +# " Commit Check skipped", then "Nothing was validated." and the +# reason ("Skipped because author dependabot[bot] is in ignore_authors."). The +# reason comes from commit-check; an older CLI sends none. A skipped scope +# deliberately carries no ✔ and no checked value: nothing was examined, so +# there is no value to report and no pass to claim. When only some scopes +# skip, their group line says so ("Author: 1 passed, 1 skipped"). +# +# The step log prints the same listing, each group folded under a title that +# carries its result, plus a `Docs:` line per finding; then one annotation per +# finding, and the verdict: +# +# ::group::✖ Commits: 2 of 3 failed +# ✔ d87faca feat: add login page +# ✖ 5584f46 bad msg +# CC001 message +# … +# ::endgroup:: +# ::error title=CC001 message::Commit 2/3 (5584f46): change "bad msg" to "fix: bad msg"%0AThe commit message should follow Conventional Commits. +# ✖ Commit Check: 2 of 5 checks failed +# How to fix: see the job summary. Check before you push: https://commit-check.com/… +# +# The verdict is a plain line, not an `::error`, so the run's error count is +# the number of findings. +# +# Notes: +# - The status marks are the Commit Check mark in a status colour, so the mark +# itself is the status signal: there is never a tick next to a failure. +# Their alt text is the glyph the step log uses, so the report still reads +# where the images cannot load. +# - A red line is text that was found and has to change, a green line is text +# to write, taken from the CLI's `fix` (see _line_edits). A rule with no +# mechanical fix gets a `#` line with the CLI's suggestion instead. +# - The diff lists only what failed, capped at MAX_HUNKS items with the rest +# folded; passing scopes live in the listing. +# - A commit is named by its short hash on every surface; the label +# ("Commit 1/11") stays bare in the `result` output. +# - With `files: true` each commit also gets a row in a "Files" group, for the +# files it changes. Its hunk reads `@@ 5584f46 files @@`, with a red line per +# path a rule found and the rule's advice under it. The agent prompt then +# opens with "changing only the files they name" in place of "without +# changing any code". +# - One check is one thing that was checked — a commit message, the branch, the +# author — not one rule evaluation. The totals therefore match the number of +# ✔/✖ rows the reader can count in the listing, and do not grow with the +# number of rules in the config. +# - Passing values are capped at 60 characters with a literal "..." suffix; a +# failing scope prints its value in full — it is the one value the reader +# has to act on and the cap can hide the reason. +# - Every fenced block grows its fence past any backtick run inside it, so a +# subject that quotes code cannot close the block. +# --------------------------------------------------------------------------- + + +RULES_URL = "https://commit-check.com/rules/" + +#: Hidden marker identifying comments this action owns. +# +# Comment identity has to be something a human cannot type by accident. The +# previous title-prefix match meant any comment opening with "# Commit Check" +# was treated as ours — and old ones are deleted, not just skipped. An HTML +# comment is invisible in the rendered body and is what Codecov, SonarQube and +# CodSpeed all use for the same purpose. +COMMENT_MARKER = "" + +#: Home of the status marks the report shows: static PNGs in the organization's +#: ``.github`` repository, so nothing has to be running for them to load. +STATUS_MARK_URL = ( + "https://raw.githubusercontent.com/commit-check/.github/main/branding/status" +) + +SITE_URL = "https://commit-check.com" + +#: Where a reader sets the same rules up locally, so the next push passes. +LOCAL_HOOK_URL = "https://commit-check.com/guides/integrations/#as-a-pre-commit-hook" + +#: One glyph per status. The step log prints it, and the report's images carry +#: it as their alt text, so a report whose images cannot load still reads. +STATUS_GLYPHS = {"pass": "✔", "fail": "✖", "warn": "⚠", "skip": "⊘"} + +#: File name of each status mark, and the word the heading uses for it. +STATUS_WORDS = { + "pass": "passed", + "fail": "failed", + "warn": "warned", + "skip": "skipped", +} + +#: Step log colours. GitHub renders these; bright black is its grey. +ANSI = {"pass": "\033[32m", "fail": "\033[31m", "warn": "\033[33m", "skip": "\033[90m"} + +ANSI_BOLD, ANSI_GREY, ANSI_RESET = "\033[1m", "\033[90m", "\033[0m" + +#: Failing items the report shows before folding the rest away. A hunk is two +#: or three lines, and folding one or two leftovers would cost a click and +#: save nothing, so up to ``MAX_HUNKS + HUNK_SLACK`` are shown unfolded. +MAX_HUNKS = 5 + +HUNK_SLACK = 2 + + +def _rule_label(check: dict[str, str]) -> str: + """Human-readable label for a check: ``CC001 message`` (kebab-case).""" + rule_id = check.get("rule_id", "") + name = check.get("check", "").replace("_", "-") + return f"{rule_id} {name}" if rule_id else name + + +def _rule_ref(check: dict[str, str]) -> str: + """Short Markdown link for a rule: ``[CC001](docs_url)``.""" + label = check.get("rule_id") or check.get("check", "").replace("_", "-") + docs_url = check.get("docs_url", "") + return f"[{label}]({docs_url})" if docs_url else label + + +def _names_a_commit(scope: model.ScopeResult) -> bool: + """Whether the scope is one commit's: its message, or the files it changes.""" + return bool(scope.sha) and ( + scope.label.startswith("Commit") or scope.label == cli.FILES_LABEL + ) + + +def _found(check: dict[str, str]) -> str: + """First line of what a rule reports it found.""" + value = str(check.get("value") or "").strip() + return value.splitlines()[0].strip() if value else "" + + +def _scope_group(label: str) -> str: + """Group name for a scope label, used to fold the step log output.""" + if label in ("PR title", "PR description"): + return "Pull request" + if label.startswith("Commit"): + return "Commits" + if label.startswith("Author"): + return "Author" + return label + + +def _grouped( + results: list[model.ScopeResult], +) -> list[tuple[str, list[model.ScopeResult]]]: + """Split results into ordered groups for step log folding.""" + groups: list[tuple[str, list[model.ScopeResult]]] = [] + for scope in results: + group_name = _scope_group(scope.label) + if groups and groups[-1][0] == group_name: + groups[-1][1].append(scope) + else: + groups.append((group_name, [scope])) + return groups + + +def _plural(count: int, word: str) -> str: + """``1 warning``, ``2 warnings``.""" + return f"{count} {word}{'' if count == 1 else 's'}" + + +def _group_status(scopes: list[model.ScopeResult]) -> tuple[str, str]: + """A group's worst outcome and the few words that say it: ``3 of 4 failed``. + + The same words head the group in the step log and its line in the + report, so a folded log and a skimmed comment both say where it went + wrong. A skipped scope never counts as passed, and a group is ``skip`` + only when nothing in it ran. + """ + total = len(scopes) + failed = sum(1 for scope in scopes if scope.status == "fail") + skipped = sum(1 for scope in scopes if scope.status == "skip") + warned = sum(1 for scope in scopes if scope.warnings) + if failed: + return "fail", f"{failed} of {total} failed" if total > 1 else "failed" + if skipped == total: + return "skip", "skipped" + if warned: + return "warn", _plural(warned, "warning") + text = f"{total - skipped} passed" if total > 1 else "passed" + return "pass", f"{text}, {skipped} skipped" if skipped else text + + +def _first_value(scope: model.ScopeResult) -> str: + """First line of what the scope checked: a subject, a title, a branch. + + The text the action piped in when it has it, then the whole message the + ``message`` rule reports, then whichever rule names a value first. A PR + description has no such line: its first line does not identify it. An + AI rule's value is the tool or the author it found, never the text, so + it never stands in for a commit's subject. + """ + if scope.label == "PR description": + return "" + if scope.label == cli.FILES_LABEL: + # Each file rule names its own finding, a path and what is wrong + # with it. The first finding stands for the scope; with none, the + # count of files a passing rule reports. + checks = [*scope.failures, *scope.warnings] or scope.checks + return next((_found(check) for check in checks if _found(check)), "") + values = [scope.text, cli._message_value(scope)] + values.extend( + str(check.get("value") or "") + for check in scope.checks + if check.get("rule_id") not in cli.AI_RULE_IDS + ) + values.append(scope.subject) + for value in values: + if value.strip(): + return value.strip().splitlines()[0].strip() + return "" + + +def _scope_value(scope: model.ScopeResult, max_len: int = 80) -> str: + """``_first_value`` capped for a row of the listing. + + The value reads naturally next to the scope's label, and the cap keeps a + passing row on one line of the fenced block. 80 holds a subject written + to the usual 72-column limit; a longer one is cut at a word, with an + ellipsis, rather than mid-word. + """ + if scope.label == "PR description" and scope.status == "pass": + # Its first line does not identify it; what was found does. + if scope.ai_tools: + return f"AI attribution: {', '.join(scope.ai_tools)}" + return "no AI attribution" + value = _first_value(scope) + if len(value) <= max_len: + return value + cut = value[: max_len - 1] + space = cut.rfind(" ") + if space > max_len // 2: + cut = cut[:space] + return cut.rstrip() + "…" + + +def _line_edits( + scope: model.ScopeResult, check: dict[str, str] +) -> tuple[list[str], list[str]]: + """The lines a rule's fix removes and adds, as ``(removed, added)``. + + The CLI's ``fix`` is corrected text, but of what differs by rule: the + whole message for most, the subject alone for the subject rules. So the + fix is compared with the rule's value when that is one line of the text + and the fix is one line too, and with the whole text otherwise. An AI + rule's value is the tool or the line it found, never the text it fixes. + + Both lists are empty when the rule offers no fix, or nothing is known to + compare it with; the caller then falls back to the rule's advice. + """ + recorded = scope.edits.get(cli._rule_key(check)) + if recorded: + return recorded + fix = (check.get("fix") or "").strip() + if not fix: + return [], [] + value = str(check.get("value") or "").strip() + text = (scope.text or cli._message_value(scope)).strip() + one_line = "\n" not in value and "\n" not in fix + if check.get("rule_id") in cli.AI_RULE_IDS: + original = text + elif one_line and value in text.splitlines(): + original = value + else: + original = text or value + if not original: + return [], [] + return cli.lines_removed(original, fix), cli.lines_removed(fix, original) + + +def _plain_error(check: dict[str, str]) -> str: + """First line of the rule's error, without a trailing ``See ``.""" + error = (check.get("error") or "").splitlines() + fallback = "check warning" if check.get("status") == "warn" else "check failed" + first = error[0] if error else fallback + return re.sub(r"\s*See https?://\S+\s*$", "", first) + + +def _advice(check: dict[str, str]) -> str: + """What to do about a finding that has no ready-made fix, in one line. + + The CLI's suggestion, without the tails that only matter once the reader + opens the rule (the list of allowed types, the config key that would + exempt the branch): those are in the listing and behind the rule link. + """ + suggest = (check.get("suggest") or "").splitlines() + if not suggest: + return _plain_error(check) + advice = re.sub(r"^In the description, ", "", suggest[0]) + return re.sub( + r"(, where is one of: .*|, or add the branch to .*)$", "", advice + ) + + +def _quoted(lines: list[str]) -> str: + """``"first"; "second"``.""" + return "; ".join(f'"{line}"' for line in lines) + + +def _instruction(scope: model.ScopeResult, check: dict[str, str]) -> str: + """One finding as an instruction: ``change "a" to "b"``, ``remove "x"``.""" + removed, added = _line_edits(scope, check) + if len(removed) == 1 and len(added) == 1: + return f'change "{removed[0]}" to "{added[0]}"' + parts = [] + if removed: + parts.append(f"remove {_quoted(removed)}") + if added: + parts.append(f"add {_quoted(added)}") + return ", and ".join(parts) or _advice(check) + + +def _target( + scope: model.ScopeResult, + instructions: list[str], + label: str, + value: str | None = None, +) -> str: + """Name what an instruction is about: ``Commit 2/3 (5584f46) "bad msg"``. + + The quoted value is left out when an instruction already quotes it. It + is the scope's own unless ``value`` names another: a files scope holds + one finding per rule, each about a path of its own. + """ + if value is None: + value = _first_value(scope) + if value and not any(f'"{value}"' in text for text in instructions): + return f'{label} "{value}"' + return label + + +def _findings(scope: model.ScopeResult, status: str) -> list[dict[str, str]]: + """A scope's failures or warnings.""" + return scope.failures if status == "fail" else scope.warnings + + +def _finding_lines(check: dict[str, str]) -> list[str]: + """The detail a reader needs to act on one finding, one item per line. + + ``value:`` (what was checked), the error, ``Suggest:`` and ``Fix:`` — + each only when the CLI filled it in. + + ``Fix:`` is the corrected text itself, ready to paste. When a rule has a + fix but no bespoke advice the CLI sets ``suggest`` to ``Use ""``, + so printing both would say the same thing twice in a row; in exactly + that case only ``Fix:`` is shown. A multi-line fix (a signed-off body) + takes one row per line so the trailer lands where it would in the + message; a multi-line value (a whole commit message on a failing rule) + or suggestion is split the same way, so every line of user text sits + inside the tree rather than at column 0. + """ + lines: list[str] = [] + if check.get("value"): + first, *rest = str(check["value"]).splitlines() + lines.append(f"value: {first}") + lines.extend(rest) + lines.extend(check.get("error", "").splitlines()) + fix = check.get("fix", "") + suggest = check.get("suggest", "") + if suggest and suggest != f'Use "{fix}"': + first, *rest = suggest.splitlines() + lines.append(f"Suggest: {first}") + lines.extend(rest) + if fix: + first, *rest = fix.splitlines() + lines.append(f"Fix: {first}") + lines.extend(rest) + return lines + + +def _render_findings(checks: list[dict[str, str]], include_docs: bool) -> list[str]: + """Render the indented detail lines for a list of check entries. + + Shared by the failure and warning branches of ``_render_scopes`` — the + same rule label / value / error / suggestion / fix / docs layout, + whichever list it is called with. + """ + lines: list[str] = [] + for check in checks: + # A scope can hold a failure and a warning at once (see below), so a + # warning says so on its own line rather than borrow the row's mark. + kind = " (warning)" if check.get("status") == "warn" else "" + lines.append(f" {_rule_label(check)}{kind}") + lines.extend(f" {line}" for line in _finding_lines(check)) + if include_docs and check.get("docs_url"): + lines.append(f" Docs: {check['docs_url']}") + return lines + + +def _row_label(scope: model.ScopeResult) -> str: + """A scope's name within its group: the short hash, ``title``, ``email``. + + The group header already says "Commits" or "Author", so the row only + needs what tells it apart from its neighbours. + """ + if _names_a_commit(scope): + return scope.sha[:7] + _group, _, name = scope.label.partition(" ") + return name or scope.label.lower() + + +def _row(mark: str, scope: model.ScopeResult, value: str) -> str: + """One aligned row of the listing: mark, label, value.""" + return f" {mark} {_row_label(scope):<12} {value}".rstrip() + + +def _one_skip_reason(results: list[model.ScopeResult]) -> bool: + """Whether every skipped scope was skipped for the same, named reason. + + Then the one sentence under the verdict (``_skip_reasons``) explains + them all, and each skipped row can show what it skipped instead of + repeating why. + """ + reasons = {s.skip_reason for s in results if s.status == "skip"} + return len(reasons) == 1 and "" not in reasons + + +def _render_scopes( + scopes: list[model.ScopeResult], include_docs: bool, reason_said: bool = False +) -> list[str]: + """Render the indented listing for one group of scopes, without its header. + + Shared by both output surfaces so they cannot drift: the step log and the + Markdown listing are the same rows, and the only difference is the docs + link, which the Markdown report already carries under the diff. + + A failing or warned scope shows its value in full rather than capped. It + is the one value the reader has to act on, and the cap can cut off the + part that explains it. + + ``reason_said`` is for a report whose skipped scopes share one reason, + stated once under the verdict: a skipped row then shows what it skipped + (a commit's subject, an author) rather than that reason again. + """ + lines: list[str] = [] + for scope in scopes: + if scope.status == "skip": + # Deliberately not a ✔. Nothing was validated here, and a tick + # claiming otherwise is what made a bypassed policy look enforced. + value = _scope_value(scope) if reason_said else "" + if value: + lines.append(_row("⊘", scope, value)) + continue + reason = scope.skip_reason + lines.append(_row("⊘", scope, f"skipped{f': {reason}' if reason else ''}")) + continue + if scope.status == "pass": + lines.append(_row("✔", scope, _scope_value(scope))) + continue + if scope.raw_text and not scope.checks: + # Defensive fallback: commit-check produced unexpected output. + lines.append(_row("✖", scope, "")) + lines.extend(f" {ln}" for ln in scope.raw_text.strip().splitlines()) + continue + # A scope's status names its worst outcome (fail beats warn), but the + # two are not exclusive: CC2xx covers both branch and merge_base, so + # one can fail while the other only warns. The row carries the worst + # mark, and both lists are rendered under it — a warning on an + # otherwise-failing scope is still a finding to fix. + lines.append(_row(STATUS_GLYPHS[scope.status], scope, _first_value(scope))) + lines.extend(_render_findings(scope.failures, include_docs)) + lines.extend(_render_findings(scope.warnings, include_docs)) + return lines + + +def _render_tree(results: list[model.ScopeResult], include_docs: bool) -> list[str]: + """Render the full grouped listing: a header line per group, then its scopes.""" + lines: list[str] = [] + reason_said = _one_skip_reason(results) + for group_name, scopes in _grouped(results): + lines.append(group_name) + lines.extend(_render_scopes(scopes, include_docs, reason_said)) + return lines + + +#: A row of the listing: two spaces, the status glyph, a space. +_ROW_MARK = re.compile(r"^ ([✔✖⚠⊘]) ") + +_GLYPH_STATUS = {glyph: status for status, glyph in STATUS_GLYPHS.items()} + + +def _coloured(line: str) -> str: + """Colour a row's status glyph for the step log. + + Only rows start with a glyph at column two; the detail under a finding + sits deeper, so user text can never be taken for a row. + """ + match = _ROW_MARK.match(line) + if not match: + return line + glyph = match.group(1) + return f" {ANSI[_GLYPH_STATUS[glyph]]}{glyph}{ANSI_RESET} {line[4:]}" + + +def _annotation_body(scope: model.ScopeResult, check: dict[str, str]) -> str: + """The message of one finding's annotation, before escaping. + + The run page shows only the first line of an annotation, so that line + says where and what to change: ``Commit 2/3 (5584f46): change "bad msg" + to "fix: bad msg"``. The rule's own sentence follows on the second line + for whoever expands it. + """ + instruction = _instruction(scope, check) + found = _found(check) if scope.label == cli.FILES_LABEL else None + target = _target(scope, [instruction], scope.display_label, found) + headline = f"{target}: {instruction}" + error = _plain_error(check) + return headline if error == instruction else f"{headline}\n{error}" + + +def render_step_log(results: list[model.ScopeResult]) -> None: + """Print results to the step log, then emit one annotation per finding. + + Each group is folded under a title that carries its own result + (``✖ Commits: 3 of 4 failed``): GitHub shows a group collapsed, and a + bare "Commits" said nothing about where to look. + + The tree and the annotations are separated deliberately. An ``::error`` or + ``::warning`` command renders as a line of its own wherever it is printed, + so emitting one inside the indented listing broke the tree apart, and its + ``title=`` — which is what carries the rule ID — is only shown in the + annotations UI, never inline. Printing the listing first and the + annotations after all the groups keeps the log readable and still + surfaces findings on the run page, where the annotation's first line is + all a reader sees (``_annotation_body``). + + A failure becomes an ``::error``, a warning a ``::warning`` — GitHub + renders the two differently, and only the errors count toward the + friendly one-line verdict claiming nothing failed. + + Under ``dry-run`` a failure is still reported, but as a ``::warning``: + an ``::error`` annotation on a step that then exits 0 reads as a + contradiction, and the run's error count would claim a failure the job + did not have. The verdict line says the same thing in words. + """ + # The tree is grouped, so it is printed group by group rather than in one + # block: ::group:: and ::endgroup:: have to bracket each section's lines. + reason_said = _one_skip_reason(results) + for group_name, scopes in _grouped(results): + status, text = _group_status(scopes) + print(f"::group::{STATUS_GLYPHS[status]} {group_name}: {text}") + for line in _render_scopes(scopes, include_docs=True, reason_said=reason_said): + print(_coloured(escape._log_safe(line))) + print("::endgroup::") + + errors: list[tuple[str, str]] = [] + warnings: list[tuple[str, str]] = [] + for scope in results: + if scope.status in ("pass", "skip"): + continue + if scope.raw_text and not scope.checks: + errors.append( + (f"Commit Check: {scope.display_label}", "output could not be parsed") + ) + continue + for check in scope.failures: + errors.append((_rule_label(check), _annotation_body(scope, check))) + for check in scope.warnings: + warnings.append((_rule_label(check), _annotation_body(scope, check))) + + level = "warning" if inputs.DRY_RUN_ENABLED else "error" + for title, message in errors: + print( + f"::{level} title={escape._annotation_escape(title)}" + f"::{escape._annotation_escape(message)}" + ) + for title, message in warnings: + print( + f"::warning title={escape._annotation_escape(title)}" + f"::{escape._annotation_escape(message)}" + ) + + # The verdict is a plain line, never an ::error: the findings above are + # already one annotation each, and a second, untitled ::error for the + # total inflated the run's error count and told the reader nothing new. + if errors: + failed, total = _check_counts(results) + if inputs.DRY_RUN_ENABLED: + print( + f"Commit Check (dry-run): {failed} of {total} checks failed; " + "not failing the job" + ) + else: + verdict = f"✖ Commit Check: {failed} of {total} checks failed" + warned = _warn_count(results) + if warned: + verdict += f", {_plural(warned, 'warning')}" + print(f"{ANSI['fail']}{ANSI_BOLD}{verdict}{ANSI_RESET}") + where = "the job summary" if _summary_written() else "the findings above" + print( + f"{ANSI_GREY}How to fix: see {where}. " + f"Check before you push: {LOCAL_HOOK_URL}{ANSI_RESET}" + ) + if not errors: + skipped, warned, total = ( + _skip_count(results), + _warn_count(results), + len(results), + ) + if total and skipped == total: + print("⊘ Commit Check: all checks skipped, nothing was validated") + if _skip_reasons(results): + print(escape._log_safe(_skip_reasons(results))) + elif warned or skipped: + passed = total - skipped - warned + tail = [] + if warned: + tail.append(_plural(warned, "warning")) + if skipped: + tail.append(f"{skipped} skipped") + print( + f"{ANSI['pass']}✔ Commit Check: {passed} of {total} checks " + f"passed, {', '.join(tail)}{ANSI_RESET}" + ) + if _skip_reasons(results): + print(escape._log_safe(_skip_reasons(results))) + else: + print(f"{ANSI['pass']}✔ Commit Check: all checks passed{ANSI_RESET}") + + +def _summary_written() -> bool: + """Whether this run writes a job summary a log line can point to.""" + return bool(inputs.JOB_SUMMARY_ENABLED and inputs.GITHUB_STEP_SUMMARY) + + +def _check_counts(results: list[model.ScopeResult]) -> tuple[int, int]: + """Return ``(failed, total)`` where one check is one thing that was checked. + + A "check" here is a scope — one commit message, the branch, the author name + — not one rule evaluation. Counting rule evaluations produced a number that + grew with the size of the pull request rather than with the strictness of + the policy: sixteen commit messages against six enabled rules reported + "1 of 100 checks failed", where 96 of the 100 were the same six rules run + again per commit. The large denominator also made a real failure look + negligible — one bad commit out of fifteen reads very differently from + 1 of 100. + + This number matches what the reader can count: the ✔/✖ rows of the + listing. Which rules failed is not lost, it is just reported where it + belongs — under the diff and in the listing. + """ + failed = sum(1 for scope in results if scope.status == "fail") + return failed, len(results) + + +def _skip_count(results: list[model.ScopeResult]) -> int: + """Number of scopes that never ran. + + Reported separately from the pass count so the headline cannot claim + that checks passed when they were skipped. + """ + return sum(1 for scope in results if scope.status == "skip") + + +def _skip_reasons(results: list[model.ScopeResult]) -> str: + """One sentence naming why checks were skipped, or ``""`` if unknown. + + The verdict is all most readers see, so it stays short: the config + section is dropped ("[commit].ignore_authors" and "[branch].ignore_authors" + both read "ignore_authors"), which folds the usual bot case into one + reason. The per-scope lines in the collapsed block keep the section. + """ + reasons = list( + dict.fromkeys( + re.sub(r"\[\w+\]\.", "", s.skip_reason) for s in results if s.skip_reason + ) + ) + return f"Skipped because {'; '.join(reasons)}." if reasons else "" + + +def _warn_count(results: list[model.ScopeResult]) -> int: + """Number of scopes that carry at least one warning. + + Counts by ``scope.warnings``, not ``scope.status == "warn"``: a scope + whose overall status is "fail" (CC2xx covers both ``branch`` and + ``merge_base``, so one can fail while the other only warns) still has + warnings to report, and this is the count the verdict uses to decide + whether to show them. + """ + return sum(1 for scope in results if scope.warnings) + + +def _commit_url(sha: str) -> str: + """Link to a commit on the GitHub instance the workflow runs against. + + ``GITHUB_SERVER_URL`` is what makes this right on GitHub Enterprise + Server; without ``GITHUB_REPOSITORY`` there is nothing to link into, so + the caller falls back to plain text rather than guess. + """ + repository = os.getenv("GITHUB_REPOSITORY", "") + if not (sha and repository): + return "" + server = os.getenv("GITHUB_SERVER_URL") or "https://github.com" + return f"{server.rstrip('/')}/{repository}/commit/{sha}" + + +def _longest_backtick_run(lines: list[str]) -> int: + """Length of the longest run of consecutive backticks across ``lines``.""" + return max((len(m) for line in lines for m in re.findall(r"`+", line)), default=0) + + +def _fenced(language: str, body: list[str]) -> list[str]: + """A fenced code block that user text cannot close. + + The body quotes commit subjects, errors and suggestions as they are. A + value with three backticks in it (a `docs:` commit showing a fence) + would close a fixed ``` fence and spill the rest of the report out as + prose, so the fence is one longer than any backtick run inside. + """ + fence = "`" * max(3, _longest_backtick_run(body) + 1) + return [f"{fence}{language}", *body, fence] + + +def _status_mark(status: str, size: int, line: bool = False) -> str: + """The ```` of a status mark: the tile at 24 px, the line mark at 16. + + The tile sits at the top of the heading. A line mark is centred on its + line of text (``absmiddle``): aligned to the top it rode about two pixels + above the words beside it. + """ + name = f"{'line-' if line else ''}{STATUS_WORDS[status]}" + align = "absmiddle" if line else "top" + return ( + f'{STATUS_GLYPHS[status]}' + ) + + +def _group_lines(results: list[model.ScopeResult]) -> str: + """One line per group, its status mark in front: the overview. + + The lines are joined by ``
`` alone, on one source line. A pull request + comment turns every newline into a line break of its own, so ``
`` + followed by a newline left an empty line between the groups there. + """ + return "
".join( + f"{_status_mark(status, 16, line=True)} {group_name}: {text}" + for group_name, scopes in _grouped(results) + for status, text in [_group_status(scopes)] + ) + + +def _hunk(scope: model.ScopeResult, status: str) -> list[str]: + """One scope's findings as a diff hunk. + + ``@@ where @@``, then red for what was found and has to go, green for + what to write instead, and a ``#`` comment for advice that has no + literal text to offer. GitHub colours all three in a ``diff`` block, + which is the only colour a comment or a job summary can carry. + """ + if scope.sha and scope.label.startswith("Commit"): + where = scope.sha[:7] + elif scope.sha and scope.label == cli.FILES_LABEL: + where = f"{scope.sha[:7]} files" + else: + where = scope.label + lines = [f"@@ {where} @@"] + if scope.label == cli.FILES_LABEL and scope.checks: + # One finding per rule, each about a path of its own: the path it + # found, then what to do about it. + for check in _findings(scope, status): + if _found(check): + lines.append(f"- {_found(check)}") + lines.append(f"# {_advice(check)}") + return lines + value = _first_value(scope) + removed: list[str] = [] + added: list[str] = [] + advice: list[str] = [] + # Whether a piece of advice is about the value itself: a subject or a + # branch name that has to change. Advice about something else, such as + # an AI tool as the commit's author, leaves the subject as context. + about_value = False + for check in _findings(scope, status): + minus, plus = _line_edits(scope, check) + removed.extend(minus) + added.extend(plus) + if not (minus or plus): + advice.append(_advice(check)) + checked = str(check.get("value") or "").strip() + about_value |= not checked or checked.splitlines()[0].strip() == value + if scope.raw_text and not scope.checks: + advice.append("the output could not be parsed, see the step log") + about_value = True + removed, added, advice = (list(dict.fromkeys(x)) for x in (removed, added, advice)) + if value and value not in removed: + # Advice about the value means it is what was found; a fix that only + # touches other lines, or advice about something else, leaves it as + # context. + lines.append(f"{'-' if about_value else ' '} {value}") + lines.extend(f"- {line}" for line in removed) + lines.extend(f"+ {line}" for line in added) + lines.extend(f"# {line}" for line in advice) + return lines + + +def _diff_block(results: list[model.ScopeResult], status: str = "fail") -> list[str]: + """The findings of one kind as a ``diff`` block, with their links under it. + + A scope appears when it has an entry of the requested kind — checked via + ``scope.failures`` / ``scope.warnings``, not ``scope.status`` — so a scope + that both failed and warned shows up in both blocks. + + A long list is cut at ``MAX_HUNKS`` and the rest folded away, so twenty + bad commits do not push the rest of the pull request off the screen. A + code block cannot hold links, so the commits shown and the rules that + spoke get one small line of them underneath. + """ + scopes = [ + scope + for scope in results + if _findings(scope, status) + or (status == "fail" and scope.raw_text and not scope.checks) + ] + hunks = [_hunk(scope, status) for scope in scopes] + shown = len(hunks) if len(hunks) <= MAX_HUNKS + HUNK_SLACK else MAX_HUNKS + lines = _fenced("diff", [line for hunk in hunks[:shown] for line in hunk]) + if len(hunks) > shown: + rest = [line for hunk in hunks[shown:] for line in hunk] + lines += ["", "
", f"and {len(hunks) - shown} more"] + lines += ["", *_fenced("diff", rest), "", "
"] + commits = list( + dict.fromkeys( + f"[`{scope.sha[:7]}`]({_commit_url(scope.sha)})" + for scope in scopes[:shown] + if _names_a_commit(scope) and _commit_url(scope.sha) + ) + ) + rules = list( + dict.fromkeys( + _rule_ref(check) for scope in scopes for check in _findings(scope, status) + ) + ) + links = [] + if commits: + links.append(f"Commits: {' '.join(commits)}") + if rules: + links.append(f"Rules: {' · '.join(rules)}") + if links: + lines += ["", f"{'  |  '.join(links)}"] + return lines + + +#: First line of the prompt "How to fix" offers for an AI coding agent. +AGENT_PROMPT = "Fix these Commit Check findings without changing any code:" + +#: The same line when a finding is about a file, which then has to change. +AGENT_PROMPT_FILES = ( + "Fix these Commit Check findings, changing only the files they name:" +) + +BRANCH_HELP = ( + "**Branch name.** Rename the branch and push it. A pull request cannot " + "change its branch, so open a new one from the renamed branch:" +) + +AUTHOR_HELP = ( + "**Author.** Set your git identity (`git config user.name`, " + "`git config user.email`), then `git commit --amend --reset-author` " + "and force-push." +) + +FILES_HELP = ( + "**Files.** Amend the commit that changed the file (`git rebase -i`, or " + "`git commit --amend` for the last one), then force-push. A later commit " + "that removes the file leaves it in the history." +) + +HOOK_HELP = ( + f"**Next time.** The [pre-commit hook]({LOCAL_HOOK_URL}) runs the same " + "rules before you push." +) + + +def _agent_prompt(failing: list[model.ScopeResult]) -> list[str]: + """A prompt to paste into an AI coding agent, one line per failing scope. + + A files scope gets a line per finding: each is about a path of its own. + """ + about_files = any(scope.label == cli.FILES_LABEL for scope in failing) + lines = [AGENT_PROMPT_FILES if about_files else AGENT_PROMPT] + for scope in failing: + if scope.label == cli.FILES_LABEL: + label = f"Files of commit {scope.sha[:7]}" if scope.sha else scope.label + for check in scope.failures: + todo = [_advice(check)] + lines.append( + f"- {_target(scope, todo, label, _found(check))}: {todo[0]}" + ) + continue + todo = list(dict.fromkeys(_instruction(scope, c) for c in scope.failures)) + is_commit = bool(scope.sha) and scope.label.startswith("Commit") + label = f"Commit {scope.sha[:7]}" if is_commit else scope.label + lines.append(f"- {_target(scope, todo, label)}: {'; '.join(todo)}") + return lines + + +def _is_last_commit(scope: model.ScopeResult) -> bool: + """Whether the scope is the newest commit: ``Commit 3/3`` or the HEAD one.""" + position = re.fullmatch(r"Commit (\d+)/(\d+)", scope.label) + return not position or position.group(1) == position.group(2) + + +def _reword_commands(commits: list[model.ScopeResult]) -> list[str]: + """The git commands that reword the failing commits and push the result.""" + if len(commits) == 1 and _is_last_commit(commits[0]): + reword = "git commit --amend" + else: + first = commits[0].sha[:7] or "" + note = '# change "pick" to "reword" on the commits above' + reword = f"git rebase -i {first}~1 {note}" + return [reword, "git push --force-with-lease"] + + +def _how_to_fix(results: list[model.ScopeResult]) -> list[str]: + """The folded "How to fix" section: only what this run's failures need. + + A prompt for whoever lets an AI agent do it, then the git commands for + doing it by hand. Most people who fail a message check have never + reworded a pushed commit, and the commands are the same every time. + """ + failing = [scope for scope in results if scope.failures] + if not failing: + return [] + commits = [scope for scope in failing if scope.label.startswith("Commit")] + labels = {scope.label for scope in failing} + # One list of lines per paragraph; a blank line goes between them. + parts = [ + ["**With an AI coding agent.** Paste this prompt:"], + _fenced("text", _agent_prompt(failing)), + ] + if commits: + many = "it" if len(commits) == 1 else "them" + parts.append([f"**Commit messages.** Reword {many}, then force-push:"]) + parts.append(_fenced("bash", _reword_commands(commits))) + if cli.FILES_LABEL in labels: + parts.append([FILES_HELP]) + if any(label.startswith("Author") for label in labels): + parts.append([AUTHOR_HELP]) + if "Branch" in labels: + # The CLI's own corrected name when it has one, a pattern otherwise. + fixes = ( + c.get("fix") for s in failing if s.label == "Branch" for c in s.failures + ) + name = next((fix for fix in fixes if fix), "/") + rename = [f"git branch -m {name}", "git push -u origin HEAD"] + parts.extend([[BRANCH_HELP], _fenced("bash", rename)]) + fields = [word for word in ("title", "description") if f"PR {word}" in labels] + if fields: + many = "it" if len(fields) == 1 else "them" + what = " and ".join(fields) + parts.append( + [f"**Pull request {what}.** Edit {many} on the pull request page."] + ) + parts.append([HOOK_HELP]) + lines = ["
", "How to fix"] + for part in parts: + lines.extend(["", *part]) + return [*lines, "", "
"] + + +def _all_checks(results: list[model.ScopeResult]) -> list[str]: + """The folded listing of every scope, passed ones included. + + The same rows the step log prints (group name, one ✔/✖ row per scope with + the checked value), with the rule's reason, suggestion and fix under each + finding, so one expand answers both "what was checked" and "what failed + and why". The same block is used whether or not anything failed. + """ + _failed, total = _check_counts(results) + unit = "check" if total == 1 else "checks" + label = f"All {total} {unit}" if total else "Details" + body = _fenced("text", _render_tree(results, include_docs=False)) + return ["
", f"{label}", "", *body, "", "
"] + + +def _commit_check_version() -> str: + """Version of the commit-check CLI that produced these results.""" + try: + from importlib.metadata import version + + return version("commit-check") + except Exception: # noqa: BLE001 - the version is decoration, never fail on it + return "" + + +def _report_footer() -> str: + """Attribution line: who checked, which version, and where to go next. + + The version is the first thing worth knowing when a result looks wrong, + and it is otherwise buried in the step log. The last link is for the + contributor who would rather hear this before pushing. + """ + installed = _commit_check_version() + version = f" {installed}" if installed else "" + return ( + f"Checked by [Commit Check]({SITE_URL}){version} · " + f"[Rules]({RULES_URL}) · [Check before you push]({LOCAL_HOOK_URL})" + ) + + +def _run_url() -> str: + """Link to this workflow run, whose page holds the job summary.""" + repository = os.getenv("GITHUB_REPOSITORY", "") + run_id = os.getenv("GITHUB_RUN_ID", "") + if not (repository and run_id): + return "" + server = os.getenv("GITHUB_SERVER_URL") or "https://github.com" + return f"{server.rstrip('/')}/{repository}/actions/runs/{run_id}" + + +def _elsewhere(what: str) -> str: + """Point to where the parts a shortened comment left out can be read.""" + where = "job summary" if _summary_written() else "step log" + url = _run_url() + place = f"[{where}]({url})" if url else where + return f"{what} are in the {place} of this run." + + +def render_report(results: list[model.ScopeResult], detail: str = "full") -> str: + """Render the Markdown report shared by the job summary and PR comment. + + Opens with the hidden marker and a heading that is the verdict — the + status mark and ``Commit Check failed`` / ``passed`` — then one line per + group, the diff of what failed, a diff of the warnings when the config + listed any rule under ``warn``, the folded "How to fix", and the folded + listing of every scope. + + ``detail`` is for a PR comment that would not fit (``render_pr_comment``): + ``"short"`` leaves out the listing, ``"headline"`` everything below the + group lines, and either says where to read what it left out. + + A warned scope counts toward "passed", never toward "failed": it ran, + found something, and is reported in full, but the config asked for it to + be surfaced rather than enforced. + """ + failed, total = _check_counts(results) + warned = _warn_count(results) + skipped = _skip_count(results) + + if failed: + status, verdict = "fail", "failed" + elif total and skipped == total: + # Nothing ran, so there is no success to announce. Saying "passed" + # here is the defect this branch exists to prevent. + status, verdict = "skip", "skipped" + elif warned: + status, verdict = "warn", "passed with warnings" + else: + status, verdict = "pass", "passed" + + lines = [COMMENT_MARKER, f"## {_status_mark(status, 24)} Commit Check {verdict}"] + lines.append("") + if status == "skip": + lines.extend(["Nothing was validated.", ""]) + if results: + lines.extend([_group_lines(results), ""]) + if skipped and _skip_reasons(results): + lines.extend([_skip_reasons(results), ""]) + if detail == "headline": + what = "The findings and how to fix them" if failed or warned else "All checks" + lines.extend([_elsewhere(what), "", _report_footer()]) + return "\n".join(lines) + if failed: + lines.extend([*_diff_block(results), ""]) + if warned: + lines.extend(["**Warnings**", "", *_diff_block(results, "warn"), ""]) + if failed: + how = _how_to_fix(results) + lines.extend([*how, ""] if how else []) + if detail == "short": + lines.extend([_elsewhere(f"All {_plural(total, 'check')}"), ""]) + else: + lines.extend([*_all_checks(results), ""]) + lines.append(_report_footer()) + return "\n".join(lines) + + +def render_job_summary(results: list[model.ScopeResult]) -> str: + """Create the Markdown body for the GitHub job summary.""" + return render_report(results) + + +#: The longest comment GitHub accepts, in UTF-16 code units. +COMMENT_LIMIT = 65536 + + +def _comment_length(body: str) -> int: + """Length of a comment as GitHub counts it: in UTF-16 code units.""" + return len(body.encode("utf-16-le")) // 2 + + +def render_pr_comment(results: list[model.ScopeResult]) -> str: + """Create the Markdown body for the PR comment (same report as summary). + + The report grows with the pull request: every failing commit's message + is quoted in the diff, the prompt and the listing. A few dozen failing + commits ran past GitHub's limit, the API refused the comment, and an + earlier one, perhaps saying "passed", stayed on the pull request. So a + report that does not fit drops the listing, then everything under the + group lines, and points to the run for the rest. The job summary, with + its far higher limit, keeps the full report. + """ + for detail in ("full", "short"): + body = render_report(results, detail) + if _comment_length(body) <= COMMENT_LIMIT: + return body + return render_report(results, "headline") diff --git a/main.py b/main.py index 744b4a3..5f05298 100755 --- a/main.py +++ b/main.py @@ -10,2973 +10,22 @@ * **PR comment** — the same report (idempotently updated) and exposes the check data as JSON in the ``result`` action output. -""" - -import json -import os -import re -import subprocess -import sys -import tempfile -import tomllib -import uuid -from dataclasses import dataclass, field -from typing import Any - -COMMIT_MESSAGE_DELIMITER = "\x00" -RULES_URL = "https://commit-check.com/rules/" - -#: Hidden marker identifying comments this action owns. -# -# Comment identity has to be something a human cannot type by accident. The -# previous title-prefix match meant any comment opening with "# Commit Check" -# was treated as ours — and old ones are deleted, not just skipped. An HTML -# comment is invisible in the rendered body and is what Codecov, SonarQube and -# CodSpeed all use for the same purpose. -COMMENT_MARKER = "" - -#: Prefixes of report bodies written by earlier versions, kept so the first run -#: after upgrading adopts the existing comment instead of posting a second one. -#: Drop these once a release has been out long enough. -LEGACY_TITLES = ("# Commit Check", "# Commit-Check") - -GITHUB_STEP_SUMMARY = os.getenv("GITHUB_STEP_SUMMARY", "") - -#: Human-readable labels for the non-message CLI flags. -CHECK_LABELS = { - "--branch": "Branch", - "--author-name": "Author name", - "--author-email": "Author email", -} - - -#: Label of the scopes that check the files a commit changes (``files: true``). -FILES_LABEL = "Files" - - -#: Boolean inputs whose value was neither true nor false, as ``(name, value)``. -#: ``main`` fails the step on them before any check runs. -INVALID_FLAGS: list[tuple[str, str]] = [] - - -def env_flag(name: str, default: str = "false") -> bool: - """Read a GitHub Action boolean input: ``true`` or ``false``, any case. - - Anything else (``yes``, ``on``, a typo) used to read as false and turn - the check off without a word. It is now recorded in ``INVALID_FLAGS``, - and the step fails with the input's name. - """ - value = os.getenv(name, default).strip().lower() - if value not in ("true", "false"): - INVALID_FLAGS.append((name, os.getenv(name, default))) - return value == "true" - - -def _reconfigure_io() -> None: - """Reconfigure stdout/stderr to UTF-8 so emoji and check marks never - crash on runners with legacy encodings (e.g. cp1252 on Windows).""" - for stream in (sys.stdout, sys.stderr): - if hasattr(stream, "reconfigure"): - stream.reconfigure(encoding="utf-8", errors="replace") - - -MESSAGE_ENABLED = env_flag("MESSAGE") -BRANCH_ENABLED = env_flag("BRANCH") -AUTHOR_NAME_ENABLED = env_flag("AUTHOR_NAME") -AUTHOR_EMAIL_ENABLED = env_flag("AUTHOR_EMAIL") -FILES_ENABLED = env_flag("FILES") -DRY_RUN_ENABLED = env_flag("DRY_RUN") -JOB_SUMMARY_ENABLED = env_flag("JOB_SUMMARY") -PR_COMMENTS_ENABLED = env_flag("PR_COMMENTS") -PR_TITLE_ENABLED = env_flag("PR_TITLE") -PR_BODY_AI_ATTRIBUTION_ENABLED = env_flag("PR_BODY_AI_ATTRIBUTION") -MESSAGE_AI_ATTRIBUTION_ENABLED = env_flag("MESSAGE_AI_ATTRIBUTION") - -#: Where the checks read the config: ``head``, the files the workflow -#: checked out, or ``base``, the pull request's base branch, so that a pull -#: request cannot loosen the rules it is checked against. -CONFIG_SOURCES = ("head", "base") -CONFIG_SOURCE = os.getenv("CONFIG_SOURCE", "head").strip().lower() or "head" - -#: The config files commit-check looks for, in its order. -CONFIG_PATHS = ( - "cchk.toml", - "commit-check.toml", - ".github/cchk.toml", - ".github/commit-check.toml", -) - -#: Passed to every commit-check run: ``--config`` and the base branch's -#: config, when ``config-source`` is ``base``; empty otherwise. -CONFIG_ARGS: list[str] = [] - - -#: The AI attribution rules: what ``message-ai-attribution: true`` keeps. -AI_RULE_IDS = frozenset({"CC013", "CC014", "CC015", "CC016", "CC017"}) - - -#: The label ``ai-label: true`` puts on a pull request that an AI tool wrote. -DEFAULT_AI_LABEL = "ai-assisted" -#: The colour a label gets when the Action has to create it. -AI_LABEL_COLOR = "8250df" - - -def ai_label_name() -> str | None: - """The label to put on an AI-written pull request, or ``None`` for none. - - ``ai-label: true`` means the default label; any other value but - ``false`` is the label's own name. - """ - value = os.getenv("AI_LABEL", "false").strip() - if not value or value.lower() == "false": - return None - return DEFAULT_AI_LABEL if value.lower() == "true" else value - - -#: AI coding agents that open pull requests from their own GitHub App, by -#: login, with the tool each one is. The same list as the GitHub App's. -AI_AGENT_BOTS = { - "amazon-q-developer[bot]": "Amazon Q Developer", - "chatgpt-codex-connector[bot]": "OpenAI Codex", - "claude[bot]": "Claude Code", - "copilot-swe-agent[bot]": "GitHub Copilot", - "cursor[bot]": "Cursor", - "devin-ai-integration[bot]": "Devin", - "factory-droid[bot]": "Factory Droid", - "google-labs-jules[bot]": "Jules", -} - - -@dataclass -class ScopeResult: - """Result of running commit-check against one scope (PR title, one commit, - branch, author, ...). - - ``checks`` holds the parsed JSON check outcomes (only set when the CLI - produced valid JSON); ``raw_text`` holds the raw CLI output when parsing - failed (a defensive fallback so unexpected output is never swallowed). - - ``sha`` is the full hash of the commit a message scope checked, or ``""`` - for scopes that have no commit (PR title, branch, author). It is kept - apart from ``label`` on purpose: ``label`` ("Commit 2/3") is what the - ``result`` output has always carried, so downstream steps can keep - matching on it, and the hash is appended only where a person reads it. - """ - - label: str - checks: list[dict[str, str]] = field(default_factory=list) - raw_text: str = "" - sha: str = "" - #: The AI tools the CLI found in what this scope checked (``ai_tools``). - ai_tools: list[str] = field(default_factory=list) - #: The text this scope checked (a commit message, the PR title), when the - #: action piped it in. The report compares it with a rule's ``fix`` to name - #: the lines to change. Never part of the ``result`` output. - text: str = "" - #: ``(removed, added)`` lines per rule, for a text too long to carry as a - #: ``fix`` (the PR description). Keyed by ``_rule_key``. - edits: dict[str, tuple[list[str], list[str]]] = field(default_factory=dict) - #: What an author check looked at (the name or the email), which the CLI - #: does not report for a skipped one; the listing shows it in that row. - subject: str = "" - - @property - def display_label(self) -> str: - """The label as a reader sees it: ``Commit 2/3 (5584f46)``. - - Seven characters, like ``git log --oneline``; the full hash goes - into the link and the ``result`` output, where it is not read by eye. - """ - return f"{self.label} ({self.sha[:7]})" if self.sha else self.label - - @property - def status(self) -> str: - """Overall status: ``pass``, ``fail``, ``warn``, or ``skip``. - - ``skip`` means every rule in this scope declined to run — the author - is on an ``ignore_authors`` list, or there was nothing to check. It - is reported separately from ``pass`` because a skipped scope - validated nothing, and rendering the two identically let a bypassed - policy read as an enforced one. - - ``warn`` means a rule found something but is listed under the - config's top-level ``warn``, so commit-check reports it without - failing the run. A real failure still outranks a warning in the same - scope (CC202 stands in for ``branch`` when the two disagree), and a - single real verdict — failing or warning — outranks the skips: a - scope is ``skip`` only when *all* of its checks skipped. - """ - if self.raw_text and not self.checks: - return "fail" - if any(c["status"] == "fail" for c in self.checks): - return "fail" - if any(c["status"] == "warn" for c in self.checks): - return "warn" - if self.checks and all(c["status"] == "skip" for c in self.checks): - return "skip" - return "pass" - - @property - def skip_reason(self) -> str: - """Why a skipped scope did not run, or ``""`` when nobody said. - - Newer commit-check releases name the reason on each skipped check (e.g. - "author dependabot[bot] is in [commit].ignore_authors"). A bare - "skipped" left the reader unable to tell a deliberate bypass from a - broken setup. - """ - if self.status != "skip": - return "" - return next((c["reason"] for c in self.checks if c.get("reason")), "") - - @property - def failures(self) -> list[dict[str, str]]: - """The checks that failed in this scope.""" - return [c for c in self.checks if c["status"] == "fail"] - - @property - def warnings(self) -> list[dict[str, str]]: - """The checks reported as warnings in this scope.""" - return [c for c in self.checks if c["status"] == "warn"] - - -def overall_status(results: list[ScopeResult]) -> str: - """Reduce scope statuses to one of ``pass``/``fail``/``warn``/``skip``. - - One function, used by every completion path, because the alternative - is what this replaced: four separate ``all(... == "pass")`` tests, each - correct only while exactly two statuses existed. The moment ``skip`` - appeared they all silently reclassified a skipped run as a failure. - - Precedence is fail, then skip, then warn, then pass. ``skip`` requires - at least one scope and all of them skipped: nothing was validated, and a - warning cannot have been found where nothing ran. ``warn`` means at - least one scope carries a finding the config listed under ``warn`` and - nothing failed. It is distinct from ``pass`` so a downstream step can - act on a bent-but-not-broken policy without walking every scope; the - exit code does not distinguish the two (see ``exit_code_for``), because - the whole point of ``warn`` is that it never fails the workflow. - """ - if any(scope.status == "fail" for scope in results): - return "fail" - if results and all(scope.status == "skip" for scope in results): - return "skip" - if any(scope.status == "warn" for scope in results): - return "warn" - return "pass" - - -def exit_code_for(results: list[ScopeResult]) -> int: - """Only a failure is an error. - - A skipped run validated nothing, but it violated no policy either, so - it must not fail the workflow. - """ - return 1 if overall_status(results) == "fail" else 0 - - -def log_env_vars(): - """Logs the environment variables for debugging purposes. - - Uses the ``::debug::`` workflow command so these only appear in the - action log when ``ACTIONS_STEP_DEBUG`` is set to ``true``. - """ - for name in ( - "MESSAGE", - "BRANCH", - "AUTHOR_NAME", - "AUTHOR_EMAIL", - "FILES", - "DRY_RUN", - "JOB_SUMMARY", - "PR_COMMENTS", - "PR_TITLE", - "PR_BODY_AI_ATTRIBUTION", - "MESSAGE_AI_ATTRIBUTION", - "AI_LABEL", - ): - value = os.getenv(name, "false") - print(f"::debug::{name}={value}") - print(f"::debug::CONFIG_SOURCE={CONFIG_SOURCE}") - - -def is_pr_event() -> bool: - """Return whether the workflow was triggered by a PR-style event.""" - return os.getenv("GITHUB_EVENT_NAME", "") in {"pull_request", "pull_request_target"} - - -#: The one fix for every "history is too shallow" finding below. -SHALLOW_CHECKOUT_HINT = "is actions/checkout using fetch-depth: 0?" - -#: On pull_request_target the default checkout is the base branch, which -#: holds none of the pull request at any depth; the fix is to check the -#: pull request out. -TARGET_CHECKOUT_HINT = ( - "is the workflow checking out the pull request, e.g. " - "ref: refs/pull//merge with fetch-depth: 0?" -) - - -def checkout_hint() -> str: - """The fix for a checkout that does not hold the pull request.""" - if os.getenv("GITHUB_EVENT_NAME") == "pull_request_target": - return TARGET_CHECKOUT_HINT - return SHALLOW_CHECKOUT_HINT - - -#: The pull request branch tip. On ``refs/pull/N/merge`` HEAD is a merge -#: commit that GitHub authored, so its recorded author is -#: ``GitHub `` whatever the contributor configured; -#: HEAD^2 is the commit the contributor actually made. -PR_HEAD_REV = "HEAD^2" - -#: The checks whose subject is a commit's recorded author. -AUTHOR_FLAGS = ("--author-name", "--author-email") - - -def warn_shallow_checkout(problem: str, consequence: str) -> None: - """Annotate a PR run whose clone is too shallow to do what was asked. - - ``actions/checkout`` defaults to ``fetch-depth: 1``, which leaves the - synthetic merge commit as the only commit in the clone. Every caller - hits that same root cause, so they share one message shape that names - the fix rather than only the symptom. - """ - text = f"{problem} ({checkout_hint()}); {consequence}" - print(f"::warning title=commit-check::{_annotation_escape(text)}") - - -def get_pr_event() -> dict[str, Any]: - """The ``pull_request`` object from the event payload, or ``{}``.""" - if not is_pr_event(): - return {} - event_path = os.getenv("GITHUB_EVENT_PATH") - if not event_path: - return {} - try: - with open(event_path, "r", encoding="utf-8") as f: - event = json.load(f) - return event.get("pull_request") or {} - except Exception as e: # noqa: BLE001 - a bad payload warns, never fails the step - print(f"::warning::Failed to read the PR from the event: {e}", file=sys.stderr) - return {} - - -def get_pr_head_sha() -> str | None: - """The pull request's head commit, from the event payload.""" - return get_pr_event().get("head", {}).get("sha") or None - - -def get_pr_base_sha() -> str | None: - """The base branch tip the pull request targets, from the event payload.""" - return get_pr_event().get("base", {}).get("sha") or None - - -def _rev_resolves(rev: str) -> bool: - """Whether ``rev`` names a commit the clone actually has.""" - try: - result = subprocess.run( - ["git", "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"], - capture_output=True, - encoding="utf-8", - check=False, - ) - except OSError: - return False - return result.returncode == 0 - - -def _local_author(sha: str) -> tuple[str, str] | None: - """Author (name, email) of a commit the clone holds, or ``None``.""" - try: - result = subprocess.run( - ["git", "show", "-s", "--format=%an%x1f%ae", sha], - capture_output=True, - encoding="utf-8", - check=False, - ) - except OSError: - return None - name, sep, email = result.stdout.strip("\n").partition("\x1f") - if result.returncode != 0 or not sep: - return None - return name, email - - -def _fetch_commit(sha: str) -> bool: - """Fetch one commit, without its history, into a clone that lacks it.""" - try: - result = subprocess.run( - ["git", "fetch", "--no-tags", "--quiet", "--depth=1", "origin", sha], - capture_output=True, - encoding="utf-8", - check=False, - ) - except OSError: - return False - return result.returncode == 0 and _rev_resolves(sha) - - -class BaseConfigError(Exception): - """The base branch's config is there but cannot be used as it is.""" - - -def _base_blob(sha: str, path: str) -> bytes | None: - """The file at ``path`` in commit ``sha``, or ``None`` when it has none. - - Absence is read from the commit's tree, so a file that is there but - cannot be read -- a blob a partial clone could not fetch -- is an error, - never taken for no config. A symbolic link is refused: its blob is the - target's path, not the config. - - :raises BaseConfigError: If the file is there but cannot be read. - """ - try: - listed = subprocess.run( - ["git", "ls-tree", "--full-tree", sha, "--", path], - capture_output=True, - check=False, - ) - if listed.returncode != 0: - raise BaseConfigError(f"git could not list {path} in the base commit") - if not listed.stdout: - return None - mode, kind, _rest = listed.stdout.split(b" ", 2) - if kind != b"blob": - return None # a folder of that name is no config file - if mode == b"120000": - raise BaseConfigError( - f"{path} is a symbolic link on the base branch, which " - "config-source: base does not follow" - ) - result = subprocess.run( - ["git", "cat-file", "blob", f"{sha}:{path}"], - capture_output=True, - check=False, - ) - except OSError as e: - raise BaseConfigError(f"git could not run: {e}") from e - if result.returncode != 0: - raise BaseConfigError(f"{path} could not be read from the base commit") - return result.stdout - - -def _checked_out_config() -> tuple[str, bytes] | None: - """The config file the checkout holds, as (path, contents), or ``None``.""" - for path in CONFIG_PATHS: - if os.path.isfile(path): - with open(path, "rb") as f: - return path, f.read() - return None - - -def _local_parent(data: bytes) -> str | None: - """A config's ``inherit_from`` when it names a local file. - - A ``github:`` or HTTPS parent is fetched from where it names, whichever - branch the config came from; only a local file could be read from the - pull request. - """ - try: - parent = tomllib.loads(data.decode("utf-8")).get("inherit_from") - except (UnicodeDecodeError, tomllib.TOMLDecodeError): - return None # commit-check reports the broken file itself - if not isinstance(parent, str) or not parent: - return None - if parent.startswith(("github:", "https://", "http://")): - return None - return parent - - -def _repo_path(work: str, path: str) -> str | None: - """``path`` under ``work`` as a repository path, or ``None`` outside it.""" - path = os.path.normpath(path) - if os.path.commonpath([work, path]) != work: - return None - return os.path.relpath(path, work).replace(os.sep, "/") - - -def _config_error(text: str) -> bool: - print(f"::error title=commit-check::{_annotation_escape(text)}") - return False - - -def use_base_config() -> bool: - """With ``config-source: base``, point every check at the base config. - - The base branch's config file is written under ``RUNNER_TEMP`` at its - path in the repository, and ``CONFIG_ARGS`` names it. A parent it names - by local path (``inherit_from``) is copied from the base branch too, to - the path commit-check tries first, next to the config; otherwise - commit-check would go on to find the pull request's copy. Without a - config on the base branch the checks run on the defaults. - - Fails closed: if the base branch cannot be read, the step fails rather - than check against a config the pull request may have changed. - - Returns whether the checks can run. - """ - if CONFIG_SOURCE != "base": - return True - if not is_pr_event(): - print( - "::notice title=commit-check::config-source: base applies to pull " - "requests; this run reads the checked-out config" - ) - return True - sha = get_pr_base_sha() - if not sha or not (_rev_resolves(sha) or _fetch_commit(sha)): - return _config_error( - "config-source is base, but the base branch commit could not be " - f"read ({checkout_hint()}); nothing was checked, so that a config " - "the pull request changes cannot apply" - ) - try: - return _stage_base_config(sha) - except BaseConfigError as e: - return _config_error(f"config-source is base, but {e}; nothing was checked") - - -def _stage_base_config(sha: str) -> bool: - """Write the base commit's config under ``RUNNER_TEMP``; see above.""" - found = None - for path in CONFIG_PATHS: - data = _base_blob(sha, path) - if data is not None: - found = (path, data) - break - path, data = found or ("cchk.toml", b"") - work = os.path.realpath( - tempfile.mkdtemp(prefix="commit-check-config-", dir=os.getenv("RUNNER_TEMP")) - ) - target = os.path.join(work, *path.split("/")) - os.makedirs(os.path.dirname(target), exist_ok=True) - with open(target, "wb") as f: - f.write(data) - - parent = _local_parent(data) - if parent is not None: - if os.path.isabs(parent) or parent.startswith(("/", "\\")): - return _config_error( - f"config-source is base, but the base branch config {path} " - f'inherits from "{parent}", an absolute path the base branch ' - "cannot vouch for; nothing was checked" - ) - # The path as commit-check builds it, next to the config. Checked - # with this platform's separators, so "..\\x" cannot climb out on - # Windows. - dest = os.path.join(os.path.dirname(target), parent) - beside = _repo_path(work, dest) - if beside is None: - return _config_error( - f"config-source is base, but the base branch config {path} " - f'inherits from "{parent}", outside the repository; nothing ' - "was checked" - ) - # commit-check looks next to the config first, then from the top of - # the repository; whichever the base branch holds is copied to the - # first place, so the second is never reached. - top = _repo_path(work, os.path.join(work, parent)) - parent_data = None - for candidate in [beside] + ([top] if top else []): - parent_data = _base_blob(sha, candidate) - if parent_data is not None: - break - if parent_data is None: - # As on the base branch itself, a parent that is missing leaves - # the config in force; the empty copy keeps the pull request's - # file, if it adds one, from being read in its place. - print( - "::notice title=commit-check::" - + _annotation_escape( - f'inherit_from "{parent}" in {path} is not on the base ' - "branch; checking with that config alone" - ) - ) - parent_data = b"" - # A parent that names a folder ("." or the config's own folder) is - # no file: commit-check says so and keeps the config, as it would on - # the base branch. - if not os.path.isdir(os.path.normpath(dest)): - # The folders of the path as written, so that "policies/../x" - # resolves here too, not from the checkout. - os.makedirs(os.path.dirname(dest), exist_ok=True) - with open(os.path.normpath(dest), "wb") as f: - f.write(parent_data) - - CONFIG_ARGS[:] = ["--config", target] - if _checked_out_config() != found: - if found is None: - text = ( - "This pull request adds a commit-check config. The checks " - "use the defaults, as the base branch has no config; the new " - "config takes effect after it merges" - ) - else: - text = ( - f"This pull request changes the commit-check config. The " - f"checks use {path} from the base branch; the change takes " - "effect after it merges" - ) - print(f"::notice title=commit-check::{_annotation_escape(text)}") - return True - - -def pr_head_rev() -> str | None: - """The commit whose recorded author the PR's author checks read. - - First choice is ``pull_request.head.sha`` from the event payload: it - names the branch tip for ``pull_request`` and ``pull_request_target`` - alike, whatever was checked out, as long as the clone has it. Failing - that, ``HEAD^2`` on a ``pull_request`` checkout, where HEAD is the - merge ref and its second parent is that same tip. Never ``HEAD^2`` on - ``pull_request_target``: there HEAD is the base branch, so ``HEAD^2`` - is nothing, or the parent of some unrelated merge on it. A shallow clone - that lacks the tip gets it fetched, without its history. - - ``None`` when neither can be had. - """ - sha = get_pr_head_sha() - if sha and (_rev_resolves(sha) or _fetch_commit(sha)): - return sha - if os.getenv("GITHUB_EVENT_NAME") == "pull_request" and _rev_resolves(PR_HEAD_REV): - return PR_HEAD_REV - return None - - -#: The rule each author check runs, for a scope that had to be skipped. -AUTHOR_RULES = { - "--author-name": ("CC101", "author_name"), - "--author-email": ("CC102", "author_email"), -} - - -def skipped_author_scope(flag: str) -> ScopeResult: - """A scope recording that an author check could not run at all. - - Reported as ``skip``, never as a pass: nothing was validated, and the - one commit the clone does hold (HEAD) has the wrong author for a pull - request, GitHub's merge commit or the base branch. - """ - rule_id, check = AUTHOR_RULES[flag] - return ScopeResult( - label=CHECK_LABELS[flag], - checks=[ - { - "rule_id": rule_id, - "check": check, - "status": "skip", - "value": "", - "error": "", - "suggest": "", - "docs_url": "", - "reason": "the pull request's head commit could not be resolved", - } - ], - ) - - -#: Why a files scope checked nothing. -FILES_UNCONFIGURED = "no rule is set in the [files] section of the config" -FILES_NOT_IN_CLONE = "the checkout lacks the commit or its parent" -FILES_UNLISTED = "the pull request's commits could not be listed" -FILES_NOTHING_CHANGED = "the commit adds or changes no file" - - -def skipped_files_scope(reason: str, sha: str = "") -> ScopeResult: - """A scope recording that the files of a commit, or of all, went unchecked. - - Reported as ``skip``, never as a pass: nothing was validated. - """ - return ScopeResult( - label=FILES_LABEL, - sha=sha, - checks=[ - { - "rule_id": "", - "check": "files", - "status": "skip", - "value": "", - "error": "", - "suggest": "", - "docs_url": "", - "reason": reason, - } - ], - ) - - -#: Why an AI-only scope ran no rule: under the default policy there is none to run. -AI_POLICY_IGNORED = 'ai_attribution is "ignore": set it to "forbid" or "disclose"' - - -def skip_when_no_ai_rule_ran(scope: ScopeResult) -> ScopeResult: - """Report an AI-only scope that ran no rule as skipped, not passed. - - Under the default ``ai_attribution = "ignore"`` the CLI builds none of - the AI rules, so it returns an empty list of checks. Shown as a pass, that - read as "checked, nothing found" to someone who turned the input on and - forgot the policy. - """ - if scope.checks or scope.raw_text: - return scope - scope.checks = [ - { - "rule_id": "CC013", - "check": "ai_attribution", - "status": "skip", - "value": "", - "error": "", - "suggest": "", - "docs_url": "", - "reason": AI_POLICY_IGNORED, - } - ] - return scope - - -def _message_value(scope: ScopeResult) -> str: - """The whole commit message, as the CLI's ``message`` rule reports it.""" - return next( - ( - str(c.get("value") or "") - for c in scope.checks - if c.get("check") == "message" - ), - "", - ) - - -def keep_ai_rules(scope: ScopeResult) -> ScopeResult: - """Narrow a commit message scope to the AI rules (CC013 to CC017). - - ``message-ai-attribution: true`` does this whatever ``message`` says: - ``message`` defaults to true, so asking for the AI rules alone must not - need it turned off as well. The CLI runs every message rule and the - format rules' verdicts are dropped here, so the CLI needs no flag of - its own for it. A scope left with no rule, under the default - ``ai_attribution = "ignore"``, is reported as skipped. - """ - if not MESSAGE_AI_ATTRIBUTION_ENABLED or scope.raw_text: - return scope - # The message rule's value is the whole message: keep it for the report - # before the rule itself is dropped (outside a PR nothing was piped in). - scope.text = scope.text or _message_value(scope) - scope.checks = [c for c in scope.checks if c.get("rule_id") in AI_RULE_IDS] - return skip_when_no_ai_rule_ran(scope) - - -def get_pr_title() -> str | None: - """Read PR title from GitHub event payload.""" - if not is_pr_event(): - return None - event_path = os.getenv("GITHUB_EVENT_PATH") - if not event_path: - return None - try: - with open(event_path, "r", encoding="utf-8") as f: - event = json.load(f) - return event.get("pull_request", {}).get("title") - except Exception as e: # noqa: BLE001 - a bad payload warns, never fails the step - print(f"::warning::Failed to read PR title from event: {e}", file=sys.stderr) - return None - - -def get_pr_body() -> str | None: - """Read the pull request description from the event payload. - - GitHub sends ``null`` for a pull request opened with no description. - """ - body = get_pr_event().get("body") - return body if isinstance(body, str) and body.strip() else None - - -def get_pr_opener_tool() -> str | None: - """The AI tool that opened the pull request from its own app, if any.""" - login = (get_pr_event().get("user") or {}).get("login") or "" - return AI_AGENT_BOTS.get(str(login).lower()) - - -def _rule_key(check: dict[str, str]) -> str: - """What names a rule within one scope: its ID, or its name without one.""" - return check.get("rule_id") or check.get("check", "") - - -def lines_removed(text: str, fixed: str) -> list[str]: - """The non-blank lines of ``text`` that ``fixed`` no longer has, in order. - - A line repeated in ``text`` counts once per copy ``fixed`` dropped. - """ - kept: dict[str, int] = {} - for line in fixed.splitlines(): - kept[line] = kept.get(line, 0) + 1 - removed = [] - for line in text.splitlines(): - if kept.get(line, 0): - kept[line] -= 1 - elif line.strip(): - removed.append(line.strip()) - return removed - - -def name_the_line_changes(scope: ScopeResult, body: str) -> None: - """Name the lines to change instead of repeating the description. - - For a message the CLI's ``fix`` is the corrected text, short enough to - paste. A description can run to a page, and the summary, the comment and - the annotation would each repeat it in full; the lines to delete or add - are what its author needs. - """ - for check in scope.checks: - fixed = check.get("fix") or "" - if not fixed: - continue - removed = lines_removed(body, fixed) - added = lines_removed(fixed, body) - scope.edits[_rule_key(check)] = (removed, added) - parts = [] - if removed: - parts.append("remove " + "; ".join(f'"{line}"' for line in removed)) - if added: - parts.append("add " + "; ".join(f'"{line}"' for line in added)) - if parts: - check["suggest"] = "In the description, " + ", and ".join(parts) - check["fix"] = "" - - -#: The AI tools found in the pull request description when it was read for -#: the label only (``ai-label`` without ``pr-body-ai-attribution``), so it is no scope. -PR_BODY_AI_TOOLS: list[str] = [] - - -#: One commit to check: ``(full sha, message)``. -Commit = tuple[str, str] - -#: ``git log`` format that yields, per commit, the full hash and the raw -#: message as two NUL-terminated fields (``%x00`` is git's spelling of -#: COMMIT_MESSAGE_DELIMITER; a literal NUL cannot be passed as an argument). -#: NUL cannot appear in a hash or a message, so the split is unambiguous -#: however many blank lines the message holds. -COMMIT_LOG_FORMAT = "--pretty=format:%H%x00%B%x00" - - -def parse_commit_messages(output: str) -> list[Commit]: - """Split ``git log`` output (see ``COMMIT_LOG_FORMAT``) into commits. - - The fields alternate hash, message, hash, message; git puts a newline - between commits, which lands on the front of the next hash and is - stripped along with the message's trailing newline. A commit with an - empty message is kept, as ``(sha, "")``: it is a commit of the pull - request like any other, and ``allow_empty_commits`` is the rule that - judges it. - """ - fields = [f.strip("\n") for f in output.split(COMMIT_MESSAGE_DELIMITER)] - return [(sha, message) for sha, message in zip(fields[0::2], fields[1::2]) if sha] - - -def _messages_in_range(revision_range: str) -> list[Commit]: - """Commits in ``revision_range`` as ``(sha, message)``, oldest first, or ``[]``.""" - result = subprocess.run( - ["git", "log", COMMIT_LOG_FORMAT, "--reverse", revision_range], - capture_output=True, - encoding="utf-8", - check=False, - ) - if result.returncode == 0 and result.stdout: - return parse_commit_messages(result.stdout) - return [] - - -def head_sha() -> str: - """The full hash of HEAD, or ``""`` when git cannot say. - - Only decoration for the non-PR ``Commit message`` scope, so a failure - here never fails the run: the message is still checked, just unlabelled. - """ - try: - result = subprocess.run( - ["git", "rev-parse", "HEAD"], - capture_output=True, - encoding="utf-8", - check=False, - ) - except OSError: - return "" - return result.stdout.strip() if result.returncode == 0 else "" - - -def get_messages_from_event_range() -> list[Commit]: - """Read PR commit messages between the payload's base and head commits. - - ``pull_request.base.sha`` and ``pull_request.head.sha`` name the pull - request whatever the workflow checked out, for ``pull_request`` and - ``pull_request_target`` alike; the range is usable whenever the clone - holds both commits. - """ - base_sha, head_sha = get_pr_base_sha(), get_pr_head_sha() - if not (base_sha and head_sha): - return [] - if not (_rev_resolves(head_sha) and _rev_resolves(base_sha)): - return [] - return _messages_in_range(f"{base_sha}..{head_sha}") - - -def get_messages_from_merge_ref() -> list[Commit]: - """Read PR commit messages from GitHub's synthetic merge commit. - - Only meaningful on a ``pull_request`` checkout, where HEAD is - ``refs/pull/N/merge``. On ``pull_request_target`` HEAD is the base - branch: ``HEAD^2`` is then nothing, or the parent of some unrelated - merge on it, whose commits are not the pull request's. - """ - if os.getenv("GITHUB_EVENT_NAME") != "pull_request": - return [] - return _messages_in_range("HEAD^1..HEAD^2") - - -def get_messages_from_head_ref(base_ref: str) -> list[Commit]: - """Read PR commit messages when the workflow checks out the head SHA.""" - return _messages_in_range(f"origin/{base_ref}..HEAD") - - -#: The most commits GitHub's pull request commits endpoint returns. -API_COMMIT_LIMIT = 250 - -#: Author (name, email) of each commit listed by the API, by hash. Those -#: commits are not in the clone, so this is the only record of who wrote them. -API_AUTHORS: dict[str, tuple[str, str]] = {} - - -def get_messages_from_api() -> list[Commit]: - """The pull request's commits from the REST API, for a clone without them. - - The default ``actions/checkout`` clone holds only GitHub's merge commit. - Deepening it cannot list a pull request that merged its base branch in; - the API lists any pull request exactly. It stops at 250 commits, so a - longer one is left unlisted rather than checked in part. - """ - pr = get_pr_event() - number, total = pr.get("number"), pr.get("commits", 0) - token, repo = os.getenv("GITHUB_TOKEN"), os.getenv("GITHUB_REPOSITORY") - if not (number and token and repo) or total > API_COMMIT_LIMIT: - return [] - from github import Auth, Github # type: ignore - - api_url = os.getenv("GITHUB_API_URL", "https://api.github.com") - pull = ( - Github(auth=Auth.Token(token), base_url=api_url).get_repo(repo).get_pull(number) - ) - listed = list(pull.get_commits()) - commits = [(c.sha, c.commit.message) for c in listed] - for c in listed: - author = c.commit.author - if author is not None: - API_AUTHORS[c.sha] = (author.name or "", author.email or "") - # A force push after the event can leave the same count but other commits. - head = get_pr_head_sha() - if len(commits) != total or (head and commits[-1][0] != head): - return [] - return commits - - -def get_pr_commit_messages() -> list[Commit]: - """Get all commits, as ``(sha, message)``, for the current PR workflow. - - The event payload's ``base.sha..head.sha`` is tried first: it names the - pull request exactly, whatever was checked out. On a ``pull_request`` - checkout HEAD is the synthetic merge commit, so ``HEAD^1..HEAD^2`` is - the same range. If the workflow checks out the PR head SHA instead, - diff against ``origin/`` when that ref is available locally. - A clone that holds none of these, or only part of the pull request (a - shallow boundary ends a range early), asks the API. - """ - if not is_pr_event(): - return [] - - try: - base_ref = os.getenv("GITHUB_BASE_REF", "") - messages = ( - get_messages_from_event_range() - or get_messages_from_merge_ref() - or (get_messages_from_head_ref(base_ref) if base_ref else []) - ) - total = get_pr_event().get("commits") - if messages and (not total or len(messages) == total): - return messages - from_api = get_messages_from_api() - if from_api: - return from_api - if messages: - warn_shallow_checkout( - f"Only {len(messages)} of the pull request's {total} commits " - "could be listed", - "the others were not checked", - ) - return messages - except Exception as e: # noqa: BLE001 - warn, then check what we have - print( - f"::warning::Failed to retrieve PR commit messages: {e}", - file=sys.stderr, - ) - return [] - - -#: Notices already relayed, so one repeated across every scope is shown once. -_RELAYED_NOTICES: set[str] = set() - - -def _relay_cli_notices(text: str) -> None: - """Put the CLI's stderr in the job log, without repeating it. - - The Action runs commit-check once per scope and once per commit in the - pull request, and a notice about the configuration is the same every - time; printed on each run it would bury the findings. - """ - for line in text.splitlines(): - line = line.strip() - if line and line not in _RELAYED_NOTICES: - _RELAYED_NOTICES.add(line) - print(f"commit-check: {_log_safe(line)}", file=sys.stderr) - - -def run_check_json( - args: list[str], - input_text: str | None = None, - env: dict[str, str] | None = None, -) -> tuple[int, dict[str, Any] | None, str]: - """Run ``commit-check --format json`` and return (exit code, parsed JSON, raw output). - - The CLI's contract is that stdout holds the JSON and nothing else, while - stderr carries what it has to say to a person: a parent config it could - not fetch, a flag whose every rule the config switched off, a dry run - that softened its own verdict. Those lines are not JSON, so they are - read separately and relayed to the job log rather than handed to the - parser -- merged into stdout they turned a passing run into an - unparsable one, which ScopeResult reports as a failure. - - The parsed JSON is ``None`` when the CLI did not produce valid JSON; the - raw output is kept so callers can fall back to showing it as text, and - in that case it carries both streams so nothing the CLI said is lost. - """ - command = ["commit-check", "--format", "json", *CONFIG_ARGS] + args - result = subprocess.run( - command, - input=input_text, - capture_output=True, - text=True, - encoding="utf-8", - check=False, - env={**os.environ, **env} if env else None, - ) - out = result.stdout or "" - err = result.stderr or "" - _relay_cli_notices(err) - try: - return result.returncode, json.loads(out), out - except json.JSONDecodeError: - # Whatever went wrong, the operator needs everything the CLI said, - # so stderr joins stdout here -- and only here, where there is no - # JSON left to protect. It is often the whole story: a config the - # CLI refused leaves stdout empty and prints "Error: ..." on stderr, - # and dropping it would leave an empty raw_text that reads as a pass. - if not err.strip(): - return result.returncode, None, out - parts = [part for part in (out.strip(), err.strip()) if part] - return result.returncode, None, "\n".join(parts) - - -def check_scope( - label: str, - args: list[str], - input_text: str | None = None, - sha: str = "", - env: dict[str, str] | None = None, -) -> ScopeResult: - """Run commit-check for one scope and wrap the outcome in a ScopeResult. - - ``sha`` names the commit a message scope checked; it rides along on both - outcomes so an unparsable CLI response still says which commit it was. - """ - _rc, data, raw = run_check_json(args, input_text=input_text, env=env) - if isinstance(data, dict): - tools = data.get("ai_tools") - return ScopeResult( - label=label, - checks=data.get("checks", []), - sha=sha, - ai_tools=[str(t) for t in tools] if isinstance(tools, list) else [], - text=input_text or "", - ) - return ScopeResult(label=label, raw_text=raw, sha=sha) - - -def run_pr_message_checks(pr_commits: list[Commit]) -> list[ScopeResult]: - """Check each PR commit individually via commit-check --message. - - The raw message is piped in, so every commit is read the same way - whether the clone holds it or only the API listed it. Its own author - goes with it as git's author variables, which is where the CLI reads the - author of a piped message: the AI author rule (CC017) and - ``ignore_authors`` then judge that commit's author, not whoever HEAD or - the runner's git config names. - """ - results: list[ScopeResult] = [] - total = len(pr_commits) - for index, (sha, msg) in enumerate(pr_commits, start=1): - label = f"Commit {index}/{total}" - author = API_AUTHORS.get(sha) or (_local_author(sha) if sha else None) - env = None - if author: - names = ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL") - env = {key: value for key, value in zip(names, author) if value} or None - if msg.strip(): - scope = check_scope(label, ["--message"], input_text=msg, sha=sha, env=env) - else: - scope = check_empty_message(label, sha, env) - results.append(keep_ai_rules(scope)) - return results - - -def run_pr_author_checks( - flags: list[str], pr_commits: list[Commit] -) -> list[ScopeResult]: - """Run the author checks on every author of the pull request's commits. - - Checking only the branch tip let an earlier commit by another author, - say a GitHub noreply address that ``author_email_pattern`` forbids, go - through. Each distinct author is checked once, on the newest commit - that carries it, so a one-person pull request still reports one scope - per check. A commit the clone lacks is fetched without its history. - - Returns ``[]`` when no author can be read, or a commit cannot be had - even by fetching it, so the caller falls back to the branch tip as before. - """ - newest: dict[tuple[str, str], str] = {} - for sha, _msg in pr_commits: - author = API_AUTHORS.get(sha) or (_local_author(sha) if sha else None) - if author: - newest.pop(author, None) - newest[author] = sha - revs = [sha for sha in newest.values() if _rev_resolves(sha) or _fetch_commit(sha)] - if len(revs) != len(newest): - return [] - authors = {sha: author for author, sha in newest.items()} - scopes: list[ScopeResult] = [] - for flag in flags: - for sha in revs: - scope = check_scope(CHECK_LABELS[flag], [flag, "--rev", sha], sha=sha) - name, email = authors[sha] - scope.subject = name if flag == "--author-name" else email - scopes.append(scope) - return scopes - - -def _shallow_boundary() -> set[str]: - """The commits a shallow clone holds without their parents. - - Git lists them, one hash per line, in the repository's ``shallow`` file; - a complete clone has none. Such a commit looks like a root commit, so a - diff of it names every file in the repository as changed. - """ - try: - located = subprocess.run( - ["git", "rev-parse", "--git-path", "shallow"], - capture_output=True, - encoding="utf-8", - check=False, - ) - if located.returncode != 0: - return set() - with open(located.stdout.strip(), encoding="utf-8") as f: - return set(f.read().split()) - except OSError: - return set() - - -def run_files_checks(shas: list[str]) -> list[ScopeResult]: - """Check the files each commit changes, via ``commit-check --files --rev``. - - One scope per commit, so a finding names the commit that has to change: - a file added in one commit and removed in the next is still in the - history. A commit is only checked when the checkout holds it together - with its parent, since the files it changes are a diff against that - parent. The others are reported as skipped, never guessed at. - - With no rule set in ``[files]`` the CLI runs none, for any commit, and - one skipped scope says so in place of a row of empty passes. - """ - boundary = _shallow_boundary() - readable = { - sha for sha in shas if sha and sha not in boundary and _rev_resolves(sha) - } - if not readable: - # Whether a rule is set at all, asked of HEAD: only the list of - # checks is read, never a verdict on HEAD itself. - probe = check_scope(FILES_LABEL, ["--files"]) - if not (probe.checks or probe.raw_text): - return [skipped_files_scope(FILES_UNCONFIGURED)] - warn_shallow_checkout( - "The checkout holds no commit to check together with its parent", - "the files check was skipped", - ) - return [skipped_files_scope(FILES_NOT_IN_CLONE)] - - results: list[ScopeResult] = [] - for sha in shas: - if sha not in readable: - results.append(skipped_files_scope(FILES_NOT_IN_CLONE, sha)) - continue - scope = check_scope(FILES_LABEL, ["--files", "--rev", sha], sha=sha) - if not (scope.checks or scope.raw_text): - return [skipped_files_scope(FILES_UNCONFIGURED)] - if scope.status == "skip" and not scope.skip_reason: - # The file rules skip a commit that only deletes, or merges - # without bringing a file along, and do not say why. - for check in scope.checks: - check["reason"] = FILES_NOTHING_CHANGED - results.append(scope) - missing = sum(1 for sha in shas if sha not in readable) - if missing: - warn_shallow_checkout( - f"{missing} of {len(shas)} commits are not in the checkout " - "together with their parent", - "their files were not checked", - ) - return results - - -def run_pr_files_checks(pr_commits: list[Commit]) -> list[ScopeResult]: - """Check the files of every commit of the pull request.""" - if not pr_commits: - warn_shallow_checkout( - "Could not list the pull request's commits", - "the files check was skipped", - ) - return [skipped_files_scope(FILES_UNLISTED)] - return run_files_checks([sha for sha, _msg in pr_commits]) - - -def check_empty_message( - label: str, sha: str, env: dict[str, str] | None -) -> ScopeResult: - """Check a commit whose message is empty, from an empty file. - - Piped, an empty message reads to the CLI as no input at all, and it - checks HEAD in its place: the merge commit, which passes. A file names - the message, so the empty one is judged (``allow_empty_commits``). - """ - fd, path = tempfile.mkstemp(prefix="commit-msg-", dir=os.getenv("RUNNER_TEMP")) - os.close(fd) - try: - return check_scope(label, ["--message", path], sha=sha, env=env) - finally: - os.unlink(path) - - -def run_other_checks(args: list[str], rev: str | None = None) -> list[ScopeResult]: - """Run each non-message check (branch, author) once, as its own scope. - - ``rev`` goes to the author checks only: it names the commit whose - recorded author is validated (commit-check >= 2.16.0), which in a PR is - the branch tip rather than GitHub's merge commit. The branch check has - no commit to point at, so it never takes it. - """ - results: list[ScopeResult] = [] - for flag in args: - label = CHECK_LABELS.get(flag) - if label: - cli_args = [flag] - if rev and flag in AUTHOR_FLAGS: - cli_args += ["--rev", rev] - results.append(check_scope(label, cli_args)) - return results - - -def build_check_args() -> list[str]: - """Map enabled validation switches to commit-check CLI arguments.""" - flags = [ - ("--message", MESSAGE_ENABLED or MESSAGE_AI_ATTRIBUTION_ENABLED), - ("--branch", BRANCH_ENABLED), - ("--author-name", AUTHOR_NAME_ENABLED), - ("--author-email", AUTHOR_EMAIL_ENABLED), - ] - return [flag for flag, enabled in flags if enabled] - - -def run_commit_check() -> tuple[int, list[ScopeResult]]: - """Runs all enabled checks and returns the overall exit code and results. - - Checks are evaluated in order: - 1. PR title (when ``pr-title: true`` and in a PR event) - 2. PR description, AI rules only (when ``pr-body-ai-attribution: true`` and in a PR - event; with only ``ai-label`` set it is read for the label, and no - scope is reported) - 3. Individual PR commit messages (when ``message: true`` and in a PR event; - AI rules only with ``message-ai-attribution: true``) - 4. The files each PR commit changes (when ``files: true``; outside a PR, - the files of the HEAD commit) - 5. Author checks on every PR commit's author, then the remaining checks - (branch; outside a PR, the HEAD commit and its author) - - Outside of a PR event all enabled checks are handed to the CLI at once. - """ - args = build_check_args() - results: list[ScopeResult] = [] - - # ---- 1. PR title check ------------------------------------------------ - if PR_TITLE_ENABLED and is_pr_event(): - pr_title = get_pr_title() - if pr_title: - # --pr-title runs the --message rules a one-line title can meet: - # none needing a body (CC011), a sign-off (CC012) or an author - # (CC017), and its advice does not say to re-commit. - results.append(check_scope("PR title", ["--pr-title"], input_text=pr_title)) - - # ---- 2. PR description ------------------------------------------------ - if (PR_BODY_AI_ATTRIBUTION_ENABLED or ai_label_name()) and is_pr_event(): - pr_body = get_pr_body() - if PR_BODY_AI_ATTRIBUTION_ENABLED: - # An empty description is checked too: it has no AI declaration, - # which CC501 fails when [pull_request] ai_declaration_checkboxes - # names the boxes. The attribution rules pass empty text. - scope = check_scope( - "PR description", ["--ai-attribution-only"], input_text=pr_body or "" - ) - name_the_line_changes(scope, pr_body or "") - results.append(skip_when_no_ai_rule_ran(scope)) - elif pr_body: - scope = check_scope( - "PR description", ["--ai-attribution-only"], input_text=pr_body - ) - PR_BODY_AI_TOOLS[:] = scope.ai_tools - - # ---- 3. Commit message checks ----------------------------------------- - pr_commits: list[Commit] | None = None - if MESSAGE_ENABLED or MESSAGE_AI_ATTRIBUTION_ENABLED: - pr_commits = get_pr_commit_messages() - if pr_commits: - # In PR context: check each commit individually to avoid - # only validating the synthetic merge commit at HEAD. - results.extend(run_pr_message_checks(pr_commits)) - args = [a for a in args if a != "--message"] - elif is_pr_event(): - # Falling through to HEAD validates the synthetic merge commit, - # "Merge X into Y", which passes CC001 by default: a shallow - # clone used to turn every pull request green without a word. - warn_shallow_checkout( - "Could not list the pull request's commits", "only HEAD was checked" - ) - - # Outside a PR, check the HEAD commit message directly. - if "--message" in args: - results.append( - keep_ai_rules(check_scope("Commit message", ["--message"], sha=head_sha())) - ) - args = [a for a in args if a != "--message"] - - # ---- 4. Files of each commit ------------------------------------------ - if FILES_ENABLED: - if is_pr_event(): - if pr_commits is None: - pr_commits = get_pr_commit_messages() - results.extend(run_pr_files_checks(pr_commits)) - else: - results.extend(run_files_checks([head_sha()])) - - # ---- 5. Remaining checks (branch, author, etc.) ----------------------- - rev = None - author_flags = [flag for flag in args if flag in AUTHOR_FLAGS] - if is_pr_event() and author_flags: - if pr_commits is None: - pr_commits = get_pr_commit_messages() - author_scopes = run_pr_author_checks(author_flags, pr_commits) - if author_scopes: - results.extend(author_scopes) - args = [a for a in args if a not in AUTHOR_FLAGS] - if is_pr_event() and any(flag in AUTHOR_FLAGS for flag in args): - rev = pr_head_rev() - if rev is None: - # HEAD's author is GitHub's merge commit on a pull_request - # checkout and the base branch on pull_request_target: checking - # it would grade the wrong person either way. Say so, and skip. - warn_shallow_checkout( - "Could not resolve the pull request's head commit for the " - "author checks", - "they were skipped", - ) - for flag in args: - if flag in AUTHOR_FLAGS: - results.append(skipped_author_scope(flag)) - args = [a for a in args if a not in AUTHOR_FLAGS] - results.extend(run_other_checks(args, rev=rev)) - - exit_code = exit_code_for(results) - return exit_code, results - - -# --------------------------------------------------------------------------- -# Rendering -# --------------------------------------------------------------------------- - -#: Home of the status marks the report shows: static PNGs in the organization's -#: ``.github`` repository, so nothing has to be running for them to load. -STATUS_MARK_URL = ( - "https://raw.githubusercontent.com/commit-check/.github/main/branding/status" -) -SITE_URL = "https://commit-check.com" -#: Where a reader sets the same rules up locally, so the next push passes. -LOCAL_HOOK_URL = "https://commit-check.com/guides/integrations/#as-a-pre-commit-hook" - -#: One glyph per status. The step log prints it, and the report's images carry -#: it as their alt text, so a report whose images cannot load still reads. -STATUS_GLYPHS = {"pass": "✔", "fail": "✖", "warn": "⚠", "skip": "⊘"} -#: File name of each status mark, and the word the heading uses for it. -STATUS_WORDS = { - "pass": "passed", - "fail": "failed", - "warn": "warned", - "skip": "skipped", -} -#: Step log colours. GitHub renders these; bright black is its grey. -ANSI = {"pass": "\033[32m", "fail": "\033[31m", "warn": "\033[33m", "skip": "\033[90m"} -ANSI_BOLD, ANSI_GREY, ANSI_RESET = "\033[1m", "\033[90m", "\033[0m" - -#: Failing items the report shows before folding the rest away. A hunk is two -#: or three lines, and folding one or two leftovers would cost a click and -#: save nothing, so up to ``MAX_HUNKS + HUNK_SLACK`` are shown unfolded. -MAX_HUNKS = 5 -HUNK_SLACK = 2 - - -def _rule_label(check: dict[str, str]) -> str: - """Human-readable label for a check: ``CC001 message`` (kebab-case).""" - rule_id = check.get("rule_id", "") - name = check.get("check", "").replace("_", "-") - return f"{rule_id} {name}" if rule_id else name - - -def _rule_ref(check: dict[str, str]) -> str: - """Short Markdown link for a rule: ``[CC001](docs_url)``.""" - label = check.get("rule_id") or check.get("check", "").replace("_", "-") - docs_url = check.get("docs_url", "") - return f"[{label}]({docs_url})" if docs_url else label - - -def _names_a_commit(scope: ScopeResult) -> bool: - """Whether the scope is one commit's: its message, or the files it changes.""" - return bool(scope.sha) and ( - scope.label.startswith("Commit") or scope.label == FILES_LABEL - ) - - -def _found(check: dict[str, str]) -> str: - """First line of what a rule reports it found.""" - value = str(check.get("value") or "").strip() - return value.splitlines()[0].strip() if value else "" - - -def _scope_group(label: str) -> str: - """Group name for a scope label, used to fold the step log output.""" - if label in ("PR title", "PR description"): - return "Pull request" - if label.startswith("Commit"): - return "Commits" - if label.startswith("Author"): - return "Author" - return label - - -def _grouped(results: list[ScopeResult]) -> list[tuple[str, list[ScopeResult]]]: - """Split results into ordered groups for step log folding.""" - groups: list[tuple[str, list[ScopeResult]]] = [] - for scope in results: - group_name = _scope_group(scope.label) - if groups and groups[-1][0] == group_name: - groups[-1][1].append(scope) - else: - groups.append((group_name, [scope])) - return groups - - -def _plural(count: int, word: str) -> str: - """``1 warning``, ``2 warnings``.""" - return f"{count} {word}{'' if count == 1 else 's'}" - - -def _group_status(scopes: list[ScopeResult]) -> tuple[str, str]: - """A group's worst outcome and the few words that say it: ``3 of 4 failed``. - - The same words head the group in the step log and its line in the - report, so a folded log and a skimmed comment both say where it went - wrong. A skipped scope never counts as passed, and a group is ``skip`` - only when nothing in it ran. - """ - total = len(scopes) - failed = sum(1 for scope in scopes if scope.status == "fail") - skipped = sum(1 for scope in scopes if scope.status == "skip") - warned = sum(1 for scope in scopes if scope.warnings) - if failed: - return "fail", f"{failed} of {total} failed" if total > 1 else "failed" - if skipped == total: - return "skip", "skipped" - if warned: - return "warn", _plural(warned, "warning") - text = f"{total - skipped} passed" if total > 1 else "passed" - return "pass", f"{text}, {skipped} skipped" if skipped else text - - -def _first_value(scope: ScopeResult) -> str: - """First line of what the scope checked: a subject, a title, a branch. - - The text the action piped in when it has it, then the whole message the - ``message`` rule reports, then whichever rule names a value first. A PR - description has no such line: its first line does not identify it. An - AI rule's value is the tool or the author it found, never the text, so - it never stands in for a commit's subject. - """ - if scope.label == "PR description": - return "" - if scope.label == FILES_LABEL: - # Each file rule names its own finding, a path and what is wrong - # with it. The first finding stands for the scope; with none, the - # count of files a passing rule reports. - checks = [*scope.failures, *scope.warnings] or scope.checks - return next((_found(check) for check in checks if _found(check)), "") - values = [scope.text, _message_value(scope)] - values.extend( - str(check.get("value") or "") - for check in scope.checks - if check.get("rule_id") not in AI_RULE_IDS - ) - values.append(scope.subject) - for value in values: - if value.strip(): - return value.strip().splitlines()[0].strip() - return "" - - -def _scope_value(scope: ScopeResult, max_len: int = 80) -> str: - """``_first_value`` capped for a row of the listing. - - The value reads naturally next to the scope's label, and the cap keeps a - passing row on one line of the fenced block. 80 holds a subject written - to the usual 72-column limit; a longer one is cut at a word, with an - ellipsis, rather than mid-word. - """ - if scope.label == "PR description" and scope.status == "pass": - # Its first line does not identify it; what was found does. - if scope.ai_tools: - return f"AI attribution: {', '.join(scope.ai_tools)}" - return "no AI attribution" - value = _first_value(scope) - if len(value) <= max_len: - return value - cut = value[: max_len - 1] - space = cut.rfind(" ") - if space > max_len // 2: - cut = cut[:space] - return cut.rstrip() + "…" - - -def _line_edits( - scope: ScopeResult, check: dict[str, str] -) -> tuple[list[str], list[str]]: - """The lines a rule's fix removes and adds, as ``(removed, added)``. - - The CLI's ``fix`` is corrected text, but of what differs by rule: the - whole message for most, the subject alone for the subject rules. So the - fix is compared with the rule's value when that is one line of the text - and the fix is one line too, and with the whole text otherwise. An AI - rule's value is the tool or the line it found, never the text it fixes. - - Both lists are empty when the rule offers no fix, or nothing is known to - compare it with; the caller then falls back to the rule's advice. - """ - recorded = scope.edits.get(_rule_key(check)) - if recorded: - return recorded - fix = (check.get("fix") or "").strip() - if not fix: - return [], [] - value = str(check.get("value") or "").strip() - text = (scope.text or _message_value(scope)).strip() - one_line = "\n" not in value and "\n" not in fix - if check.get("rule_id") in AI_RULE_IDS: - original = text - elif one_line and value in text.splitlines(): - original = value - else: - original = text or value - if not original: - return [], [] - return lines_removed(original, fix), lines_removed(fix, original) - - -def _plain_error(check: dict[str, str]) -> str: - """First line of the rule's error, without a trailing ``See ``.""" - error = (check.get("error") or "").splitlines() - fallback = "check warning" if check.get("status") == "warn" else "check failed" - first = error[0] if error else fallback - return re.sub(r"\s*See https?://\S+\s*$", "", first) - - -def _advice(check: dict[str, str]) -> str: - """What to do about a finding that has no ready-made fix, in one line. - - The CLI's suggestion, without the tails that only matter once the reader - opens the rule (the list of allowed types, the config key that would - exempt the branch): those are in the listing and behind the rule link. - """ - suggest = (check.get("suggest") or "").splitlines() - if not suggest: - return _plain_error(check) - advice = re.sub(r"^In the description, ", "", suggest[0]) - return re.sub( - r"(, where is one of: .*|, or add the branch to .*)$", "", advice - ) - - -def _quoted(lines: list[str]) -> str: - """``"first"; "second"``.""" - return "; ".join(f'"{line}"' for line in lines) - - -def _instruction(scope: ScopeResult, check: dict[str, str]) -> str: - """One finding as an instruction: ``change "a" to "b"``, ``remove "x"``.""" - removed, added = _line_edits(scope, check) - if len(removed) == 1 and len(added) == 1: - return f'change "{removed[0]}" to "{added[0]}"' - parts = [] - if removed: - parts.append(f"remove {_quoted(removed)}") - if added: - parts.append(f"add {_quoted(added)}") - return ", and ".join(parts) or _advice(check) - - -def _target( - scope: ScopeResult, instructions: list[str], label: str, value: str | None = None -) -> str: - """Name what an instruction is about: ``Commit 2/3 (5584f46) "bad msg"``. - - The quoted value is left out when an instruction already quotes it. It - is the scope's own unless ``value`` names another: a files scope holds - one finding per rule, each about a path of its own. - """ - if value is None: - value = _first_value(scope) - if value and not any(f'"{value}"' in text for text in instructions): - return f'{label} "{value}"' - return label - - -def _findings(scope: ScopeResult, status: str) -> list[dict[str, str]]: - """A scope's failures or warnings.""" - return scope.failures if status == "fail" else scope.warnings - - -def _finding_lines(check: dict[str, str]) -> list[str]: - """The detail a reader needs to act on one finding, one item per line. - - ``value:`` (what was checked), the error, ``Suggest:`` and ``Fix:`` — - each only when the CLI filled it in. - - ``Fix:`` is the corrected text itself, ready to paste. When a rule has a - fix but no bespoke advice the CLI sets ``suggest`` to ``Use ""``, - so printing both would say the same thing twice in a row; in exactly - that case only ``Fix:`` is shown. A multi-line fix (a signed-off body) - takes one row per line so the trailer lands where it would in the - message; a multi-line value (a whole commit message on a failing rule) - or suggestion is split the same way, so every line of user text sits - inside the tree rather than at column 0. - """ - lines: list[str] = [] - if check.get("value"): - first, *rest = str(check["value"]).splitlines() - lines.append(f"value: {first}") - lines.extend(rest) - lines.extend(check.get("error", "").splitlines()) - fix = check.get("fix", "") - suggest = check.get("suggest", "") - if suggest and suggest != f'Use "{fix}"': - first, *rest = suggest.splitlines() - lines.append(f"Suggest: {first}") - lines.extend(rest) - if fix: - first, *rest = fix.splitlines() - lines.append(f"Fix: {first}") - lines.extend(rest) - return lines - - -def _render_findings(checks: list[dict[str, str]], include_docs: bool) -> list[str]: - """Render the indented detail lines for a list of check entries. - - Shared by the failure and warning branches of ``_render_scopes`` — the - same rule label / value / error / suggestion / fix / docs layout, - whichever list it is called with. - """ - lines: list[str] = [] - for check in checks: - # A scope can hold a failure and a warning at once (see below), so a - # warning says so on its own line rather than borrow the row's mark. - kind = " (warning)" if check.get("status") == "warn" else "" - lines.append(f" {_rule_label(check)}{kind}") - lines.extend(f" {line}" for line in _finding_lines(check)) - if include_docs and check.get("docs_url"): - lines.append(f" Docs: {check['docs_url']}") - return lines - - -def _row_label(scope: ScopeResult) -> str: - """A scope's name within its group: the short hash, ``title``, ``email``. - - The group header already says "Commits" or "Author", so the row only - needs what tells it apart from its neighbours. - """ - if _names_a_commit(scope): - return scope.sha[:7] - _group, _, name = scope.label.partition(" ") - return name or scope.label.lower() - - -def _row(mark: str, scope: ScopeResult, value: str) -> str: - """One aligned row of the listing: mark, label, value.""" - return f" {mark} {_row_label(scope):<12} {value}".rstrip() - - -def _one_skip_reason(results: list[ScopeResult]) -> bool: - """Whether every skipped scope was skipped for the same, named reason. - - Then the one sentence under the verdict (``_skip_reasons``) explains - them all, and each skipped row can show what it skipped instead of - repeating why. - """ - reasons = {s.skip_reason for s in results if s.status == "skip"} - return len(reasons) == 1 and "" not in reasons - - -def _render_scopes( - scopes: list[ScopeResult], include_docs: bool, reason_said: bool = False -) -> list[str]: - """Render the indented listing for one group of scopes, without its header. - - Shared by both output surfaces so they cannot drift: the step log and the - Markdown listing are the same rows, and the only difference is the docs - link, which the Markdown report already carries under the diff. - - A failing or warned scope shows its value in full rather than capped. It - is the one value the reader has to act on, and the cap can cut off the - part that explains it. - - ``reason_said`` is for a report whose skipped scopes share one reason, - stated once under the verdict: a skipped row then shows what it skipped - (a commit's subject, an author) rather than that reason again. - """ - lines: list[str] = [] - for scope in scopes: - if scope.status == "skip": - # Deliberately not a ✔. Nothing was validated here, and a tick - # claiming otherwise is what made a bypassed policy look enforced. - value = _scope_value(scope) if reason_said else "" - if value: - lines.append(_row("⊘", scope, value)) - continue - reason = scope.skip_reason - lines.append(_row("⊘", scope, f"skipped{f': {reason}' if reason else ''}")) - continue - if scope.status == "pass": - lines.append(_row("✔", scope, _scope_value(scope))) - continue - if scope.raw_text and not scope.checks: - # Defensive fallback: commit-check produced unexpected output. - lines.append(_row("✖", scope, "")) - lines.extend(f" {ln}" for ln in scope.raw_text.strip().splitlines()) - continue - # A scope's status names its worst outcome (fail beats warn), but the - # two are not exclusive: CC2xx covers both branch and merge_base, so - # one can fail while the other only warns. The row carries the worst - # mark, and both lists are rendered under it — a warning on an - # otherwise-failing scope is still a finding to fix. - lines.append(_row(STATUS_GLYPHS[scope.status], scope, _first_value(scope))) - lines.extend(_render_findings(scope.failures, include_docs)) - lines.extend(_render_findings(scope.warnings, include_docs)) - return lines - - -def _render_tree(results: list[ScopeResult], include_docs: bool) -> list[str]: - """Render the full grouped listing: a header line per group, then its scopes.""" - lines: list[str] = [] - reason_said = _one_skip_reason(results) - for group_name, scopes in _grouped(results): - lines.append(group_name) - lines.extend(_render_scopes(scopes, include_docs, reason_said)) - return lines - - -def _annotation_escape(text: str) -> str: - """Escape text for a workflow command payload. - - A newline would end the command and leave the rest of the message as a - stray log line, and a bare ``%`` can be read as the start of an escape. - """ - return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") - - -#: C0 and C1 control characters, and DEL, except the newline and tab that a -#: multi-line commit message legitimately carries. -_CONTROL_CHARS = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]") - - -def _log_safe(text: str) -> str: - """Make commit-controlled text inert before it is printed to the step log. - - The tree prints values from the CLI's JSON, and those are whoever wrote - the commit, branch or pull request title: a multi-line value (a whole - message on a failing rule, a sign-off fix) prints each further line on a - line of its own. The runner reads any log line beginning with ``::`` as a - workflow command, after skipping leading whitespace, so indenting it is - not enough; and it reads the older ``##[command]`` form anywhere in a - line. Left as they are, such lines can forge annotations or mask log - text. So such a line gets a backslash before its ``::``, ``##[`` is broken - up, and control characters are shown as ``\\xNN`` escapes. This is the - CLI's own ``printable()`` (commit-check#620), which covers its text - output but not the JSON this action renders itself. - - Only the step log needs it: the Markdown report and the annotation - payloads are not read as commands. It runs before the log's own colours - are added, so an escape sequence in the log is always the action's. - """ - if text.isprintable() and "::" not in text and "##[" not in text: - return text # nothing to escape: the common case - text = _CONTROL_CHARS.sub(lambda m: f"\\x{ord(m.group()):02x}", text) - text = text.replace("##[", "#\\#[") - return "\n".join( - line.replace("::", "\\::", 1) if line.lstrip().startswith("::") else line - for line in text.split("\n") - ) - - -#: A row of the listing: two spaces, the status glyph, a space. -_ROW_MARK = re.compile(r"^ ([✔✖⚠⊘]) ") -_GLYPH_STATUS = {glyph: status for status, glyph in STATUS_GLYPHS.items()} - - -def _coloured(line: str) -> str: - """Colour a row's status glyph for the step log. - - Only rows start with a glyph at column two; the detail under a finding - sits deeper, so user text can never be taken for a row. - """ - match = _ROW_MARK.match(line) - if not match: - return line - glyph = match.group(1) - return f" {ANSI[_GLYPH_STATUS[glyph]]}{glyph}{ANSI_RESET} {line[4:]}" - - -def _annotation_body(scope: ScopeResult, check: dict[str, str]) -> str: - """The message of one finding's annotation, before escaping. - - The run page shows only the first line of an annotation, so that line - says where and what to change: ``Commit 2/3 (5584f46): change "bad msg" - to "fix: bad msg"``. The rule's own sentence follows on the second line - for whoever expands it. - """ - instruction = _instruction(scope, check) - found = _found(check) if scope.label == FILES_LABEL else None - target = _target(scope, [instruction], scope.display_label, found) - headline = f"{target}: {instruction}" - error = _plain_error(check) - return headline if error == instruction else f"{headline}\n{error}" - - -def render_step_log(results: list[ScopeResult]) -> None: - """Print results to the step log, then emit one annotation per finding. - - Each group is folded under a title that carries its own result - (``✖ Commits: 3 of 4 failed``): GitHub shows a group collapsed, and a - bare "Commits" said nothing about where to look. - - The tree and the annotations are separated deliberately. An ``::error`` or - ``::warning`` command renders as a line of its own wherever it is printed, - so emitting one inside the indented listing broke the tree apart, and its - ``title=`` — which is what carries the rule ID — is only shown in the - annotations UI, never inline. Printing the listing first and the - annotations after all the groups keeps the log readable and still - surfaces findings on the run page, where the annotation's first line is - all a reader sees (``_annotation_body``). - - A failure becomes an ``::error``, a warning a ``::warning`` — GitHub - renders the two differently, and only the errors count toward the - friendly one-line verdict claiming nothing failed. - - Under ``dry-run`` a failure is still reported, but as a ``::warning``: - an ``::error`` annotation on a step that then exits 0 reads as a - contradiction, and the run's error count would claim a failure the job - did not have. The verdict line says the same thing in words. - """ - # The tree is grouped, so it is printed group by group rather than in one - # block: ::group:: and ::endgroup:: have to bracket each section's lines. - reason_said = _one_skip_reason(results) - for group_name, scopes in _grouped(results): - status, text = _group_status(scopes) - print(f"::group::{STATUS_GLYPHS[status]} {group_name}: {text}") - for line in _render_scopes(scopes, include_docs=True, reason_said=reason_said): - print(_coloured(_log_safe(line))) - print("::endgroup::") - - errors: list[tuple[str, str]] = [] - warnings: list[tuple[str, str]] = [] - for scope in results: - if scope.status in ("pass", "skip"): - continue - if scope.raw_text and not scope.checks: - errors.append( - (f"Commit Check: {scope.display_label}", "output could not be parsed") - ) - continue - for check in scope.failures: - errors.append((_rule_label(check), _annotation_body(scope, check))) - for check in scope.warnings: - warnings.append((_rule_label(check), _annotation_body(scope, check))) - - level = "warning" if DRY_RUN_ENABLED else "error" - for title, message in errors: - print( - f"::{level} title={_annotation_escape(title)}" - f"::{_annotation_escape(message)}" - ) - for title, message in warnings: - print( - f"::warning title={_annotation_escape(title)}" - f"::{_annotation_escape(message)}" - ) - - # The verdict is a plain line, never an ::error: the findings above are - # already one annotation each, and a second, untitled ::error for the - # total inflated the run's error count and told the reader nothing new. - if errors: - failed, total = _check_counts(results) - if DRY_RUN_ENABLED: - print( - f"Commit Check (dry-run): {failed} of {total} checks failed; " - "not failing the job" - ) - else: - verdict = f"✖ Commit Check: {failed} of {total} checks failed" - warned = _warn_count(results) - if warned: - verdict += f", {_plural(warned, 'warning')}" - print(f"{ANSI['fail']}{ANSI_BOLD}{verdict}{ANSI_RESET}") - where = "the job summary" if _summary_written() else "the findings above" - print( - f"{ANSI_GREY}How to fix: see {where}. " - f"Check before you push: {LOCAL_HOOK_URL}{ANSI_RESET}" - ) - if not errors: - skipped, warned, total = ( - _skip_count(results), - _warn_count(results), - len(results), - ) - if total and skipped == total: - print("⊘ Commit Check: all checks skipped, nothing was validated") - if _skip_reasons(results): - print(_log_safe(_skip_reasons(results))) - elif warned or skipped: - passed = total - skipped - warned - tail = [] - if warned: - tail.append(_plural(warned, "warning")) - if skipped: - tail.append(f"{skipped} skipped") - print( - f"{ANSI['pass']}✔ Commit Check: {passed} of {total} checks " - f"passed, {', '.join(tail)}{ANSI_RESET}" - ) - if _skip_reasons(results): - print(_log_safe(_skip_reasons(results))) - else: - print(f"{ANSI['pass']}✔ Commit Check: all checks passed{ANSI_RESET}") - - -def _summary_written() -> bool: - """Whether this run writes a job summary a log line can point to.""" - return bool(JOB_SUMMARY_ENABLED and GITHUB_STEP_SUMMARY) - - -def _check_counts(results: list[ScopeResult]) -> tuple[int, int]: - """Return ``(failed, total)`` where one check is one thing that was checked. - - A "check" here is a scope — one commit message, the branch, the author name - — not one rule evaluation. Counting rule evaluations produced a number that - grew with the size of the pull request rather than with the strictness of - the policy: sixteen commit messages against six enabled rules reported - "1 of 100 checks failed", where 96 of the 100 were the same six rules run - again per commit. The large denominator also made a real failure look - negligible — one bad commit out of fifteen reads very differently from - 1 of 100. - - This number matches what the reader can count: the ✔/✖ rows of the - listing. Which rules failed is not lost, it is just reported where it - belongs — under the diff and in the listing. - """ - failed = sum(1 for scope in results if scope.status == "fail") - return failed, len(results) - - -def _skip_count(results: list[ScopeResult]) -> int: - """Number of scopes that never ran. - - Reported separately from the pass count so the headline cannot claim - that checks passed when they were skipped. - """ - return sum(1 for scope in results if scope.status == "skip") - - -def _skip_reasons(results: list[ScopeResult]) -> str: - """One sentence naming why checks were skipped, or ``""`` if unknown. - - The verdict is all most readers see, so it stays short: the config - section is dropped ("[commit].ignore_authors" and "[branch].ignore_authors" - both read "ignore_authors"), which folds the usual bot case into one - reason. The per-scope lines in the collapsed block keep the section. - """ - reasons = list( - dict.fromkeys( - re.sub(r"\[\w+\]\.", "", s.skip_reason) for s in results if s.skip_reason - ) - ) - return f"Skipped because {'; '.join(reasons)}." if reasons else "" - - -def _warn_count(results: list[ScopeResult]) -> int: - """Number of scopes that carry at least one warning. - - Counts by ``scope.warnings``, not ``scope.status == "warn"``: a scope - whose overall status is "fail" (CC2xx covers both ``branch`` and - ``merge_base``, so one can fail while the other only warns) still has - warnings to report, and this is the count the verdict uses to decide - whether to show them. - """ - return sum(1 for scope in results if scope.warnings) - - -def _commit_url(sha: str) -> str: - """Link to a commit on the GitHub instance the workflow runs against. - - ``GITHUB_SERVER_URL`` is what makes this right on GitHub Enterprise - Server; without ``GITHUB_REPOSITORY`` there is nothing to link into, so - the caller falls back to plain text rather than guess. - """ - repository = os.getenv("GITHUB_REPOSITORY", "") - if not (sha and repository): - return "" - server = os.getenv("GITHUB_SERVER_URL") or "https://github.com" - return f"{server.rstrip('/')}/{repository}/commit/{sha}" - - -def _longest_backtick_run(lines: list[str]) -> int: - """Length of the longest run of consecutive backticks across ``lines``.""" - return max((len(m) for line in lines for m in re.findall(r"`+", line)), default=0) - - -def _fenced(language: str, body: list[str]) -> list[str]: - """A fenced code block that user text cannot close. - - The body quotes commit subjects, errors and suggestions as they are. A - value with three backticks in it (a `docs:` commit showing a fence) - would close a fixed ``` fence and spill the rest of the report out as - prose, so the fence is one longer than any backtick run inside. - """ - fence = "`" * max(3, _longest_backtick_run(body) + 1) - return [f"{fence}{language}", *body, fence] - - -def _status_mark(status: str, size: int, line: bool = False) -> str: - """The ```` of a status mark: the tile at 24 px, the line mark at 16. - - The tile sits at the top of the heading. A line mark is centred on its - line of text (``absmiddle``): aligned to the top it rode about two pixels - above the words beside it. - """ - name = f"{'line-' if line else ''}{STATUS_WORDS[status]}" - align = "absmiddle" if line else "top" - return ( - f'{STATUS_GLYPHS[status]}' - ) - - -def _group_lines(results: list[ScopeResult]) -> str: - """One line per group, its status mark in front: the overview. - - The lines are joined by ``
`` alone, on one source line. A pull request - comment turns every newline into a line break of its own, so ``
`` - followed by a newline left an empty line between the groups there. - """ - return "
".join( - f"{_status_mark(status, 16, line=True)} {group_name}: {text}" - for group_name, scopes in _grouped(results) - for status, text in [_group_status(scopes)] - ) - - -def _hunk(scope: ScopeResult, status: str) -> list[str]: - """One scope's findings as a diff hunk. - - ``@@ where @@``, then red for what was found and has to go, green for - what to write instead, and a ``#`` comment for advice that has no - literal text to offer. GitHub colours all three in a ``diff`` block, - which is the only colour a comment or a job summary can carry. - """ - if scope.sha and scope.label.startswith("Commit"): - where = scope.sha[:7] - elif scope.sha and scope.label == FILES_LABEL: - where = f"{scope.sha[:7]} files" - else: - where = scope.label - lines = [f"@@ {where} @@"] - if scope.label == FILES_LABEL and scope.checks: - # One finding per rule, each about a path of its own: the path it - # found, then what to do about it. - for check in _findings(scope, status): - if _found(check): - lines.append(f"- {_found(check)}") - lines.append(f"# {_advice(check)}") - return lines - value = _first_value(scope) - removed: list[str] = [] - added: list[str] = [] - advice: list[str] = [] - # Whether a piece of advice is about the value itself: a subject or a - # branch name that has to change. Advice about something else, such as - # an AI tool as the commit's author, leaves the subject as context. - about_value = False - for check in _findings(scope, status): - minus, plus = _line_edits(scope, check) - removed.extend(minus) - added.extend(plus) - if not (minus or plus): - advice.append(_advice(check)) - checked = str(check.get("value") or "").strip() - about_value |= not checked or checked.splitlines()[0].strip() == value - if scope.raw_text and not scope.checks: - advice.append("the output could not be parsed, see the step log") - about_value = True - removed, added, advice = (list(dict.fromkeys(x)) for x in (removed, added, advice)) - if value and value not in removed: - # Advice about the value means it is what was found; a fix that only - # touches other lines, or advice about something else, leaves it as - # context. - lines.append(f"{'-' if about_value else ' '} {value}") - lines.extend(f"- {line}" for line in removed) - lines.extend(f"+ {line}" for line in added) - lines.extend(f"# {line}" for line in advice) - return lines - - -def _diff_block(results: list[ScopeResult], status: str = "fail") -> list[str]: - """The findings of one kind as a ``diff`` block, with their links under it. - - A scope appears when it has an entry of the requested kind — checked via - ``scope.failures`` / ``scope.warnings``, not ``scope.status`` — so a scope - that both failed and warned shows up in both blocks. - - A long list is cut at ``MAX_HUNKS`` and the rest folded away, so twenty - bad commits do not push the rest of the pull request off the screen. A - code block cannot hold links, so the commits shown and the rules that - spoke get one small line of them underneath. - """ - scopes = [ - scope - for scope in results - if _findings(scope, status) - or (status == "fail" and scope.raw_text and not scope.checks) - ] - hunks = [_hunk(scope, status) for scope in scopes] - shown = len(hunks) if len(hunks) <= MAX_HUNKS + HUNK_SLACK else MAX_HUNKS - lines = _fenced("diff", [line for hunk in hunks[:shown] for line in hunk]) - if len(hunks) > shown: - rest = [line for hunk in hunks[shown:] for line in hunk] - lines += ["", "
", f"and {len(hunks) - shown} more"] - lines += ["", *_fenced("diff", rest), "", "
"] - commits = list( - dict.fromkeys( - f"[`{scope.sha[:7]}`]({_commit_url(scope.sha)})" - for scope in scopes[:shown] - if _names_a_commit(scope) and _commit_url(scope.sha) - ) - ) - rules = list( - dict.fromkeys( - _rule_ref(check) for scope in scopes for check in _findings(scope, status) - ) - ) - links = [] - if commits: - links.append(f"Commits: {' '.join(commits)}") - if rules: - links.append(f"Rules: {' · '.join(rules)}") - if links: - lines += ["", f"{'  |  '.join(links)}"] - return lines - - -#: First line of the prompt "How to fix" offers for an AI coding agent. -AGENT_PROMPT = "Fix these Commit Check findings without changing any code:" -#: The same line when a finding is about a file, which then has to change. -AGENT_PROMPT_FILES = ( - "Fix these Commit Check findings, changing only the files they name:" -) -BRANCH_HELP = ( - "**Branch name.** Rename the branch and push it. A pull request cannot " - "change its branch, so open a new one from the renamed branch:" -) -AUTHOR_HELP = ( - "**Author.** Set your git identity (`git config user.name`, " - "`git config user.email`), then `git commit --amend --reset-author` " - "and force-push." -) -FILES_HELP = ( - "**Files.** Amend the commit that changed the file (`git rebase -i`, or " - "`git commit --amend` for the last one), then force-push. A later commit " - "that removes the file leaves it in the history." -) -HOOK_HELP = ( - f"**Next time.** The [pre-commit hook]({LOCAL_HOOK_URL}) runs the same " - "rules before you push." -) - - -def _agent_prompt(failing: list[ScopeResult]) -> list[str]: - """A prompt to paste into an AI coding agent, one line per failing scope. - - A files scope gets a line per finding: each is about a path of its own. - """ - about_files = any(scope.label == FILES_LABEL for scope in failing) - lines = [AGENT_PROMPT_FILES if about_files else AGENT_PROMPT] - for scope in failing: - if scope.label == FILES_LABEL: - label = f"Files of commit {scope.sha[:7]}" if scope.sha else scope.label - for check in scope.failures: - todo = [_advice(check)] - lines.append( - f"- {_target(scope, todo, label, _found(check))}: {todo[0]}" - ) - continue - todo = list(dict.fromkeys(_instruction(scope, c) for c in scope.failures)) - is_commit = bool(scope.sha) and scope.label.startswith("Commit") - label = f"Commit {scope.sha[:7]}" if is_commit else scope.label - lines.append(f"- {_target(scope, todo, label)}: {'; '.join(todo)}") - return lines - - -def _is_last_commit(scope: ScopeResult) -> bool: - """Whether the scope is the newest commit: ``Commit 3/3`` or the HEAD one.""" - position = re.fullmatch(r"Commit (\d+)/(\d+)", scope.label) - return not position or position.group(1) == position.group(2) - - -def _reword_commands(commits: list[ScopeResult]) -> list[str]: - """The git commands that reword the failing commits and push the result.""" - if len(commits) == 1 and _is_last_commit(commits[0]): - reword = "git commit --amend" - else: - first = commits[0].sha[:7] or "" - note = '# change "pick" to "reword" on the commits above' - reword = f"git rebase -i {first}~1 {note}" - return [reword, "git push --force-with-lease"] - - -def _how_to_fix(results: list[ScopeResult]) -> list[str]: - """The folded "How to fix" section: only what this run's failures need. - - A prompt for whoever lets an AI agent do it, then the git commands for - doing it by hand. Most people who fail a message check have never - reworded a pushed commit, and the commands are the same every time. - """ - failing = [scope for scope in results if scope.failures] - if not failing: - return [] - commits = [scope for scope in failing if scope.label.startswith("Commit")] - labels = {scope.label for scope in failing} - # One list of lines per paragraph; a blank line goes between them. - parts = [ - ["**With an AI coding agent.** Paste this prompt:"], - _fenced("text", _agent_prompt(failing)), - ] - if commits: - many = "it" if len(commits) == 1 else "them" - parts.append([f"**Commit messages.** Reword {many}, then force-push:"]) - parts.append(_fenced("bash", _reword_commands(commits))) - if FILES_LABEL in labels: - parts.append([FILES_HELP]) - if any(label.startswith("Author") for label in labels): - parts.append([AUTHOR_HELP]) - if "Branch" in labels: - # The CLI's own corrected name when it has one, a pattern otherwise. - fixes = ( - c.get("fix") for s in failing if s.label == "Branch" for c in s.failures - ) - name = next((fix for fix in fixes if fix), "/") - rename = [f"git branch -m {name}", "git push -u origin HEAD"] - parts.extend([[BRANCH_HELP], _fenced("bash", rename)]) - fields = [word for word in ("title", "description") if f"PR {word}" in labels] - if fields: - many = "it" if len(fields) == 1 else "them" - what = " and ".join(fields) - parts.append( - [f"**Pull request {what}.** Edit {many} on the pull request page."] - ) - parts.append([HOOK_HELP]) - lines = ["
", "How to fix"] - for part in parts: - lines.extend(["", *part]) - return [*lines, "", "
"] - - -def _all_checks(results: list[ScopeResult]) -> list[str]: - """The folded listing of every scope, passed ones included. - - The same rows the step log prints (group name, one ✔/✖ row per scope with - the checked value), with the rule's reason, suggestion and fix under each - finding, so one expand answers both "what was checked" and "what failed - and why". The same block is used whether or not anything failed. - """ - _failed, total = _check_counts(results) - unit = "check" if total == 1 else "checks" - label = f"All {total} {unit}" if total else "Details" - body = _fenced("text", _render_tree(results, include_docs=False)) - return ["
", f"{label}", "", *body, "", "
"] - - -# --------------------------------------------------------------------------- -# Output specification -# -# The Markdown report shared by the job summary and the PR comment renders -# as follows (values are filled from ScopeResult data; stands for an -# of that status mark, see _status_mark). -# -# Every body opens with COMMENT_MARKER, which is invisible when rendered and is -# how the action recognises its own PR comment on the next run. -# -# Failure: -# -# -# ## Commit Check failed -# -# Pull request: passed
Commits: 2 of 3 failed
Branch: failed -# (one source line: see _group_lines) -# -# ```diff -# @@ 5584f46 @@ -# - bad msg -# + fix: bad msg -# @@ 37d6def @@ -# feat: add OAuth providers -# - Co-authored-by: Claude -# @@ Branch @@ -# - login-page -# # Use / with an allowed type -# ``` -# -# Commits: [`5584f46`](…) [`37d6def`](…)  |  Rules: [CC001](…) · [CC013](…) · [CC201](…) -# -#
-# How to fix -# -# **With an AI coding agent.** Paste this prompt: -# -# ```text -# Fix these Commit Check findings without changing any code: -# - Commit 5584f46: change "bad msg" to "fix: bad msg" -# - Commit 37d6def "feat: add OAuth providers": remove "Co-authored-by: Claude " -# - Branch "login-page": Use / with an allowed type -# ``` -# -# **Commit messages.** Reword them, then force-push: -# -# ```bash -# git rebase -i 5584f46~1 # change "pick" to "reword" on the commits above -# git push --force-with-lease -# ``` -# -# **Branch name.** Rename the branch and push it. … -# -# **Next time.** The [pre-commit hook](…) runs the same rules before you push. -# -#
-# -#
-# All 5 checks -# -# ```text -# Pull request -# ✔ title feat: add login page -# Commits -# ✔ d87faca feat: add login page -# ✖ 5584f46 bad msg -# CC001 message -# value: bad msg -# The commit message should follow Conventional Commits. -# Fix: fix: bad msg -# ✖ 37d6def feat: add OAuth providers -# CC013 ai-attribution -# value: Claude Code -# AI attribution is forbidden in this project — detected: Claude Code -# Suggest: … -# Fix: feat: add OAuth providers -# Branch -# ✖ branch login-page -# CC201 branch -# value: login-page -# The branch should follow Conventional Branch. -# Suggest: Use / with an allowed type, or … -# ``` -# -#
-# -# Checked by [Commit Check](https://commit-check.com) 2.22.0 · [Rules](…) · [Check before you push](…) -# -# Success: the heading reads " Commit Check passed", then the -# group lines, the folded listing and the footer. No diff, no "How to fix". -# -# Warning (the repository's config lists a rule under the top-level `warn`): -# " Commit Check passed with warnings", the group lines (a warned -# group reads " Branch: 1 warning"), then **Warnings** and -# the same diff block built from the warnings. A warned scope is reported -# exactly like a failing one except the mark is ⚠ rather than ✖, it counts -# toward "passed" rather than "failed", and it never turns the workflow red. -# A real failure elsewhere still fails the run; both diff blocks then appear. -# -# Skipped (every rule declined to run — e.g. the author is in ignore_authors): -# " Commit Check skipped", then "Nothing was validated." and the -# reason ("Skipped because author dependabot[bot] is in ignore_authors."). The -# reason comes from commit-check; an older CLI sends none. A skipped scope -# deliberately carries no ✔ and no checked value: nothing was examined, so -# there is no value to report and no pass to claim. When only some scopes -# skip, their group line says so ("Author: 1 passed, 1 skipped"). -# -# The step log prints the same listing, each group folded under a title that -# carries its result, plus a `Docs:` line per finding; then one annotation per -# finding, and the verdict: -# -# ::group::✖ Commits: 2 of 3 failed -# ✔ d87faca feat: add login page -# ✖ 5584f46 bad msg -# CC001 message -# … -# ::endgroup:: -# ::error title=CC001 message::Commit 2/3 (5584f46): change "bad msg" to "fix: bad msg"%0AThe commit message should follow Conventional Commits. -# ✖ Commit Check: 2 of 5 checks failed -# How to fix: see the job summary. Check before you push: https://commit-check.com/… -# -# The verdict is a plain line, not an `::error`, so the run's error count is -# the number of findings. -# -# Notes: -# - The status marks are the Commit Check mark in a status colour, so the mark -# itself is the status signal: there is never a tick next to a failure. -# Their alt text is the glyph the step log uses, so the report still reads -# where the images cannot load. -# - A red line is text that was found and has to change, a green line is text -# to write, taken from the CLI's `fix` (see _line_edits). A rule with no -# mechanical fix gets a `#` line with the CLI's suggestion instead. -# - The diff lists only what failed, capped at MAX_HUNKS items with the rest -# folded; passing scopes live in the listing. -# - A commit is named by its short hash on every surface; the label -# ("Commit 1/11") stays bare in the `result` output. -# - With `files: true` each commit also gets a row in a "Files" group, for the -# files it changes. Its hunk reads `@@ 5584f46 files @@`, with a red line per -# path a rule found and the rule's advice under it. The agent prompt then -# opens with "changing only the files they name" in place of "without -# changing any code". -# - One check is one thing that was checked — a commit message, the branch, the -# author — not one rule evaluation. The totals therefore match the number of -# ✔/✖ rows the reader can count in the listing, and do not grow with the -# number of rules in the config. -# - Passing values are capped at 60 characters with a literal "..." suffix; a -# failing scope prints its value in full — it is the one value the reader -# has to act on and the cap can hide the reason. -# - Every fenced block grows its fence past any backtick run inside it, so a -# subject that quotes code cannot close the block. -# --------------------------------------------------------------------------- - - -def _commit_check_version() -> str: - """Version of the commit-check CLI that produced these results.""" - try: - from importlib.metadata import version - - return version("commit-check") - except Exception: # noqa: BLE001 - the version is decoration, never fail on it - return "" - - -def _report_footer() -> str: - """Attribution line: who checked, which version, and where to go next. - - The version is the first thing worth knowing when a result looks wrong, - and it is otherwise buried in the step log. The last link is for the - contributor who would rather hear this before pushing. - """ - installed = _commit_check_version() - version = f" {installed}" if installed else "" - return ( - f"Checked by [Commit Check]({SITE_URL}){version} · " - f"[Rules]({RULES_URL}) · [Check before you push]({LOCAL_HOOK_URL})" - ) - - -def _run_url() -> str: - """Link to this workflow run, whose page holds the job summary.""" - repository = os.getenv("GITHUB_REPOSITORY", "") - run_id = os.getenv("GITHUB_RUN_ID", "") - if not (repository and run_id): - return "" - server = os.getenv("GITHUB_SERVER_URL") or "https://github.com" - return f"{server.rstrip('/')}/{repository}/actions/runs/{run_id}" - - -def _elsewhere(what: str) -> str: - """Point to where the parts a shortened comment left out can be read.""" - where = "job summary" if _summary_written() else "step log" - url = _run_url() - place = f"[{where}]({url})" if url else where - return f"{what} are in the {place} of this run." - - -def render_report(results: list[ScopeResult], detail: str = "full") -> str: - """Render the Markdown report shared by the job summary and PR comment. - - Opens with the hidden marker and a heading that is the verdict — the - status mark and ``Commit Check failed`` / ``passed`` — then one line per - group, the diff of what failed, a diff of the warnings when the config - listed any rule under ``warn``, the folded "How to fix", and the folded - listing of every scope. - - ``detail`` is for a PR comment that would not fit (``render_pr_comment``): - ``"short"`` leaves out the listing, ``"headline"`` everything below the - group lines, and either says where to read what it left out. - - A warned scope counts toward "passed", never toward "failed": it ran, - found something, and is reported in full, but the config asked for it to - be surfaced rather than enforced. - """ - failed, total = _check_counts(results) - warned = _warn_count(results) - skipped = _skip_count(results) - - if failed: - status, verdict = "fail", "failed" - elif total and skipped == total: - # Nothing ran, so there is no success to announce. Saying "passed" - # here is the defect this branch exists to prevent. - status, verdict = "skip", "skipped" - elif warned: - status, verdict = "warn", "passed with warnings" - else: - status, verdict = "pass", "passed" - - lines = [COMMENT_MARKER, f"## {_status_mark(status, 24)} Commit Check {verdict}"] - lines.append("") - if status == "skip": - lines.extend(["Nothing was validated.", ""]) - if results: - lines.extend([_group_lines(results), ""]) - if skipped and _skip_reasons(results): - lines.extend([_skip_reasons(results), ""]) - if detail == "headline": - what = "The findings and how to fix them" if failed or warned else "All checks" - lines.extend([_elsewhere(what), "", _report_footer()]) - return "\n".join(lines) - if failed: - lines.extend([*_diff_block(results), ""]) - if warned: - lines.extend(["**Warnings**", "", *_diff_block(results, "warn"), ""]) - if failed: - how = _how_to_fix(results) - lines.extend([*how, ""] if how else []) - if detail == "short": - lines.extend([_elsewhere(f"All {_plural(total, 'check')}"), ""]) - else: - lines.extend([*_all_checks(results), ""]) - lines.append(_report_footer()) - return "\n".join(lines) - - -def render_job_summary(results: list[ScopeResult]) -> str: - """Create the Markdown body for the GitHub job summary.""" - return render_report(results) - - -#: The longest comment GitHub accepts, in UTF-16 code units. -COMMENT_LIMIT = 65536 - - -def _comment_length(body: str) -> int: - """Length of a comment as GitHub counts it: in UTF-16 code units.""" - return len(body.encode("utf-16-le")) // 2 - - -def render_pr_comment(results: list[ScopeResult]) -> str: - """Create the Markdown body for the PR comment (same report as summary). - - The report grows with the pull request: every failing commit's message - is quoted in the diff, the prompt and the listing. A few dozen failing - commits ran past GitHub's limit, the API refused the comment, and an - earlier one, perhaps saying "passed", stayed on the pull request. So a - report that does not fit drops the listing, then everything under the - group lines, and points to the run for the rest. The job summary, with - its far higher limit, keeps the full report. - """ - for detail in ("full", "short"): - body = render_report(results, detail) - if _comment_length(body) <= COMMENT_LIMIT: - return body - return render_report(results, "headline") - - -# --------------------------------------------------------------------------- -# Output surfaces -# --------------------------------------------------------------------------- - - -def add_job_summary(results: list[ScopeResult]) -> int: - """Adds the commit check result to the GitHub job summary.""" - if not JOB_SUMMARY_ENABLED or not GITHUB_STEP_SUMMARY: - return 0 - - with open(GITHUB_STEP_SUMMARY, "a", encoding="utf-8") as summary_file: - summary_file.write(render_job_summary(results)) - - return exit_code_for(results) - - -def set_result_output(results: list[ScopeResult]) -> None: - """Expose the structured results as the ``result`` action output. - - Written through :func:`_write_output`, whose per-write random delimiter - keeps a line of user text (a commit subject reading ``EOF``, say) from - closing the heredoc early. - """ - output_path = os.getenv("GITHUB_OUTPUT") - if not output_path: - return - payload = { - "status": overall_status(results), - "ai_tools": ai_tools_found(results), - "scopes": [ - { - "label": scope.label, - "sha": scope.sha, - "status": scope.status, - "checks": scope.checks, - } - for scope in results - ], - } - with open(output_path, "a", encoding="utf-8") as f: - _write_output(f, "result", json.dumps(payload, indent=2)) - - -def _write_output(f: Any, name: str, value: str) -> None: - """Append one multi-line output in the heredoc form ``GITHUB_OUTPUT`` takes. - - The runner reads lines up to the first one equal to the delimiter and - rejects the whole file if it never finds one, which fails the step and - drops every output written after the bad one. A fixed ``EOF`` delimiter - is therefore unsafe: the JSON quotes commit subjects and error text as - they are, and a subject reading ``EOF`` is legal. So the delimiter is - random per write, the shape actions/github-script uses. - """ - delimiter = f"ghadelimiter_{uuid.uuid4()}" - while delimiter in value: # pragma: no cover - 122 random bits - delimiter = f"ghadelimiter_{uuid.uuid4()}" - f.write(f"{name}<<{delimiter}\n{value}\n{delimiter}\n") - - -def is_fork_pr() -> bool: - """Returns True when the triggering PR originates from a forked repository.""" - event_path = os.getenv("GITHUB_EVENT_PATH") - if not event_path: - return False - try: - with open(event_path, "r", encoding="utf-8") as f: - event = json.load(f) - pr = event.get("pull_request", {}) - head_full_name = pr.get("head", {}).get("repo", {}).get("full_name", "") - base_full_name = pr.get("base", {}).get("repo", {}).get("full_name", "") - return bool( - head_full_name and base_full_name and head_full_name != base_full_name - ) - except Exception: # noqa: BLE001 - an unreadable payload is not a fork PR - return False - - -def is_fork_pr_with_readonly_token() -> bool: - """Returns True when the PR is from a fork AND the event has a read-only token. - - Under the pull_request event, GITHUB_TOKEN is read-only for fork PRs. - Under pull_request_target, GITHUB_TOKEN has the workflow's configured - permissions regardless of whether the PR is from a fork. - """ - return is_fork_pr() and os.getenv("GITHUB_EVENT_NAME", "") != "pull_request_target" - - -def get_pr_number() -> int: - """Extract the pull request number from event payload or GITHUB_REF. - - For pull_request: GITHUB_REF is refs/pull//merge - For pull_request_target: GITHUB_REF is refs/heads/ (not useful), - so we fall back to the event payload. - """ - ref = os.getenv("GITHUB_REF", "") - parts = ref.split("/") - if len(parts) >= 4 and parts[1] == "pull": - return int(parts[2]) - # Fallback: read PR number from event payload - event_path = os.getenv("GITHUB_EVENT_PATH") - if event_path: - try: - with open(event_path, "r", encoding="utf-8") as f: - event = json.load(f) - number = event.get("number") or (event.get("pull_request", {}) or {}).get( - "number" - ) - if number: - return int(number) - except Exception: # noqa: BLE001, S110 - fall through to the error below - pass - raise ValueError( - "Unable to determine PR number from GITHUB_REF or GITHUB_EVENT_PATH" - ) - - -def _is_bot(comment: Any) -> bool: - """Whether a comment was posted by a bot account rather than a person.""" - try: - return comment.user.type == "Bot" - except Exception: # noqa: BLE001 - an unknown author is not a bot - return False - - -def _find_own_comments(comments: list[Any]) -> tuple[Any | None, list[Any]]: - """Pick the comment to update and the ones to delete. - - Returns ``(target, stale)``. Only comments a bot posted with - ``COMMENT_MARKER`` in them are ever edited or deleted: a person can paste - the marker too (quoting a report, say), and their comment is theirs. A comment from an earlier - version has no marker, so it is adopted (edited, which adds the marker) - when there is no marked comment yet, and only if a bot posted it: the - legacy signal is a title prefix, which a person can type by accident, and - editing someone's comment out from under them is not recoverable. - """ - marked = [c for c in comments if COMMENT_MARKER in c.body and _is_bot(c)] - if marked: - return marked[-1], marked[:-1] - - legacy = [c for c in comments if c.body.startswith(LEGACY_TITLES) and _is_bot(c)] - return (legacy[-1], []) if legacy else (None, []) - - -def add_pr_comments(results: list[ScopeResult]) -> int: - """Posts the commit check result as a comment on the pull request.""" - if not PR_COMMENTS_ENABLED: - return 0 - - # A push has no pull request to comment on. This used to fall through to - # get_pr_number(), which raised, and every push run carried a warning. - if not is_pr_event(): - print("Skipping PR comment: not a pull request event.") - return 0 - - # Fork PRs triggered by the pull_request event receive a read-only token; - # the GitHub API will always reject comment writes with 403. - # pull_request_target events always have the configured token permissions. - if is_fork_pr_with_readonly_token(): - # Name only the surfaces this run actually produced: with - # job-summary: false there is no summary to send the reader to. - where = "in the annotations on the run page" - if _summary_written(): - where = f"in this job's summary and {where}" - msg = ( - "Skipping PR comment: pull requests from forked repositories " - "cannot write comments via the pull_request event (GITHUB_TOKEN is " - f"read-only for forks). The findings are {where}. " - "See https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md" - ) - print(f"::warning::{msg}") - if JOB_SUMMARY_ENABLED and GITHUB_STEP_SUMMARY: - with open(GITHUB_STEP_SUMMARY, "a", encoding="utf-8") as f: - f.write( - "\n---\n" - "### \u2139\ufe0f PR Comment Skipped\n\n" - "Pull requests from forked repositories cannot write comments " - "using the `pull_request` event because `GITHUB_TOKEN` has " - "read-only permissions. The report above and the annotations " - "on the run page are unaffected.\n\n" - "> **\U0001f4a1 Tip:** see " - "[Fork pull requests]" - "(https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md).\n" - ) - return 0 - - try: - from github import Auth, Github, GithubException # type: ignore - except ImportError as e: - # Imported here, so it has to be caught here. Leaving it inside the - # try below would bind GithubException only on success — and an - # ImportError would then make the `except GithubException` clause - # itself raise NameError, which propagates past the `except Exception` - # underneath it and kills a step that is meant to be non-fatal. - print(f"::warning::Unable to post PR comment: {e}", file=sys.stderr) - return 0 - - try: - token = os.getenv("GITHUB_TOKEN") - repo_name = os.getenv("GITHUB_REPOSITORY") - pr_number = get_pr_number() - - if not token: - raise ValueError("GITHUB_TOKEN is not set") - if not repo_name: - raise ValueError("GITHUB_REPOSITORY is not set") - - api_url = os.getenv("GITHUB_API_URL", "https://api.github.com") - g = Github(auth=Auth.Token(token), base_url=api_url) - repo = g.get_repo(repo_name) - pull_request = repo.get_issue(pr_number) - - pr_comment_body = render_pr_comment(results) - - target, stale = _find_own_comments(list(pull_request.get_comments())) - - if target is not None: - if target.body == pr_comment_body: - print(f"PR comment already up-to-date for PR #{pr_number}.") - return exit_code_for(results) - print(f"Updating the last comment on PR #{pr_number}.") - target.edit(pr_comment_body) - for comment in stale: - print(f"Deleting an old comment on PR #{pr_number}.") - comment.delete() - else: - print(f"Creating a new comment on PR #{pr_number}.") - pull_request.create_comment(body=pr_comment_body) - - return exit_code_for(results) - except GithubException as e: - if e.status == 403: - # GithubException.data is whatever the response decoded to, which - # is None for an empty body and a str for a non-JSON one. Reaching - # for .get unguarded would raise inside this handler and escape the - # function, turning the best-effort path into a step failure. - detail = e.data.get("message") if isinstance(e.data, dict) else None - print( - "::warning::Unable to post PR comment (403 Forbidden). " - "Ensure your workflow grants 'pull-requests: write' permission. " - f"Error: {detail or e}", - file=sys.stderr, - ) - return 0 - # Annotated, not just printed: posting the comment is best-effort and - # never fails the step, so without an annotation the run is green, the - # comment is absent, and nothing says why. - print(f"::warning::Unable to post PR comment: {e}", file=sys.stderr) - return 0 - except Exception as e: # noqa: BLE001 - the comment is best-effort - print(f"::warning::Unable to post PR comment: {e}", file=sys.stderr) - return 0 - - -def ai_tools_found(results: list[ScopeResult]) -> list[str]: - """Every AI tool found in the pull request, sorted. - - In the checked commits (messages and authors), the title, the - description, and the app that opened the pull request. - """ - tools = {tool for scope in results for tool in scope.ai_tools} - tools.update(PR_BODY_AI_TOOLS) - if is_pr_event(): - opener = get_pr_opener_tool() - if opener: - tools.add(opener) - return sorted(tools) +This file is the entrypoint action.yml runs; the code lives in the ``action`` +package next to it, one module per part of the work. +""" -def add_ai_label(results: list[ScopeResult]) -> None: - """Label the pull request when an AI tool wrote any of it (``ai-label``). +import sys - The label is only ever added, never removed: a maintainer may have put - it there by hand. Best-effort, like the comment: a failure warns and - never fails the step. - """ - name = ai_label_name() - if not name or not is_pr_event(): - return - tools = ai_tools_found(results) - if not tools: - print("No AI tool found in the pull request; no label added.") - return - found = ", ".join(tools) - if is_fork_pr_with_readonly_token(): - print( - f"::warning::AI tools found ({found}), but the label '{name}' was " - "not added: pull requests from forked repositories get a read-only " - "GITHUB_TOKEN under the pull_request event. " - "See https://github.com/commit-check/commit-check-action/blob/main/docs/fork-pr-comments.md" - ) - return +from action import base_config, cli, inputs, publish, render - try: - from github import Auth, Github, GithubException # type: ignore - except ImportError as e: - print(f"::warning::Unable to add the AI label: {e}", file=sys.stderr) - return - try: - token = os.getenv("GITHUB_TOKEN") - repo_name = os.getenv("GITHUB_REPOSITORY") - if not token: - raise ValueError("GITHUB_TOKEN is not set") - if not repo_name: - raise ValueError("GITHUB_REPOSITORY is not set") - pr_number = get_pr_number() - api_url = os.getenv("GITHUB_API_URL", "https://api.github.com") - repo = Github(auth=Auth.Token(token), base_url=api_url).get_repo(repo_name) - issue = repo.get_issue(pr_number) - if any(label.name == name for label in issue.labels): - print(f"PR #{pr_number} already has the label '{name}' ({found}).") - return - try: - repo.get_label(name) - except GithubException as e: - if e.status != 404: - raise - try: - repo.create_label( - name, AI_LABEL_COLOR, "Written with the help of an AI tool" - ) - except GithubException as created: - # 422: another run created it in the meantime; use that one. - if created.status != 422: - raise - issue.add_to_labels(name) - print(f"Added the label '{name}' to PR #{pr_number}: {found}.") - except GithubException as e: - hint = ( - " Ensure your workflow grants 'pull-requests: write' permission." - if e.status == 403 - else "" - ) - print( - f"::warning::Unable to add the AI label.{hint} Error: {e}", file=sys.stderr - ) - except Exception as e: # noqa: BLE001 - the label is best-effort - print(f"::warning::Unable to add the AI label: {e}", file=sys.stderr) +def _reconfigure_io() -> None: + """Reconfigure stdout/stderr to UTF-8 so emoji and check marks never + crash on runners with legacy encodings (e.g. cp1252 on Windows).""" + for stream in (sys.stdout, sys.stderr): + if hasattr(stream, "reconfigure"): + stream.reconfigure(encoding="utf-8", errors="replace") def log_error_and_exit(ret_code: int) -> None: @@ -2992,42 +41,25 @@ def log_error_and_exit(ret_code: int) -> None: sys.exit(ret_code) -def fail_on_invalid_flags() -> None: - """Stop with an error when an input holds a value it does not take.""" - invalid = CONFIG_SOURCE not in CONFIG_SOURCES - if not INVALID_FLAGS and not invalid: - return - for name, value in INVALID_FLAGS: - input_name = name.lower().replace("_", "-") - print( - f"::error::Input {input_name} must be true or false, got " - f"{_log_safe(repr(value))}" - ) - if invalid: - print( - "::error::Input config-source must be head or base, got " - f"{_log_safe(repr(os.getenv('CONFIG_SOURCE', '')))}" - ) - sys.exit(1) - - def main(): """Main function to run commit-check and render all output surfaces.""" _reconfigure_io() - fail_on_invalid_flags() - log_env_vars() - if not use_base_config(): + inputs.fail_on_invalid_flags() + inputs.log_env_vars() + if not base_config.use_base_config(): sys.exit(1) - ret_code, results = run_commit_check() + ret_code, results = cli.run_commit_check() - render_step_log(results) - set_result_output(results) + render.render_step_log(results) + publish.set_result_output(results) - ret_code = max(ret_code, add_job_summary(results), add_pr_comments(results)) - add_ai_label(results) + ret_code = max( + ret_code, publish.add_job_summary(results), publish.add_pr_comments(results) + ) + publish.add_ai_label(results) - if DRY_RUN_ENABLED: + if inputs.DRY_RUN_ENABLED: ret_code = 0 log_error_and_exit(ret_code) diff --git a/tests/base_config_test.py b/tests/base_config_test.py index d6f7d3e..a4072ad 100644 --- a/tests/base_config_test.py +++ b/tests/base_config_test.py @@ -12,14 +12,15 @@ from unittest.mock import MagicMock, patch import main +from action import base_config, cli class TestConfigSource(unittest.TestCase): """config-source: base checks a pull request against its base branch's config.""" def setUp(self): - main.CONFIG_ARGS.clear() - self.addCleanup(main.CONFIG_ARGS.clear) + base_config.CONFIG_ARGS.clear() + self.addCleanup(base_config.CONFIG_ARGS.clear) tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) self.tmp = tmp.name @@ -44,7 +45,7 @@ def setUp(self): ) for target in ( patch.dict(os.environ, env, clear=True), - patch("main.CONFIG_SOURCE", "base"), + patch("action.inputs.CONFIG_SOURCE", "base"), ): target.start() self.addCleanup(target.stop) @@ -83,7 +84,7 @@ def _base(self, sha: str | None) -> None: def _use_base(self) -> tuple[bool, str]: out = io.StringIO() with patch("sys.stdout", out): - ok = main.use_base_config() + ok = base_config.use_base_config() return ok, out.getvalue() def _read(self, path: str) -> str: @@ -91,24 +92,24 @@ def _read(self, path: str) -> str: return f.read() def _config_file(self) -> str: - self.assertEqual(main.CONFIG_ARGS[0], "--config") - return main.CONFIG_ARGS[1] + self.assertEqual(base_config.CONFIG_ARGS[0], "--config") + return base_config.CONFIG_ARGS[1] def test_head_reads_the_checkout_and_runs_nothing(self): with ( - patch("main.CONFIG_SOURCE", "head"), - patch("main.subprocess.run") as run, + patch("action.inputs.CONFIG_SOURCE", "head"), + patch("subprocess.run") as run, ): ok, out = self._use_base() self.assertTrue(ok) - self.assertEqual((main.CONFIG_ARGS, out), ([], "")) + self.assertEqual((base_config.CONFIG_ARGS, out), ([], "")) run.assert_not_called() def test_outside_a_pull_request_the_checkout_is_read(self): with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "push"}): ok, out = self._use_base() self.assertTrue(ok) - self.assertEqual(main.CONFIG_ARGS, []) + self.assertEqual(base_config.CONFIG_ARGS, []) self.assertIn("config-source: base applies to pull requests", out) def test_the_pull_request_cannot_loosen_its_own_rules(self): @@ -189,7 +190,7 @@ def test_a_parent_outside_the_repository_fails_closed(self): self._base(base) ok, out = self._use_base() self.assertFalse(ok) - self.assertEqual(main.CONFIG_ARGS, []) + self.assertEqual(base_config.CONFIG_ARGS, []) self.assertIn( "::error title=commit-check::config-source is base, but the base " 'branch config cchk.toml inherits from "../org.toml", outside the ' @@ -236,7 +237,7 @@ def test_a_base_commit_the_event_lacks_fails_closed(self): self._base(None) ok, out = self._use_base() self.assertFalse(ok) - self.assertEqual(main.CONFIG_ARGS, []) + self.assertEqual(base_config.CONFIG_ARGS, []) self.assertIn( "::error title=commit-check::config-source is base, but the base " "branch commit could not be read (is actions/checkout using " @@ -248,42 +249,44 @@ def test_a_base_commit_the_event_lacks_fails_closed(self): def test_a_base_commit_the_clone_lacks_is_fetched(self): self._base("a" * 40) with ( - patch("main._fetch_commit", return_value=False) as fetch, + patch("action.context._fetch_commit", return_value=False) as fetch, patch("sys.stdout", io.StringIO()), ): - self.assertFalse(main.use_base_config()) + self.assertFalse(base_config.use_base_config()) fetch.assert_called_once_with("a" * 40) with ( - patch("main._rev_resolves", return_value=False), - patch("main._fetch_commit", return_value=True), - patch("main._base_blob", return_value=None), + patch("action.context._rev_resolves", return_value=False), + patch("action.context._fetch_commit", return_value=True), + patch("action.base_config._base_blob", return_value=None), patch("sys.stdout", io.StringIO()), ): - self.assertTrue(main.use_base_config()) + self.assertTrue(base_config.use_base_config()) self.assertEqual(self._read(self._config_file()), "") def test_git_missing_fails_closed(self): with ( - patch("main.subprocess.run", side_effect=OSError("no git")), - self.assertRaisesRegex(main.BaseConfigError, "git could not run"), + patch("subprocess.run", side_effect=OSError("no git")), + self.assertRaisesRegex(base_config.BaseConfigError, "git could not run"), ): - main._base_blob("a" * 40, "cchk.toml") + base_config._base_blob("a" * 40, "cchk.toml") def test_a_commit_git_cannot_list_fails_closed(self): - with self.assertRaisesRegex(main.BaseConfigError, "could not list cchk.toml"): - main._base_blob("a" * 40, "cchk.toml") + with self.assertRaisesRegex( + base_config.BaseConfigError, "could not list cchk.toml" + ): + base_config._base_blob("a" * 40, "cchk.toml") def test_a_file_git_cannot_read_is_not_taken_for_no_config(self): """A partial clone that cannot fetch the blob must not read as absent.""" listed = MagicMock(returncode=0, stdout=b"100644 blob abc\tcchk.toml\n") unread = MagicMock(returncode=128, stdout=b"") with ( - patch("main.subprocess.run", side_effect=[listed, unread]), + patch("subprocess.run", side_effect=[listed, unread]), self.assertRaisesRegex( - main.BaseConfigError, "cchk.toml could not be read from the base" + base_config.BaseConfigError, "cchk.toml could not be read from the base" ), ): - main._base_blob("a" * 40, "cchk.toml") + base_config._base_blob("a" * 40, "cchk.toml") base = self._commit({"cchk.toml": "[commit]\n"}) self._base(base) real_run = subprocess.run @@ -293,10 +296,10 @@ def no_blobs(cmd, *args, **kwargs): return unread return real_run(cmd, *args, **kwargs) - with patch("main.subprocess.run", side_effect=no_blobs): + with patch("subprocess.run", side_effect=no_blobs): ok, out = self._use_base() self.assertFalse(ok) - self.assertEqual(main.CONFIG_ARGS, []) + self.assertEqual(base_config.CONFIG_ARGS, []) self.assertIn( "::error title=commit-check::config-source is base, but cchk.toml " "could not be read from the base commit; nothing was checked", @@ -319,16 +322,16 @@ def test_a_symbolic_link_is_refused(self): def test_a_folder_named_like_a_config_is_no_config(self): base = self._commit({"cchk.toml/README.md": "hi\n"}) - self.assertIsNone(main._base_blob(base, "cchk.toml")) + self.assertIsNone(base_config._base_blob(base, "cchk.toml")) def test_an_absolute_parent_fails_closed(self): for parent in ("/etc/cchk.toml", "\\\\server\\cchk.toml"): - main.CONFIG_ARGS.clear() + base_config.CONFIG_ARGS.clear() base = self._commit({"cchk.toml": f"inherit_from = {json.dumps(parent)}\n"}) self._base(base) ok, out = self._use_base() self.assertFalse(ok, parent) - self.assertEqual(main.CONFIG_ARGS, []) + self.assertEqual(base_config.CONFIG_ARGS, []) self.assertIn("an absolute path the base branch cannot vouch for", out) def test_a_parent_path_through_a_folder_resolves_to_the_base_copy(self): @@ -360,10 +363,12 @@ def test_only_a_local_parent_is_copied(self): b"\xff\xfe", b"", ): - self.assertIsNone(main._local_parent(data), data) - self.assertEqual(main._local_parent(b'inherit_from = "a/b.toml"\n'), "a/b.toml") + self.assertIsNone(base_config._local_parent(data), data) + self.assertEqual( + base_config._local_parent(b'inherit_from = "a/b.toml"\n'), "a/b.toml" + ) self.assertEqual( - main._local_parent(b'inherit_from = "/etc/c.toml"\n'), "/etc/c.toml" + base_config._local_parent(b'inherit_from = "/etc/c.toml"\n'), "/etc/c.toml" ) @unittest.skipUnless(shutil.which("commit-check"), "needs commit-check") @@ -373,17 +378,17 @@ def test_commit_check_runs_on_the_base_rules(self): self._base(base) self.assertTrue(self._use_base()[0]) with patch("sys.stderr", io.StringIO()): - rc, data, _raw = main.run_check_json( + rc, data, _raw = cli.run_check_json( ["--message"], input_text="chore: tidy up\n" ) self.assertEqual(rc, 1) self.assertEqual(data["status"], "fail") def test_every_check_gets_the_config(self): - main.CONFIG_ARGS[:] = ["--config", "/tmp/x/cchk.toml"] + base_config.CONFIG_ARGS[:] = ["--config", "/tmp/x/cchk.toml"] mock_result = MagicMock(returncode=0, stdout="{}", stderr="") - with patch("main.subprocess.run", return_value=mock_result) as run: - main.run_check_json(["--branch"]) + with patch("subprocess.run", return_value=mock_result) as run: + cli.run_check_json(["--branch"]) self.assertEqual( run.call_args[0][0], [ @@ -399,10 +404,10 @@ def test_every_check_gets_the_config(self): def test_an_unknown_value_fails_before_any_check(self): out = io.StringIO() with ( - patch("main.CONFIG_SOURCE", "main"), + patch("action.inputs.CONFIG_SOURCE", "main"), patch.dict(os.environ, {"CONFIG_SOURCE": "main"}), patch("sys.stdout", out), - patch("main.run_commit_check") as run, + patch("action.cli.run_commit_check") as run, self.assertRaises(SystemExit) as cm, ): main.main() @@ -415,9 +420,9 @@ def test_an_unknown_value_fails_before_any_check(self): def test_main_stops_when_the_base_config_cannot_be_read(self): with ( - patch("main.log_env_vars"), - patch("main.use_base_config", return_value=False), - patch("main.run_commit_check") as run, + patch("action.inputs.log_env_vars"), + patch("action.base_config.use_base_config", return_value=False), + patch("action.cli.run_commit_check") as run, self.assertRaises(SystemExit) as cm, ): main.main() diff --git a/tests/cli_test.py b/tests/cli_test.py index b738dbf..289b499 100644 --- a/tests/cli_test.py +++ b/tests/cli_test.py @@ -18,7 +18,7 @@ pass_scope, ) -import main +from action import cli, context, inputs, model, render def json_output(*checks) -> str: @@ -30,8 +30,8 @@ def json_output(*checks) -> str: class TestRunCheckJson(unittest.TestCase): def test_parses_json_output(self): mock_result = MagicMock(returncode=0, stdout=json_output(make_check("branch"))) - with patch("main.subprocess.run", return_value=mock_result): - rc, data, raw = main.run_check_json(["--branch"]) + with patch("subprocess.run", return_value=mock_result): + rc, data, raw = cli.run_check_json(["--branch"]) self.assertEqual(rc, 0) self.assertEqual(data["status"], "pass") self.assertEqual(len(data["checks"]), 1) @@ -39,8 +39,8 @@ def test_parses_json_output(self): def test_command_includes_format_json(self): mock_result = MagicMock(returncode=0, stdout="{}") - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - main.run_check_json(["--branch"]) + with patch("subprocess.run", return_value=mock_result) as mock_run: + cli.run_check_json(["--branch"]) self.assertEqual( mock_run.call_args[0][0], ["commit-check", "--format", "json", "--branch"], @@ -48,15 +48,15 @@ def test_command_includes_format_json(self): def test_input_text_is_passed_through(self): mock_result = MagicMock(returncode=0, stdout="{}") - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - main.run_check_json(["--message"], input_text="fix: demo") + with patch("subprocess.run", return_value=mock_result) as mock_run: + cli.run_check_json(["--message"], input_text="fix: demo") self.assertEqual(mock_run.call_args[1]["input"], "fix: demo") self.assertTrue(mock_run.call_args[1]["text"]) def test_invalid_json_returns_none_with_raw_output(self): mock_result = MagicMock(returncode=1, stdout="Commit rejected.\n", stderr="") - with patch("main.subprocess.run", return_value=mock_result): - rc, data, raw = main.run_check_json(["--branch"]) + with patch("subprocess.run", return_value=mock_result): + rc, data, raw = cli.run_check_json(["--branch"]) self.assertEqual(rc, 1) self.assertIsNone(data) self.assertEqual(raw, "Commit rejected.\n") @@ -67,16 +67,16 @@ def test_parses_checks_into_scope(self): mock_result = MagicMock( returncode=1, stdout=json_output(make_check("branch", status="fail")) ) - with patch("main.subprocess.run", return_value=mock_result): - scope = main.check_scope("Branch", ["--branch"]) + with patch("subprocess.run", return_value=mock_result): + scope = cli.check_scope("Branch", ["--branch"]) self.assertEqual(scope.label, "Branch") self.assertEqual(scope.status, "fail") self.assertEqual(scope.failures[0]["rule_id"], "CC001") def test_invalid_json_falls_back_to_raw_text(self): mock_result = MagicMock(returncode=1, stdout="unexpected output", stderr="") - with patch("main.subprocess.run", return_value=mock_result): - scope = main.check_scope("Branch", ["--branch"]) + with patch("subprocess.run", return_value=mock_result): + scope = cli.check_scope("Branch", ["--branch"]) self.assertEqual(scope.label, "Branch") self.assertEqual(scope.raw_text, "unexpected output") self.assertEqual(scope.status, "fail") @@ -84,9 +84,9 @@ def test_invalid_json_falls_back_to_raw_text(self): def test_keeps_the_text_it_piped_in(self): """The report compares it with a rule's fix to name the lines to change.""" mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message"))) - with patch("main.subprocess.run", return_value=mock_result): - piped = main.check_scope("PR title", ["--message"], input_text="feat: x") - read_by_the_cli = main.check_scope("Branch", ["--branch"]) + with patch("subprocess.run", return_value=mock_result): + piped = cli.check_scope("PR title", ["--message"], input_text="feat: x") + read_by_the_cli = cli.check_scope("Branch", ["--branch"]) self.assertEqual(piped.text, "feat: x") self.assertEqual(read_by_the_cli.text, "") @@ -95,18 +95,18 @@ class TestRunPrMessageChecks(unittest.TestCase): """Each commit's raw message is piped in, with that commit's own author.""" def setUp(self): - local = patch("main._local_author", return_value=None) + local = patch("action.context._local_author", return_value=None) self.local_author = local.start() self.addCleanup(local.stop) - main.API_AUTHORS.clear() - self.addCleanup(main.API_AUTHORS.clear) + context.API_AUTHORS.clear() + self.addCleanup(context.API_AUTHORS.clear) def test_a_commit_in_the_clone_carries_its_own_author(self): """The raw message is still piped, so it reads as before (no --rev).""" self.local_author.return_value = ("Renovate Bot", "bot@renovateapp.com") mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message"))) - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - scopes = main.run_pr_message_checks([(SHA_A, "fix: something")]) + with patch("subprocess.run", return_value=mock_result) as mock_run: + scopes = cli.run_pr_message_checks([(SHA_A, "fix: something")]) self.assertEqual(scopes[0].status, "pass") self.assertEqual(scopes[0].sha, SHA_A) self.local_author.assert_called_once_with(SHA_A) @@ -130,10 +130,10 @@ def test_message_ai_attribution_checks_only_the_ai_rules(self): ) mock_result = MagicMock(returncode=1, stdout=output) with ( - patch("main.MESSAGE_AI_ATTRIBUTION_ENABLED", True), - patch("main.subprocess.run", return_value=mock_result) as mock_run, + patch("action.inputs.MESSAGE_AI_ATTRIBUTION_ENABLED", True), + patch("subprocess.run", return_value=mock_result) as mock_run, ): - [scope] = main.run_pr_message_checks([(SHA_A, "WIP")]) + [scope] = cli.run_pr_message_checks([(SHA_A, "WIP")]) self.assertEqual( mock_run.call_args[0][0], ["commit-check", "--format", "json", "--message"] ) @@ -151,10 +151,10 @@ def test_message_ai_attribution_passes_a_badly_formatted_message(self): ), ) with ( - patch("main.MESSAGE_AI_ATTRIBUTION_ENABLED", True), - patch("main.subprocess.run", return_value=mock_result), + patch("action.inputs.MESSAGE_AI_ATTRIBUTION_ENABLED", True), + patch("subprocess.run", return_value=mock_result), ): - [scope] = main.run_pr_message_checks([(SHA_A, "WIP")]) + [scope] = cli.run_pr_message_checks([(SHA_A, "WIP")]) self.assertEqual(scope.status, "pass") self.assertEqual(scope.text, "WIP") @@ -162,7 +162,7 @@ def test_message_ai_attribution_keeps_the_head_message_for_the_report(self): """Outside a PR nothing is piped in, and the message rule, whose value is the whole message, is one of the rules dropped.""" message = "feat: x\n\nCo-authored-by: Claude " - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit message", checks=[ make_check("message", value=message), @@ -175,12 +175,12 @@ def test_message_ai_attribution_keeps_the_head_message_for_the_report(self): ), ], ) - with patch("main.MESSAGE_AI_ATTRIBUTION_ENABLED", True): - main.keep_ai_rules(scope) + with patch("action.inputs.MESSAGE_AI_ATTRIBUTION_ENABLED", True): + cli.keep_ai_rules(scope) self.assertEqual([c["rule_id"] for c in scope.checks], ["CC013"]) self.assertEqual(scope.text, message) self.assertEqual( - main._line_edits(scope, scope.checks[0]), + render._line_edits(scope, scope.checks[0]), (["Co-authored-by: Claude "], []), ) @@ -188,18 +188,18 @@ def test_message_ai_attribution_under_ignore_is_skipped(self): """No AI rule ran: say so rather than report a pass.""" mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message"))) with ( - patch("main.MESSAGE_AI_ATTRIBUTION_ENABLED", True), - patch("main.subprocess.run", return_value=mock_result), + patch("action.inputs.MESSAGE_AI_ATTRIBUTION_ENABLED", True), + patch("subprocess.run", return_value=mock_result), ): - [scope] = main.run_pr_message_checks([(SHA_A, "feat: x")]) + [scope] = cli.run_pr_message_checks([(SHA_A, "feat: x")]) self.assertEqual(scope.status, "skip") - self.assertEqual(scope.checks[0]["reason"], main.AI_POLICY_IGNORED) + self.assertEqual(scope.checks[0]["reason"], cli.AI_POLICY_IGNORED) def test_a_blank_author_field_is_left_to_git(self): self.local_author.return_value = ("Renovate Bot", "") mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message"))) - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - main.run_pr_message_checks([(SHA_A, "fix: something")]) + with patch("subprocess.run", return_value=mock_result) as mock_run: + cli.run_pr_message_checks([(SHA_A, "fix: something")]) env = mock_run.call_args[1]["env"] self.assertEqual(env["GIT_AUTHOR_NAME"], "Renovate Bot") self.assertNotEqual(env.get("GIT_AUTHOR_EMAIL"), "") @@ -207,22 +207,22 @@ def test_a_blank_author_field_is_left_to_git(self): def test_no_author_at_all_passes_no_environment(self): self.local_author.return_value = ("", "") mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message"))) - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - main.run_pr_message_checks([(SHA_A, "fix: something")]) + with patch("subprocess.run", return_value=mock_result) as mock_run: + cli.run_pr_message_checks([(SHA_A, "fix: something")]) self.assertIsNone(mock_run.call_args[1]["env"]) def test_a_commit_without_a_hash_is_not_looked_up(self): mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message"))) - with patch("main.subprocess.run", return_value=mock_result): - main.run_pr_message_checks([("", "fix: something")]) + with patch("subprocess.run", return_value=mock_result): + cli.run_pr_message_checks([("", "fix: something")]) self.local_author.assert_not_called() def test_an_api_listed_commit_carries_its_author(self): """No commit to read, so the API's author goes in git's variables.""" - main.API_AUTHORS[SHA_A] = ("google-labs-jules[bot]", "jules@example.com") + context.API_AUTHORS[SHA_A] = ("google-labs-jules[bot]", "jules@example.com") mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message"))) - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - main.run_pr_message_checks([(SHA_A, "fix: something")]) + with patch("subprocess.run", return_value=mock_result) as mock_run: + cli.run_pr_message_checks([(SHA_A, "fix: something")]) self.assertEqual(mock_run.call_args[1]["input"], "fix: something") env = mock_run.call_args[1]["env"] self.assertEqual(env["GIT_AUTHOR_NAME"], "google-labs-jules[bot]") @@ -232,8 +232,8 @@ def test_an_api_listed_commit_carries_its_author(self): def test_single_message_pass(self): mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message"))) - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - scopes = main.run_pr_message_checks([(SHA_A, "fix: something")]) + with patch("subprocess.run", return_value=mock_result) as mock_run: + scopes = cli.run_pr_message_checks([(SHA_A, "fix: something")]) self.assertEqual(len(scopes), 1) self.assertEqual(scopes[0].status, "pass") self.assertEqual(scopes[0].label, "Commit 1/1") @@ -250,16 +250,16 @@ def test_failed_message_marks_scope_failed(self): returncode=1, stdout=json_output(make_check("message", status="fail")), ) - with patch("main.subprocess.run", return_value=mock_result): - scopes = main.run_pr_message_checks([(SHA_A, "bad commit")]) + with patch("subprocess.run", return_value=mock_result): + scopes = cli.run_pr_message_checks([(SHA_A, "bad commit")]) self.assertEqual(scopes[0].status, "fail") self.assertEqual(len(scopes[0].failures), 1) self.assertEqual(scopes[0].sha, SHA_A) def test_unparsable_output_still_names_the_commit(self): mock_result = MagicMock(returncode=1, stdout="unexpected output", stderr="") - with patch("main.subprocess.run", return_value=mock_result): - scopes = main.run_pr_message_checks([(SHA_A, "bad commit")]) + with patch("subprocess.run", return_value=mock_result): + scopes = cli.run_pr_message_checks([(SHA_A, "bad commit")]) self.assertEqual(scopes[0].raw_text, "unexpected output") self.assertEqual(scopes[0].sha, SHA_A) @@ -272,8 +272,8 @@ def test_labels_commits_in_order(self): ), MagicMock(returncode=0, stdout=json_output(make_check("message"))), ] - with patch("main.subprocess.run", side_effect=results): - scopes = main.run_pr_message_checks( + with patch("subprocess.run", side_effect=results): + scopes = cli.run_pr_message_checks( [("a" * 40, "ok"), ("b" * 40, "bad"), ("c" * 40, "ok")] ) # The label stays the bare index for the ``result`` output; the hash @@ -285,16 +285,16 @@ def test_labels_commits_in_order(self): self.assertEqual(scopes[1].status, "fail") def test_empty_list(self): - with patch("main.subprocess.run") as mock_run: - scopes = main.run_pr_message_checks([]) + with patch("subprocess.run") as mock_run: + scopes = cli.run_pr_message_checks([]) self.assertEqual(scopes, []) mock_run.assert_not_called() class TestRunOtherChecks(unittest.TestCase): def test_empty_args_returns_no_scopes(self): - with patch("main.subprocess.run") as mock_run: - scopes = main.run_other_checks([]) + with patch("subprocess.run") as mock_run: + scopes = cli.run_other_checks([]) self.assertEqual(scopes, []) mock_run.assert_not_called() @@ -305,8 +305,8 @@ def test_runs_each_flag_as_its_own_scope(self): ), MagicMock(returncode=0, stdout=json_output(make_check("author_name"))), ] - with patch("main.subprocess.run", side_effect=results) as mock_run: - scopes = main.run_other_checks(["--branch", "--author-name"]) + with patch("subprocess.run", side_effect=results) as mock_run: + scopes = cli.run_other_checks(["--branch", "--author-name"]) self.assertEqual([s.label for s in scopes], ["Branch", "Author name"]) self.assertEqual(scopes[0].status, "fail") self.assertEqual(scopes[1].status, "pass") @@ -320,8 +320,8 @@ def test_runs_each_flag_as_its_own_scope(self): ) def test_unknown_flag_is_skipped(self): - with patch("main.subprocess.run") as mock_run: - scopes = main.run_other_checks(["--unknown"]) + with patch("subprocess.run") as mock_run: + scopes = cli.run_other_checks(["--unknown"]) self.assertEqual(scopes, []) mock_run.assert_not_called() @@ -329,48 +329,52 @@ def test_unknown_flag_is_skipped(self): class TestRunCommitCheck(unittest.TestCase): def test_pr_path_checks_each_commit(self): with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.get_pr_commit_messages", return_value=["fix: something"]), - patch("main.run_pr_message_checks", return_value=[pass_scope()]) as mock_pr, - patch("main.run_other_checks", return_value=[]), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch( + "action.context.get_pr_commit_messages", return_value=["fix: something"] + ), + patch( + "action.cli.run_pr_message_checks", return_value=[pass_scope()] + ) as mock_pr, + patch("action.cli.run_other_checks", return_value=[]), ): - rc, results = main.run_commit_check() + rc, results = cli.run_commit_check() self.assertEqual(rc, 0) mock_pr.assert_called_once_with(["fix: something"]) self.assertEqual(len(results), 1) def test_pr_path_fails_when_any_scope_fails(self): with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.BRANCH_ENABLED", True), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.get_pr_commit_messages", return_value=["bad msg"]), - patch("main.run_pr_message_checks", return_value=[fail_scope()]), - patch("main.run_other_checks", return_value=[pass_scope()]), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", True), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.get_pr_commit_messages", return_value=["bad msg"]), + patch("action.cli.run_pr_message_checks", return_value=[fail_scope()]), + patch("action.cli.run_other_checks", return_value=[pass_scope()]), ): - rc, results = main.run_commit_check() + rc, results = cli.run_commit_check() self.assertEqual(rc, 1) self.assertEqual(len(results), 2) def test_pr_title_check_runs_when_enabled(self): with ( - patch("main.PR_TITLE_ENABLED", True), - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.is_pr_event", return_value=True), - patch("main.get_pr_title", return_value="feat: a feature"), + patch("action.inputs.PR_TITLE_ENABLED", True), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.is_pr_event", return_value=True), + patch("action.context.get_pr_title", return_value="feat: a feature"), patch( - "main.check_scope", return_value=pass_scope("PR title") + "action.cli.check_scope", return_value=pass_scope("PR title") ) as mock_scope, - patch("main.run_other_checks", return_value=[]), + patch("action.cli.run_other_checks", return_value=[]), ): - rc, _results = main.run_commit_check() + rc, _results = cli.run_commit_check() self.assertEqual(rc, 0) mock_scope.assert_called_once_with( "PR title", ["--pr-title"], input_text="feat: a feature" @@ -378,31 +382,31 @@ def test_pr_title_check_runs_when_enabled(self): def test_pr_title_failure_propagates(self): with ( - patch("main.PR_TITLE_ENABLED", True), - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.is_pr_event", return_value=True), - patch("main.get_pr_title", return_value="bad title"), - patch("main.check_scope", return_value=fail_scope("PR title")), - patch("main.run_other_checks", return_value=[]), + patch("action.inputs.PR_TITLE_ENABLED", True), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.is_pr_event", return_value=True), + patch("action.context.get_pr_title", return_value="bad title"), + patch("action.cli.check_scope", return_value=fail_scope("PR title")), + patch("action.cli.run_other_checks", return_value=[]), ): - rc, _results = main.run_commit_check() + rc, _results = cli.run_commit_check() self.assertEqual(rc, 1) def test_pr_title_skipped_outside_pr_context(self): with ( - patch("main.PR_TITLE_ENABLED", True), - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.is_pr_event", return_value=False), - patch("main.get_pr_title") as mock_title, - patch("main.run_other_checks", return_value=[]), + patch("action.inputs.PR_TITLE_ENABLED", True), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.is_pr_event", return_value=False), + patch("action.context.get_pr_title") as mock_title, + patch("action.cli.run_other_checks", return_value=[]), ): - rc, _results = main.run_commit_check() + rc, _results = cli.run_commit_check() self.assertEqual(rc, 0) mock_title.assert_not_called() @@ -410,35 +414,35 @@ def test_pr_title_check_needs_a_title_to_check(self): """An event that carries no title adds no scope, rather than checking an empty message.""" with ( - patch("main.PR_TITLE_ENABLED", True), - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.is_pr_event", return_value=True), - patch("main.get_pr_title", return_value=None), - patch("main.check_scope") as mock_scope, - patch("main.run_other_checks", return_value=[]), + patch("action.inputs.PR_TITLE_ENABLED", True), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.is_pr_event", return_value=True), + patch("action.context.get_pr_title", return_value=None), + patch("action.cli.check_scope") as mock_scope, + patch("action.cli.run_other_checks", return_value=[]), ): - rc, results = main.run_commit_check() + rc, results = cli.run_commit_check() self.assertEqual((rc, results), (0, [])) mock_scope.assert_not_called() def test_non_pr_message_check_uses_commit_message_scope(self): with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.get_pr_commit_messages", return_value=[]), - patch("main.run_pr_message_checks") as mock_pr, - patch("main.head_sha", return_value=SHA_A), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.get_pr_commit_messages", return_value=[]), + patch("action.cli.run_pr_message_checks") as mock_pr, + patch("action.context.head_sha", return_value=SHA_A), patch( - "main.check_scope", return_value=pass_scope("Commit message") + "action.cli.check_scope", return_value=pass_scope("Commit message") ) as mock_scope, - patch("main.run_other_checks", return_value=[]), + patch("action.cli.run_other_checks", return_value=[]), ): - rc, _results = main.run_commit_check() + rc, _results = cli.run_commit_check() self.assertEqual(rc, 0) mock_pr.assert_not_called() # HEAD is the commit that was checked, so the scope names it too. @@ -447,16 +451,20 @@ def test_non_pr_message_check_uses_commit_message_scope(self): def test_message_ai_attribution_alone_checks_each_commit(self): """With message: false the commits are still checked, for AI only.""" with ( - patch("main.MESSAGE_ENABLED", False), - patch("main.MESSAGE_AI_ATTRIBUTION_ENABLED", True), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.get_pr_commit_messages", return_value=[(SHA_A, "WIP")]), - patch("main.run_pr_message_checks", return_value=[pass_scope()]) as mock_pr, - patch("main.run_other_checks", return_value=[]) as mock_other, + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.MESSAGE_AI_ATTRIBUTION_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch( + "action.context.get_pr_commit_messages", return_value=[(SHA_A, "WIP")] + ), + patch( + "action.cli.run_pr_message_checks", return_value=[pass_scope()] + ) as mock_pr, + patch("action.cli.run_other_checks", return_value=[]) as mock_other, ): - rc, _results = main.run_commit_check() + rc, _results = cli.run_commit_check() self.assertEqual(rc, 0) mock_pr.assert_called_once_with([(SHA_A, "WIP")]) mock_other.assert_called_once_with([], rev=None) @@ -464,19 +472,19 @@ def test_message_ai_attribution_alone_checks_each_commit(self): def test_message_ai_attribution_narrows_the_head_check(self): """Outside a PR, HEAD is checked for AI only, even with message: true.""" with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.MESSAGE_AI_ATTRIBUTION_ENABLED", True), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.get_pr_commit_messages", return_value=[]), - patch("main.head_sha", return_value=SHA_A), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.MESSAGE_AI_ATTRIBUTION_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.get_pr_commit_messages", return_value=[]), + patch("action.context.head_sha", return_value=SHA_A), patch( - "main.check_scope", return_value=pass_scope("Commit message") + "action.cli.check_scope", return_value=pass_scope("Commit message") ) as mock_scope, - patch("main.run_other_checks", return_value=[]), + patch("action.cli.run_other_checks", return_value=[]), ): - main.run_commit_check() + cli.run_commit_check() mock_scope.assert_called_once_with("Commit message", ["--message"], sha=SHA_A) def test_message_flag_removed_before_other_checks_in_pr(self): @@ -487,15 +495,15 @@ def fake_other_checks(args, rev=None): return [] with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.BRANCH_ENABLED", True), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.get_pr_commit_messages", return_value=["fix: x"]), - patch("main.run_pr_message_checks", return_value=[pass_scope()]), - patch("main.run_other_checks", side_effect=fake_other_checks), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", True), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.get_pr_commit_messages", return_value=["fix: x"]), + patch("action.cli.run_pr_message_checks", return_value=[pass_scope()]), + patch("action.cli.run_other_checks", side_effect=fake_other_checks), ): - main.run_commit_check() + cli.run_commit_check() self.assertNotIn("--message", captured_args) self.assertIn("--branch", captured_args) @@ -507,7 +515,7 @@ def fake_other_checks(args, rev=None): def _run_capturing_stdout(self): buffer = io.StringIO() with patch("sys.stdout", buffer): - rc, results = main.run_commit_check() + rc, results = cli.run_commit_check() return rc, results, buffer.getvalue() def test_pr_without_enumerable_commits_warns_and_checks_head(self): @@ -518,17 +526,17 @@ def test_pr_without_enumerable_commits_warns_and_checks_head(self): "Merge X into Y" commit, which passes CC001 by default. """ with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.is_pr_event", return_value=True), - patch("main.get_pr_commit_messages", return_value=[]), - patch("main.head_sha", return_value=""), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.is_pr_event", return_value=True), + patch("action.context.get_pr_commit_messages", return_value=[]), + patch("action.context.head_sha", return_value=""), patch( - "main.check_scope", return_value=pass_scope("Commit message") + "action.cli.check_scope", return_value=pass_scope("Commit message") ) as mock_scope, - patch("main.run_other_checks", return_value=[]), + patch("action.cli.run_other_checks", return_value=[]), ): rc, _results, output = self._run_capturing_stdout() self.assertEqual(rc, 0) @@ -537,14 +545,14 @@ def test_pr_without_enumerable_commits_warns_and_checks_head(self): def test_push_without_pr_commits_does_not_warn(self): with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.is_pr_event", return_value=False), - patch("main.get_pr_commit_messages", return_value=[]), - patch("main.check_scope", return_value=pass_scope("Commit message")), - patch("main.run_other_checks", return_value=[]), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.is_pr_event", return_value=False), + patch("action.context.get_pr_commit_messages", return_value=[]), + patch("action.cli.check_scope", return_value=pass_scope("Commit message")), + patch("action.cli.run_other_checks", return_value=[]), ): _rc, _results, output = self._run_capturing_stdout() self.assertNotIn("::warning", output) @@ -570,13 +578,13 @@ def test_pr_author_checks_read_the_branch_tip(self): """On refs/pull/N/merge HEAD's author is GitHub, not the contributor.""" run, commands = self._fake_git_and_cli(resolves=True) with ( - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", True), - patch("main.AUTHOR_NAME_ENABLED", True), - patch("main.AUTHOR_EMAIL_ENABLED", True), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", True), + patch("action.inputs.AUTHOR_NAME_ENABLED", True), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", True), patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.get_pr_head_sha", return_value=None), - patch("main.subprocess.run", side_effect=run), + patch("action.context.get_pr_head_sha", return_value=None), + patch("subprocess.run", side_effect=run), ): rc, results, output = self._run_capturing_stdout() self.assertEqual(rc, 0) @@ -602,13 +610,13 @@ def test_pr_author_checks_prefer_the_payload_head_sha(self): """pull_request.head.sha names the tip for either PR event type.""" run, commands = self._fake_git_and_cli(resolves=True) with ( - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", True), - patch("main.AUTHOR_EMAIL_ENABLED", False), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", True), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}), - patch("main.get_pr_head_sha", return_value="deadbeefcafe"), - patch("main.subprocess.run", side_effect=run), + patch("action.context.get_pr_head_sha", return_value="deadbeefcafe"), + patch("subprocess.run", side_effect=run), ): rc, results, output = self._run_capturing_stdout() self.assertEqual(rc, 0) @@ -634,13 +642,13 @@ def test_pr_author_checks_are_skipped_on_a_shallow_clone(self): """HEAD's author is GitHub's merge commit: skip rather than grade it.""" run, commands = self._fake_git_and_cli(resolves=False) with ( - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", True), - patch("main.AUTHOR_NAME_ENABLED", True), - patch("main.AUTHOR_EMAIL_ENABLED", True), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", True), + patch("action.inputs.AUTHOR_NAME_ENABLED", True), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", True), patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.get_pr_head_sha", return_value=None), - patch("main.subprocess.run", side_effect=run), + patch("action.context.get_pr_head_sha", return_value=None), + patch("subprocess.run", side_effect=run), ): rc, results, output = self._run_capturing_stdout() self.assertEqual(rc, 0) @@ -678,13 +686,13 @@ def test_pull_request_target_never_uses_head2(self): """On pull_request_target HEAD is the base branch; HEAD^2 is unrelated.""" run, commands = self._fake_git_and_cli(resolves=True) with ( - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", True), - patch("main.AUTHOR_EMAIL_ENABLED", False), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", True), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}), - patch("main.get_pr_head_sha", return_value=None), - patch("main.subprocess.run", side_effect=run), + patch("action.context.get_pr_head_sha", return_value=None), + patch("subprocess.run", side_effect=run), ): rc, results, output = self._run_capturing_stdout() self.assertEqual(rc, 0) @@ -698,12 +706,12 @@ def test_pull_request_target_never_uses_head2(self): def test_push_author_checks_never_pass_rev(self): run, commands = self._fake_git_and_cli(resolves=True) with ( - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", True), - patch("main.AUTHOR_EMAIL_ENABLED", True), - patch("main.is_pr_event", return_value=False), - patch("main.subprocess.run", side_effect=run), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", True), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", True), + patch("action.context.is_pr_event", return_value=False), + patch("subprocess.run", side_effect=run), ): _rc, _results, output = self._run_capturing_stdout() self.assertFalse([c for c in commands if c[0] == "git"], commands) @@ -730,12 +738,12 @@ class TestStderrIsNotPartOfTheJson(unittest.TestCase): ) def setUp(self): - main._RELAYED_NOTICES.clear() + cli._RELAYED_NOTICES.clear() def test_the_two_streams_are_read_separately(self): mock_result = MagicMock(returncode=0, stdout="{}", stderr="") - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - main.run_check_json(["--branch"]) + with patch("subprocess.run", return_value=mock_result) as mock_run: + cli.run_check_json(["--branch"]) self.assertIs(mock_run.call_args[1]["capture_output"], True) def test_a_notice_does_not_break_the_json(self): @@ -745,23 +753,23 @@ def test_a_notice_does_not_break_the_json(self): stderr=self.NOTICE, ) with ( - patch("main.subprocess.run", return_value=mock_result), + patch("subprocess.run", return_value=mock_result), patch.object(sys, "stderr", io.StringIO()), ): - rc, data, _raw = main.run_check_json(["--branch"]) + rc, data, _raw = cli.run_check_json(["--branch"]) self.assertEqual(rc, 0) self.assertIsNotNone(data) self.assertEqual(data["status"], "pass") # And the scope built from it is a pass, not the "unparsable" fail. - self.assertEqual(main.check_scope("Branch", ["--branch"]).label, "Branch") + self.assertEqual(cli.check_scope("Branch", ["--branch"]).label, "Branch") def test_a_notice_alone_does_not_fail_the_scope(self): mock_result = MagicMock(returncode=0, stdout=json_output(), stderr=self.NOTICE) with ( - patch("main.subprocess.run", return_value=mock_result), + patch("subprocess.run", return_value=mock_result), patch.object(sys, "stderr", io.StringIO()), ): - scope = main.check_scope("Branch", ["--branch"]) + scope = cli.check_scope("Branch", ["--branch"]) self.assertEqual(scope.status, "pass") self.assertEqual(scope.raw_text, "") @@ -771,11 +779,11 @@ def test_notices_reach_the_job_log_once(self): ) fake_err = io.StringIO() with ( - patch("main.subprocess.run", return_value=mock_result), + patch("subprocess.run", return_value=mock_result), patch.object(sys, "stderr", fake_err), ): for _ in range(3): - main.run_check_json(["--branch"]) + cli.run_check_json(["--branch"]) printed = fake_err.getvalue() self.assertIn("--branch requested but no branch rules are configured", printed) # Once, not once per scope and per commit in the pull request. @@ -786,10 +794,10 @@ def test_unparsable_output_keeps_both_streams(self): returncode=2, stdout="", stderr="Error: cchk.toml: Expected ']'\n" ) with ( - patch("main.subprocess.run", return_value=mock_result), + patch("subprocess.run", return_value=mock_result), patch.object(sys, "stderr", io.StringIO()), ): - scope = main.check_scope("Branch", ["--branch"]) + scope = cli.check_scope("Branch", ["--branch"]) self.assertEqual(scope.status, "fail") self.assertIn("Expected ']'", scope.raw_text) @@ -797,8 +805,8 @@ def test_unparsable_output_keeps_both_streams(self): class TestCheckScopeAiTools(unittest.TestCase): def _scope(self, payload): result = MagicMock(returncode=0, stdout=json.dumps(payload), stderr="") - with patch("main.subprocess.run", return_value=result): - return main.check_scope("Commit 1/1", ["--message"]) + with patch("subprocess.run", return_value=result): + return cli.check_scope("Commit 1/1", ["--message"]) def test_reads_the_tools(self): scope = self._scope({"checks": [], "ai_tools": ["Claude Code"]}) @@ -811,27 +819,27 @@ def test_an_older_cli_reports_none(self): class TestRunCommitCheckPrBody(unittest.TestCase): def setUp(self): - main.PR_BODY_AI_TOOLS.clear() - self.addCleanup(main.PR_BODY_AI_TOOLS.clear) + cli.PR_BODY_AI_TOOLS.clear() + self.addCleanup(cli.PR_BODY_AI_TOOLS.clear) def _run(self, pr_body_enabled, ai_label, body="Adds a parser."): - body_scope = main.ScopeResult( + body_scope = model.ScopeResult( label="PR description", checks=[], ai_tools=["OpenAI Codex"] ) with ( - patch("main.PR_TITLE_ENABLED", False), - patch("main.PR_BODY_AI_ATTRIBUTION_ENABLED", pr_body_enabled), + patch("action.inputs.PR_TITLE_ENABLED", False), + patch("action.inputs.PR_BODY_AI_ATTRIBUTION_ENABLED", pr_body_enabled), patch.dict(os.environ, {"AI_LABEL": ai_label}), - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.is_pr_event", return_value=True), - patch("main.get_pr_body", return_value=body), - patch("main.check_scope", return_value=body_scope) as mock_scope, - patch("main.run_other_checks", return_value=[]), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.context.is_pr_event", return_value=True), + patch("action.context.get_pr_body", return_value=body), + patch("action.cli.check_scope", return_value=body_scope) as mock_scope, + patch("action.cli.run_other_checks", return_value=[]), ): - _rc, results = main.run_commit_check() + _rc, results = cli.run_commit_check() return results, mock_scope def test_pr_body_is_a_scope_checked_with_the_ai_rules_only(self): @@ -845,22 +853,22 @@ def test_no_ai_rule_ran_reads_as_skipped_not_passed(self): """Under ai_attribution = "ignore" the CLI runs no rule on the description.""" results, _ = self._run(True, "false") self.assertEqual(results[0].status, "skip") - self.assertEqual(results[0].skip_reason, main.AI_POLICY_IGNORED) + self.assertEqual(results[0].skip_reason, cli.AI_POLICY_IGNORED) def test_a_rule_that_ran_keeps_its_verdict(self): checks = [{"rule_id": "CC013", "check": "ai_attribution", "status": "pass"}] - scope = main.ScopeResult(label="PR description", checks=list(checks)) - self.assertEqual(main.skip_when_no_ai_rule_ran(scope).checks, checks) + scope = model.ScopeResult(label="PR description", checks=list(checks)) + self.assertEqual(cli.skip_when_no_ai_rule_ran(scope).checks, checks) def test_unparsable_output_still_fails(self): - scope = main.ScopeResult(label="PR description", raw_text="Error: bad config") - self.assertEqual(main.skip_when_no_ai_rule_ran(scope).status, "fail") + scope = model.ScopeResult(label="PR description", raw_text="Error: bad config") + self.assertEqual(cli.skip_when_no_ai_rule_ran(scope).status, "fail") def test_ai_label_alone_reads_it_but_reports_no_scope(self): results, mock_scope = self._run(False, "true") mock_scope.assert_called_once() self.assertEqual(results, []) - self.assertEqual(main.PR_BODY_AI_TOOLS, ["OpenAI Codex"]) + self.assertEqual(cli.PR_BODY_AI_TOOLS, ["OpenAI Codex"]) def test_off_by_default(self): results, mock_scope = self._run(False, "false") @@ -885,10 +893,10 @@ class TestDescriptionLineChanges(unittest.TestCase): BODY = "## Summary\nAdds a parser.\n\nLink to Devin run: https://app.devin.ai/sessions/1\n" def _scope(self, *checks): - return main.ScopeResult(label="PR description", checks=list(checks)) + return model.ScopeResult(label="PR description", checks=list(checks)) def test_lines_removed_keeps_order_and_counts_copies(self): - self.assertEqual(main.lines_removed("a\nb\na\n\nc", "a\nc"), ["b", "a"]) + self.assertEqual(cli.lines_removed("a\nb\na\n\nc", "a\nc"), ["b", "a"]) def test_forbid_names_the_line_to_delete(self): scope = self._scope( @@ -898,7 +906,7 @@ def test_forbid_names_the_line_to_delete(self): "fix": "## Summary\nAdds a parser.", } ) - main.name_the_line_changes(scope, self.BODY) + cli.name_the_line_changes(scope, self.BODY) self.assertEqual( scope.checks[0]["suggest"], 'In the description, remove "Link to Devin run: https://app.devin.ai/sessions/1"', @@ -920,7 +928,7 @@ def test_disclose_names_the_line_to_add_and_the_one_it_replaces(self): }, {"rule_id": "CC014", "suggest": "x", "fix": body + "\nAssisted-by: Claude"}, ) - main.name_the_line_changes(scope, body) + cli.name_the_line_changes(scope, body) self.assertEqual( [c["suggest"] for c in scope.checks], [ @@ -937,7 +945,7 @@ def test_a_check_without_a_fix_or_a_change_is_left_alone(self): {"rule_id": "CC013", "suggest": "s", "fix": ""}, {"rule_id": "CC013", "suggest": "s", "fix": "same"}, ) - main.name_the_line_changes(scope, "same") + cli.name_the_line_changes(scope, "same") self.assertEqual( scope.checks, [ @@ -956,16 +964,16 @@ def test_run_names_the_lines_for_a_reported_description(self): } ) with ( - patch("main.PR_TITLE_ENABLED", False), - patch("main.PR_BODY_AI_ATTRIBUTION_ENABLED", True), + patch("action.inputs.PR_TITLE_ENABLED", False), + patch("action.inputs.PR_BODY_AI_ATTRIBUTION_ENABLED", True), patch.dict(os.environ, {"AI_LABEL": "false"}), - patch("main.MESSAGE_ENABLED", False), - patch("main.is_pr_event", return_value=True), - patch("main.get_pr_body", return_value=self.BODY), - patch("main.check_scope", return_value=scope), - patch("main.run_other_checks", return_value=[]), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.context.is_pr_event", return_value=True), + patch("action.context.get_pr_body", return_value=self.BODY), + patch("action.cli.check_scope", return_value=scope), + patch("action.cli.run_other_checks", return_value=[]), ): - _rc, results = main.run_commit_check() + _rc, results = cli.run_commit_check() self.assertEqual(results[0].checks[0]["fix"], "") @@ -973,8 +981,8 @@ class TestPrAuthorChecksEveryCommit(unittest.TestCase): """The author checks read every PR commit's author, not only the tip.""" def setUp(self): - main.API_AUTHORS.clear() - self.addCleanup(main.API_AUTHORS.clear) + context.API_AUTHORS.clear() + self.addCleanup(context.API_AUTHORS.clear) def _run(self, commits, authors, resolves=True, message=False): commands: list[list[str]] = [] @@ -998,18 +1006,22 @@ def run(command, **_kwargs): ) with ( - patch("main.MESSAGE_ENABLED", message), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", True), + patch("action.inputs.MESSAGE_ENABLED", message), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", True), patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.get_pr_commit_messages", return_value=commits) as listed, - patch("main._local_author", side_effect=lambda sha: authors.get(sha)), - patch("main.get_pr_head_sha", return_value=commits[-1][0]), - patch("main.subprocess.run", side_effect=run), + patch( + "action.context.get_pr_commit_messages", return_value=commits + ) as listed, + patch( + "action.context._local_author", side_effect=lambda sha: authors.get(sha) + ), + patch("action.context.get_pr_head_sha", return_value=commits[-1][0]), + patch("subprocess.run", side_effect=run), patch("sys.stdout", io.StringIO()), ): - rc, results = main.run_commit_check() + rc, results = cli.run_commit_check() self.listed_calls = listed.call_count return rc, results, commands @@ -1054,7 +1066,7 @@ def test_one_author_is_checked_once_on_the_newest_commit(self): self.assertEqual([(s.label, s.sha) for s in results], [("Author email", "c3")]) def test_an_api_listed_author_is_used(self): - main.API_AUTHORS["a1"] = ("Dev", "dev@users.noreply.github.com") + context.API_AUTHORS["a1"] = ("Dev", "dev@users.noreply.github.com") _rc, results, _ = self._run( [("a1", "feat: one")], {"a1": ("Dev", "dev@users.noreply.github.com")} ) @@ -1089,10 +1101,10 @@ def run(command, **kwargs): ) with ( - patch("main.subprocess.run", side_effect=run), - patch("main._local_author", return_value=None), + patch("subprocess.run", side_effect=run), + patch("action.context._local_author", return_value=None), ): - results = main.run_pr_message_checks([("a1", "")]) + results = cli.run_pr_message_checks([("a1", "")]) command, piped, content = seen[0] self.assertEqual(command[:4], ["commit-check", "--format", "json", "--message"]) self.assertIsNone(piped) @@ -1113,8 +1125,8 @@ def test_a_shallow_clone_lists_them_in_its_shallow_file(self): with open(path, "w", encoding="utf-8") as f: f.write(f"{SHA_A}\n{SHA_B}\n") located = MagicMock(returncode=0, stdout=f"{path}\n") - with patch("main.subprocess.run", return_value=located) as run: - self.assertEqual(main._shallow_boundary(), {SHA_A, SHA_B}) + with patch("subprocess.run", return_value=located) as run: + self.assertEqual(cli._shallow_boundary(), {SHA_A, SHA_B}) self.assertEqual( run.call_args.args[0], ["git", "rev-parse", "--git-path", "shallow"] ) @@ -1122,16 +1134,16 @@ def test_a_shallow_clone_lists_them_in_its_shallow_file(self): def test_a_complete_clone_has_no_such_file(self): with tempfile.TemporaryDirectory() as tmp: located = MagicMock(returncode=0, stdout=os.path.join(tmp, "shallow")) - with patch("main.subprocess.run", return_value=located): - self.assertEqual(main._shallow_boundary(), set()) + with patch("subprocess.run", return_value=located): + self.assertEqual(cli._shallow_boundary(), set()) def test_outside_a_repository_there_is_none(self): - with patch("main.subprocess.run", return_value=MagicMock(returncode=128)): - self.assertEqual(main._shallow_boundary(), set()) + with patch("subprocess.run", return_value=MagicMock(returncode=128)): + self.assertEqual(cli._shallow_boundary(), set()) def test_without_git_there_is_none(self): - with patch("main.subprocess.run", side_effect=OSError("no git")): - self.assertEqual(main._shallow_boundary(), set()) + with patch("subprocess.run", side_effect=OSError("no git")): + self.assertEqual(cli._shallow_boundary(), set()) class TestRunFilesChecks(unittest.TestCase): @@ -1145,17 +1157,20 @@ def check_scope(label, args, sha=""): calls.append(args) answer = answers.get(args[-1], []) if isinstance(answer, str): - return main.ScopeResult(label=label, raw_text=answer, sha=sha) - return main.ScopeResult(label=label, checks=list(answer), sha=sha) + return model.ScopeResult(label=label, raw_text=answer, sha=sha) + return model.ScopeResult(label=label, checks=list(answer), sha=sha) out = io.StringIO() with ( - patch("main._shallow_boundary", return_value=set(boundary)), - patch("main._rev_resolves", side_effect=lambda sha: sha not in missing), - patch("main.check_scope", side_effect=check_scope), + patch("action.cli._shallow_boundary", return_value=set(boundary)), + patch( + "action.context._rev_resolves", + side_effect=lambda sha: sha not in missing, + ), + patch("action.cli.check_scope", side_effect=check_scope), patch("sys.stdout", out), ): - results = main.run_files_checks(shas) + results = cli.run_files_checks(shas) return results, calls, out.getvalue() def test_every_commit_is_checked_at_its_own_revision(self): @@ -1183,8 +1198,8 @@ def test_a_commit_without_its_parent_is_skipped_not_guessed_at(self): self.assertEqual( [(s.sha, s.status, s.skip_reason) for s in results], [ - ("a1", "skip", main.FILES_NOT_IN_CLONE), - ("b2", "skip", main.FILES_NOT_IN_CLONE), + ("a1", "skip", cli.FILES_NOT_IN_CLONE), + ("b2", "skip", cli.FILES_NOT_IN_CLONE), ("c3", "pass", ""), ], ) @@ -1203,7 +1218,7 @@ def test_a_checkout_with_none_of_them_gets_one_skipped_scope(self): self.assertEqual(calls, [["--files"]]) self.assertEqual( [(s.label, s.sha, s.status, s.skip_reason) for s in results], - [("Files", "", "skip", main.FILES_NOT_IN_CLONE)], + [("Files", "", "skip", cli.FILES_NOT_IN_CLONE)], ) self.assertIn("the files check was skipped", out) @@ -1211,14 +1226,14 @@ def test_an_unknown_head_is_not_checked(self): """Outside a PR the one commit is HEAD; git may fail to name it.""" results, calls, _out = self._run([""], {"--files": "boom"}) self.assertEqual(calls, [["--files"]]) - self.assertEqual(results[0].skip_reason, main.FILES_NOT_IN_CLONE) + self.assertEqual(results[0].skip_reason, cli.FILES_NOT_IN_CLONE) def test_no_rule_set_is_one_skipped_scope_and_no_shallow_warning(self): for missing in ([], ["a1", "b2"]): results, _calls, out = self._run(["a1", "b2"], {}, missing=missing) self.assertEqual( [(s.label, s.sha, s.status, s.skip_reason) for s in results], - [("Files", "", "skip", main.FILES_UNCONFIGURED)], + [("Files", "", "skip", cli.FILES_UNCONFIGURED)], ) self.assertEqual(out, "") @@ -1227,7 +1242,7 @@ def test_a_commit_that_changes_no_file_says_so(self): skipped["reason"] = "" results, _calls, _out = self._run(["a1"], {"a1": [skipped]}) self.assertEqual(results[0].status, "skip") - self.assertEqual(results[0].skip_reason, main.FILES_NOTHING_CHANGED) + self.assertEqual(results[0].skip_reason, cli.FILES_NOTHING_CHANGED) def test_the_clis_own_skip_reason_is_kept(self): skipped = files_pass(value="", status="skip") @@ -1243,18 +1258,18 @@ def test_unparsable_output_is_a_failure_of_that_commit(self): def test_a_pull_request_whose_commits_cannot_be_listed_is_skipped(self): out = io.StringIO() - with patch("sys.stdout", out), patch("main.check_scope") as check: - results = main.run_pr_files_checks([]) + with patch("sys.stdout", out), patch("action.cli.check_scope") as check: + results = cli.run_pr_files_checks([]) check.assert_not_called() self.assertEqual( [(s.label, s.status, s.skip_reason) for s in results], - [("Files", "skip", main.FILES_UNLISTED)], + [("Files", "skip", cli.FILES_UNLISTED)], ) self.assertIn("Could not list the pull request's commits", out.getvalue()) def test_a_pull_request_hands_over_its_commits(self): - with patch("main.run_files_checks", return_value=[]) as run: - main.run_pr_files_checks([("a1", "feat: one"), ("b2", "feat: two")]) + with patch("action.cli.run_files_checks", return_value=[]) as run: + cli.run_pr_files_checks([("a1", "feat: one"), ("b2", "feat: two")]) run.assert_called_once_with(["a1", "b2"]) @@ -1265,30 +1280,32 @@ def _run(self, event="pull_request", message=True, files=True): commits = [("a1", "feat: one"), ("b2", "feat: two")] if listable else [] def check_scope(label, args, **kwargs): - return main.ScopeResult( + return model.ScopeResult( label=label, checks=[files_pass()], sha=kwargs.get("sha", "") ) with ( - patch("main.MESSAGE_ENABLED", message), - patch("main.BRANCH_ENABLED", True), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), - patch("main.FILES_ENABLED", files), + patch("action.inputs.MESSAGE_ENABLED", message), + patch("action.inputs.BRANCH_ENABLED", True), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), + patch("action.inputs.FILES_ENABLED", files), patch.dict(os.environ, {"GITHUB_EVENT_NAME": event}), - patch("main.get_pr_commit_messages", return_value=commits) as listed, - patch("main._local_author", return_value=None), - patch("main._shallow_boundary", return_value=set()), - patch("main._rev_resolves", return_value=True), - patch("main.head_sha", return_value="h0"), - patch("main.check_scope", side_effect=check_scope), + patch( + "action.context.get_pr_commit_messages", return_value=commits + ) as listed, + patch("action.context._local_author", return_value=None), + patch("action.cli._shallow_boundary", return_value=set()), + patch("action.context._rev_resolves", return_value=True), + patch("action.context.head_sha", return_value="h0"), + patch("action.cli.check_scope", side_effect=check_scope), ): - _rc, results = main.run_commit_check() + _rc, results = cli.run_commit_check() self.listed_calls = listed.call_count return [(s.label, s.sha) for s in results] def test_off_by_default(self): - self.assertFalse(main.FILES_ENABLED) + self.assertFalse(inputs.FILES_ENABLED) self.assertNotIn("Files", [label for label, _ in self._run(files=False)]) def test_a_pull_request_gets_one_scope_per_commit_after_the_messages(self): diff --git a/tests/context_test.py b/tests/context_test.py index a789632..91f43ab 100644 --- a/tests/context_test.py +++ b/tests/context_test.py @@ -11,7 +11,7 @@ from helpers import SHA_A, SHA_B -import main +from action import context #: ``git log`` output in COMMIT_LOG_FORMAT for two commits: hash, NUL, message #: (with its trailing newline), NUL, then git's own newline before the next. @@ -20,37 +20,37 @@ class TestParseCommitMessages(unittest.TestCase): def test_splits_messages_and_trims_surrounding_newlines(self): - result = main.parse_commit_messages( + result = context.parse_commit_messages( f"{SHA_A}\x00\nfix: first\n\x00\n{SHA_B}\x00\nfeat: second\n\n\x00" ) self.assertEqual(result, [(SHA_A, "fix: first"), (SHA_B, "feat: second")]) def test_real_git_log_layout(self): self.assertEqual( - main.parse_commit_messages(TWO_COMMITS_LOG), + context.parse_commit_messages(TWO_COMMITS_LOG), [(SHA_A, "fix: first"), (SHA_B, "feat: second")], ) def test_the_format_asks_git_for_the_hash_and_the_body(self): """A literal NUL cannot be an argument; git spells it %x00.""" - self.assertEqual(main.COMMIT_LOG_FORMAT, "--pretty=format:%H%x00%B%x00") - self.assertNotIn("\x00", main.COMMIT_LOG_FORMAT) + self.assertEqual(context.COMMIT_LOG_FORMAT, "--pretty=format:%H%x00%B%x00") + self.assertNotIn("\x00", context.COMMIT_LOG_FORMAT) def test_an_empty_message_is_kept_and_does_not_shift_the_hashes(self): output = f"{SHA_A}\x00\n\x00\n{SHA_B}\x00feat: second\n\x00" self.assertEqual( - main.parse_commit_messages(output), + context.parse_commit_messages(output), [(SHA_A, ""), (SHA_B, "feat: second")], ) def test_empty_output_is_no_commits(self): - self.assertEqual(main.parse_commit_messages(""), []) + self.assertEqual(context.parse_commit_messages(""), []) class TestGetPrTitle(unittest.TestCase): def test_non_pr_event_returns_none(self): with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "push"}): - self.assertIsNone(main.get_pr_title()) + self.assertIsNone(context.get_pr_title()) def test_pr_event_returns_title(self): event = { @@ -65,7 +65,7 @@ def test_pr_event_returns_title(self): {"GITHUB_EVENT_NAME": "pull_request", "GITHUB_EVENT_PATH": event_path}, ), ): - self.assertEqual(main.get_pr_title(), "feat: add login page") + self.assertEqual(context.get_pr_title(), "feat: add login page") os.unlink(event_path) def test_pull_request_target_event(self): @@ -84,14 +84,14 @@ def test_pull_request_target_event(self): }, ), ): - self.assertEqual(main.get_pr_title(), "fix: resolve timeout") + self.assertEqual(context.get_pr_title(), "fix: resolve timeout") os.unlink(event_path) def test_missing_event_path_returns_none(self): with patch.dict(os.environ, {}, clear=True): os.environ["GITHUB_EVENT_NAME"] = "pull_request" os.environ.pop("GITHUB_EVENT_PATH", None) - self.assertIsNone(main.get_pr_title()) + self.assertIsNone(context.get_pr_title()) def test_invalid_json_returns_none(self): with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f: @@ -104,7 +104,7 @@ def test_invalid_json_returns_none(self): ), patch("builtins.print"), ): - self.assertIsNone(main.get_pr_title()) + self.assertIsNone(context.get_pr_title()) os.unlink(event_path) @@ -113,9 +113,9 @@ class TestLocalAuthor(unittest.TestCase): def test_reads_name_and_email(self): result = MagicMock(returncode=0, stdout="Jane Dev\x1fjane@example.com\n") - with patch("main.subprocess.run", return_value=result) as mock_run: + with patch("subprocess.run", return_value=result) as mock_run: self.assertEqual( - main._local_author(SHA_A), ("Jane Dev", "jane@example.com") + context._local_author(SHA_A), ("Jane Dev", "jane@example.com") ) self.assertEqual( mock_run.call_args[0][0], @@ -124,17 +124,17 @@ def test_reads_name_and_email(self): def test_a_commit_git_cannot_show_has_no_author(self): result = MagicMock(returncode=128, stdout="") - with patch("main.subprocess.run", return_value=result): - self.assertIsNone(main._local_author(SHA_A)) + with patch("subprocess.run", return_value=result): + self.assertIsNone(context._local_author(SHA_A)) def test_output_without_the_separator_has_no_author(self): result = MagicMock(returncode=0, stdout="unexpected\n") - with patch("main.subprocess.run", return_value=result): - self.assertIsNone(main._local_author(SHA_A)) + with patch("subprocess.run", return_value=result): + self.assertIsNone(context._local_author(SHA_A)) def test_missing_git_has_no_author(self): - with patch("main.subprocess.run", side_effect=OSError("no git")): - self.assertIsNone(main._local_author(SHA_A)) + with patch("subprocess.run", side_effect=OSError("no git")): + self.assertIsNone(context._local_author(SHA_A)) def test_reads_a_real_commit(self): with tempfile.TemporaryDirectory() as repo: @@ -165,7 +165,7 @@ def test_reads_a_real_commit(self): cwd = os.getcwd() os.chdir(repo) try: - author = main._local_author(sha) + author = context._local_author(sha) finally: os.chdir(cwd) self.assertEqual(author, ("Renovate Bot", "bot@renovateapp.com")) @@ -174,26 +174,26 @@ def test_reads_a_real_commit(self): class TestGetPrCommitMessages(unittest.TestCase): def setUp(self): # Never the event of whatever CI run the tests happen to be in. - patcher = patch("main.get_pr_event", return_value={}) + patcher = patch("action.context.get_pr_event", return_value={}) patcher.start() self.addCleanup(patcher.stop) def test_non_pr_event_returns_empty(self): with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "push"}): - result = main.get_pr_commit_messages() + result = context.get_pr_commit_messages() self.assertEqual(result, []) def test_event_range_is_preferred(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), patch( - "main.get_messages_from_event_range", + "action.context.get_messages_from_event_range", return_value=["fix: first", "feat: second"], ) as mock_range, - patch("main.get_messages_from_merge_ref") as mock_merge, - patch("main.get_messages_from_head_ref") as mock_head, + patch("action.context.get_messages_from_merge_ref") as mock_merge, + patch("action.context.get_messages_from_head_ref") as mock_head, ): - result = main.get_pr_commit_messages() + result = context.get_pr_commit_messages() self.assertEqual(result, ["fix: first", "feat: second"]) mock_range.assert_called_once() mock_merge.assert_not_called() @@ -202,14 +202,14 @@ def test_event_range_is_preferred(self): def test_merge_ref_is_next(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.get_messages_from_event_range", return_value=[]), + patch("action.context.get_messages_from_event_range", return_value=[]), patch( - "main.get_messages_from_merge_ref", + "action.context.get_messages_from_merge_ref", return_value=["fix: first", "feat: second"], ) as mock_merge, - patch("main.get_messages_from_head_ref") as mock_head, + patch("action.context.get_messages_from_head_ref") as mock_head, ): - result = main.get_pr_commit_messages() + result = context.get_pr_commit_messages() self.assertEqual(result, ["fix: first", "feat: second"]) mock_merge.assert_called_once() mock_head.assert_not_called() @@ -217,21 +217,27 @@ def test_merge_ref_is_next(self): def test_pull_request_target_is_supported(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}), - patch("main.get_messages_from_event_range", return_value=["fix: first"]), + patch( + "action.context.get_messages_from_event_range", + return_value=["fix: first"], + ), ): - result = main.get_pr_commit_messages() + result = context.get_pr_commit_messages() self.assertEqual(result, ["fix: first"]) def test_a_range_cut_short_by_a_shallow_clone_asks_the_api(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.get_messages_from_event_range", return_value=[("b2", "fix")]), - patch("main.get_pr_event", return_value={"commits": 2}), - patch("main.get_messages_from_api", return_value=[]) as api, - patch("main.warn_shallow_checkout") as warn, + patch( + "action.context.get_messages_from_event_range", + return_value=[("b2", "fix")], + ), + patch("action.context.get_pr_event", return_value={"commits": 2}), + patch("action.context.get_messages_from_api", return_value=[]) as api, + patch("action.context.warn_shallow_checkout") as warn, ): # The API cannot help either: check what the clone had, and say so. - self.assertEqual(main.get_pr_commit_messages(), [("b2", "fix")]) + self.assertEqual(context.get_pr_commit_messages(), [("b2", "fix")]) api.assert_called_once() self.assertIn("Only 1 of the pull request's 2 commits", warn.call_args[0][0]) @@ -241,12 +247,15 @@ def test_asks_the_api_when_the_clone_holds_none_of_them(self): os.environ, {"GITHUB_EVENT_NAME": "pull_request", "GITHUB_BASE_REF": "main"}, ), - patch("main.get_messages_from_event_range", return_value=[]), - patch("main.get_messages_from_merge_ref", return_value=[]), - patch("main.get_messages_from_head_ref", return_value=[]), - patch("main.get_messages_from_api", return_value=[("a1", "feat: one")]), + patch("action.context.get_messages_from_event_range", return_value=[]), + patch("action.context.get_messages_from_merge_ref", return_value=[]), + patch("action.context.get_messages_from_head_ref", return_value=[]), + patch( + "action.context.get_messages_from_api", + return_value=[("a1", "feat: one")], + ), ): - self.assertEqual(main.get_pr_commit_messages(), [("a1", "feat: one")]) + self.assertEqual(context.get_pr_commit_messages(), [("a1", "feat: one")]) def test_nothing_listed_anywhere_is_empty_and_not_warned_here(self): """With no partial list there is no "only N of M" to report; the @@ -256,13 +265,13 @@ def test_nothing_listed_anywhere_is_empty_and_not_warned_here(self): os.environ, {"GITHUB_EVENT_NAME": "pull_request", "GITHUB_BASE_REF": ""}, ), - patch("main.get_messages_from_event_range", return_value=[]), - patch("main.get_messages_from_merge_ref", return_value=[]), - patch("main.get_messages_from_head_ref") as mock_head, - patch("main.get_messages_from_api", return_value=[]) as api, - patch("main.warn_shallow_checkout") as warn, + patch("action.context.get_messages_from_event_range", return_value=[]), + patch("action.context.get_messages_from_merge_ref", return_value=[]), + patch("action.context.get_messages_from_head_ref") as mock_head, + patch("action.context.get_messages_from_api", return_value=[]) as api, + patch("action.context.warn_shallow_checkout") as warn, ): - self.assertEqual(main.get_pr_commit_messages(), []) + self.assertEqual(context.get_pr_commit_messages(), []) # No base ref to diff against, so the head-ref reader is never asked. mock_head.assert_not_called() api.assert_called_once() @@ -277,14 +286,14 @@ def test_falls_back_to_base_ref_when_merge_ref_is_unavailable(self): "GITHUB_BASE_REF": "main", }, ), - patch("main.get_messages_from_event_range", return_value=[]), - patch("main.get_messages_from_merge_ref", return_value=[]), + patch("action.context.get_messages_from_event_range", return_value=[]), + patch("action.context.get_messages_from_merge_ref", return_value=[]), patch( - "main.get_messages_from_head_ref", + "action.context.get_messages_from_head_ref", return_value=["fix: first", "feat: second"], ) as mock_head, ): - result = main.get_pr_commit_messages() + result = context.get_pr_commit_messages() self.assertEqual(result, ["fix: first", "feat: second"]) mock_head.assert_called_once_with("main") @@ -292,11 +301,11 @@ def test_exception_returns_empty(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), patch( - "main.get_messages_from_event_range", + "action.context.get_messages_from_event_range", side_effect=Exception("git failed"), ), ): - result = main.get_pr_commit_messages() + result = context.get_pr_commit_messages() self.assertEqual(result, []) @@ -305,22 +314,22 @@ def test_get_messages_from_merge_ref(self): mock_result = MagicMock(returncode=0, stdout=TWO_COMMITS_LOG) with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.subprocess.run", return_value=mock_result) as mock_run, + patch("subprocess.run", return_value=mock_result) as mock_run, ): - result = main.get_messages_from_merge_ref() + result = context.get_messages_from_merge_ref() self.assertEqual(result, [(SHA_A, "fix: first"), (SHA_B, "feat: second")]) self.assertEqual( mock_run.call_args[0][0], - ["git", "log", main.COMMIT_LOG_FORMAT, "--reverse", "HEAD^1..HEAD^2"], + ["git", "log", context.COMMIT_LOG_FORMAT, "--reverse", "HEAD^1..HEAD^2"], ) def test_merge_ref_is_never_read_on_pull_request_target(self): """HEAD is the base branch there; HEAD^2 belongs to some other merge.""" with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}), - patch("main.subprocess.run") as mock_run, + patch("subprocess.run") as mock_run, ): - self.assertEqual(main.get_messages_from_merge_ref(), []) + self.assertEqual(context.get_messages_from_merge_ref(), []) mock_run.assert_not_called() def test_get_messages_from_event_range(self): @@ -333,49 +342,49 @@ def run(command, **_kwargs): return MagicMock(returncode=0, stdout=TWO_COMMITS_LOG) with ( - patch("main.get_pr_base_sha", return_value="base111"), - patch("main.get_pr_head_sha", return_value="head222"), - patch("main.subprocess.run", side_effect=run), + patch("action.context.get_pr_base_sha", return_value="base111"), + patch("action.context.get_pr_head_sha", return_value="head222"), + patch("subprocess.run", side_effect=run), ): - result = main.get_messages_from_event_range() + result = context.get_messages_from_event_range() self.assertEqual(result, [(SHA_A, "fix: first"), (SHA_B, "feat: second")]) self.assertIn( - ["git", "log", main.COMMIT_LOG_FORMAT, "--reverse", "base111..head222"], + ["git", "log", context.COMMIT_LOG_FORMAT, "--reverse", "base111..head222"], commands, ) def test_event_range_needs_both_commits_in_the_clone(self): with ( - patch("main.get_pr_base_sha", return_value="base111"), - patch("main.get_pr_head_sha", return_value="head222"), - patch("main.subprocess.run", return_value=MagicMock(returncode=1)), + patch("action.context.get_pr_base_sha", return_value="base111"), + patch("action.context.get_pr_head_sha", return_value="head222"), + patch("subprocess.run", return_value=MagicMock(returncode=1)), ): - self.assertEqual(main.get_messages_from_event_range(), []) + self.assertEqual(context.get_messages_from_event_range(), []) def test_event_range_without_a_payload_is_empty(self): with ( - patch("main.get_pr_base_sha", return_value=None), - patch("main.get_pr_head_sha", return_value=None), - patch("main.subprocess.run") as mock_run, + patch("action.context.get_pr_base_sha", return_value=None), + patch("action.context.get_pr_head_sha", return_value=None), + patch("subprocess.run") as mock_run, ): - self.assertEqual(main.get_messages_from_event_range(), []) + self.assertEqual(context.get_messages_from_event_range(), []) mock_run.assert_not_called() def test_a_failing_git_log_yields_no_messages(self): - with patch("main.subprocess.run", return_value=MagicMock(returncode=128)): - self.assertEqual(main.get_messages_from_head_ref("main"), []) + with patch("subprocess.run", return_value=MagicMock(returncode=128)): + self.assertEqual(context.get_messages_from_head_ref("main"), []) def test_get_messages_from_head_ref(self): mock_result = MagicMock(returncode=0, stdout=f"{SHA_A}\x00fix: first\n\x00") - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - result = main.get_messages_from_head_ref("main") + with patch("subprocess.run", return_value=mock_result) as mock_run: + result = context.get_messages_from_head_ref("main") self.assertEqual(result, [(SHA_A, "fix: first")]) self.assertEqual( mock_run.call_args[0][0], [ "git", "log", - main.COMMIT_LOG_FORMAT, + context.COMMIT_LOG_FORMAT, "--reverse", "origin/main..HEAD", ], @@ -385,28 +394,26 @@ def test_get_messages_from_head_ref(self): class TestHeadSha(unittest.TestCase): def test_returns_the_full_hash(self): mock_result = MagicMock(returncode=0, stdout=f"{SHA_A}\n") - with patch("main.subprocess.run", return_value=mock_result) as mock_run: - self.assertEqual(main.head_sha(), SHA_A) + with patch("subprocess.run", return_value=mock_result) as mock_run: + self.assertEqual(context.head_sha(), SHA_A) self.assertEqual(mock_run.call_args[0][0], ["git", "rev-parse", "HEAD"]) def test_no_head_is_empty(self): - with patch("main.subprocess.run", return_value=MagicMock(returncode=128)): - self.assertEqual(main.head_sha(), "") + with patch("subprocess.run", return_value=MagicMock(returncode=128)): + self.assertEqual(context.head_sha(), "") def test_missing_git_is_empty(self): - with patch("main.subprocess.run", side_effect=OSError("no git")): - self.assertEqual(main.head_sha(), "") + with patch("subprocess.run", side_effect=OSError("no git")): + self.assertEqual(context.head_sha(), "") class TestPrHeadRev(unittest.TestCase): def test_payload_head_sha_wins_when_the_clone_has_it(self): with ( - patch("main.get_pr_head_sha", return_value="abc123"), - patch( - "main.subprocess.run", return_value=MagicMock(returncode=0) - ) as mock_run, + patch("action.context.get_pr_head_sha", return_value="abc123"), + patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_run, ): - self.assertEqual(main.pr_head_rev(), "abc123") + self.assertEqual(context.pr_head_rev(), "abc123") self.assertEqual( mock_run.call_args[0][0], ["git", "rev-parse", "--verify", "--quiet", "abc123^{commit}"], @@ -415,12 +422,10 @@ def test_payload_head_sha_wins_when_the_clone_has_it(self): def test_pull_request_falls_back_to_head2(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.get_pr_head_sha", return_value=None), - patch( - "main.subprocess.run", return_value=MagicMock(returncode=0) - ) as mock_run, + patch("action.context.get_pr_head_sha", return_value=None), + patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_run, ): - self.assertEqual(main.pr_head_rev(), "HEAD^2") + self.assertEqual(context.pr_head_rev(), "HEAD^2") self.assertEqual( mock_run.call_args[0][0], ["git", "rev-parse", "--verify", "--quiet", "HEAD^2^{commit}"], @@ -429,37 +434,35 @@ def test_pull_request_falls_back_to_head2(self): def test_pull_request_target_does_not_fall_back_to_head2(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}), - patch("main.get_pr_head_sha", return_value=None), - patch( - "main.subprocess.run", return_value=MagicMock(returncode=0) - ) as mock_run, + patch("action.context.get_pr_head_sha", return_value=None), + patch("subprocess.run", return_value=MagicMock(returncode=0)) as mock_run, ): - self.assertIsNone(main.pr_head_rev()) + self.assertIsNone(context.pr_head_rev()) mock_run.assert_not_called() def test_unfetched_payload_sha_on_pull_request_target_returns_none(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}), - patch("main.get_pr_head_sha", return_value="abc123"), - patch("main.subprocess.run", return_value=MagicMock(returncode=1)), + patch("action.context.get_pr_head_sha", return_value="abc123"), + patch("subprocess.run", return_value=MagicMock(returncode=1)), ): - self.assertIsNone(main.pr_head_rev()) + self.assertIsNone(context.pr_head_rev()) def test_shallow_clone_returns_none(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.get_pr_head_sha", return_value=None), - patch("main.subprocess.run", return_value=MagicMock(returncode=1)), + patch("action.context.get_pr_head_sha", return_value=None), + patch("subprocess.run", return_value=MagicMock(returncode=1)), ): - self.assertIsNone(main.pr_head_rev()) + self.assertIsNone(context.pr_head_rev()) def test_missing_git_returns_none(self): with ( patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}), - patch("main.get_pr_head_sha", return_value=None), - patch("main.subprocess.run", side_effect=OSError("no git")), + patch("action.context.get_pr_head_sha", return_value=None), + patch("subprocess.run", side_effect=OSError("no git")), ): - self.assertIsNone(main.pr_head_rev()) + self.assertIsNone(context.pr_head_rev()) class TestFetchPrHead(unittest.TestCase): @@ -473,18 +476,18 @@ def test_a_head_the_clone_lacks_is_fetched_without_history(self): ] ) with ( - patch("main.get_pr_head_sha", return_value="abc123"), - patch("main.subprocess.run", run), + patch("action.context.get_pr_head_sha", return_value="abc123"), + patch("subprocess.run", run), ): - self.assertEqual(main.pr_head_rev(), "abc123") + self.assertEqual(context.pr_head_rev(), "abc123") self.assertEqual( run.call_args_list[1][0][0], ["git", "fetch", "--no-tags", "--quiet", "--depth=1", "origin", "abc123"], ) def test_a_fetch_without_git_gives_up(self): - with patch("main.subprocess.run", side_effect=OSError("no git")): - self.assertFalse(main._fetch_commit("abc123")) + with patch("subprocess.run", side_effect=OSError("no git")): + self.assertFalse(context._fetch_commit("abc123")) class TestGetMessagesFromApi(unittest.TestCase): @@ -513,11 +516,14 @@ def _run(self, total, api_commits, head="b2"): } with ( patch.dict(os.environ, env), - patch("main.get_pr_event", return_value={"number": 7, "commits": total}), - patch("main.get_pr_head_sha", return_value=head), + patch( + "action.context.get_pr_event", + return_value={"number": 7, "commits": total}, + ), + patch("action.context.get_pr_head_sha", return_value=head), patch.dict(sys.modules, {"github": github_module}), ): - return main.get_messages_from_api(), github_module + return context.get_messages_from_api(), github_module def test_lists_the_commits_oldest_first(self): commits = [("a1", "feat: one"), ("b2", "fix: two")] @@ -529,11 +535,11 @@ def test_lists_the_commits_oldest_first(self): ) def test_records_each_commit_author(self): - main.API_AUTHORS.clear() - self.addCleanup(main.API_AUTHORS.clear) + context.API_AUTHORS.clear() + self.addCleanup(context.API_AUTHORS.clear) self._run(2, [("a1", "feat: one"), ("b2", "fix: two")]) self.assertEqual( - main.API_AUTHORS, + context.API_AUTHORS, { "a1": ("author a1", "a1@example.com"), "b2": ("author b2", "b2@example.com"), @@ -541,8 +547,8 @@ def test_records_each_commit_author(self): ) def test_a_commit_without_an_author_records_nothing(self): - main.API_AUTHORS.clear() - self.addCleanup(main.API_AUTHORS.clear) + context.API_AUTHORS.clear() + self.addCleanup(context.API_AUTHORS.clear) pull = MagicMock() pull.get_commits.return_value = [ MagicMock(sha="b2", commit=MagicMock(message="fix: two", author=None)) @@ -552,12 +558,14 @@ def test_a_commit_without_an_author_records_nothing(self): env = {"GITHUB_TOKEN": "token", "GITHUB_REPOSITORY": "owner/repo"} with ( patch.dict(os.environ, env), - patch("main.get_pr_event", return_value={"number": 7, "commits": 1}), - patch("main.get_pr_head_sha", return_value="b2"), + patch( + "action.context.get_pr_event", return_value={"number": 7, "commits": 1} + ), + patch("action.context.get_pr_head_sha", return_value="b2"), patch.dict(sys.modules, {"github": github_module}), ): - self.assertEqual(main.get_messages_from_api(), [("b2", "fix: two")]) - self.assertEqual(main.API_AUTHORS, {}) + self.assertEqual(context.get_messages_from_api(), [("b2", "fix: two")]) + self.assertEqual(context.API_AUTHORS, {}) def test_a_list_that_ends_elsewhere_is_not_used(self): # A force push after the event: same count, other commits. @@ -569,7 +577,7 @@ def test_a_partial_list_is_not_used(self): self.assertEqual(result, []) def test_more_than_the_api_returns_is_left_unlisted(self): - result, github_module = self._run(main.API_COMMIT_LIMIT + 1, []) + result, github_module = self._run(context.API_COMMIT_LIMIT + 1, []) self.assertEqual(result, []) github_module.Github.assert_not_called() @@ -577,12 +585,12 @@ def test_more_than_the_api_returns_is_left_unlisted(self): class TestCheckoutHint(unittest.TestCase): def test_pull_request_names_fetch_depth(self): with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}): - self.assertEqual(main.checkout_hint(), main.SHALLOW_CHECKOUT_HINT) + self.assertEqual(context.checkout_hint(), context.SHALLOW_CHECKOUT_HINT) def test_pull_request_target_names_the_checkout(self): with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}): - self.assertEqual(main.checkout_hint(), main.TARGET_CHECKOUT_HINT) - self.assertIn("refs/pull//merge", main.checkout_hint()) + self.assertEqual(context.checkout_hint(), context.TARGET_CHECKOUT_HINT) + self.assertIn("refs/pull//merge", context.checkout_hint()) class TestGetPrHeadSha(unittest.TestCase): @@ -598,7 +606,7 @@ def test_reads_the_head_sha_from_the_event(self): "GITHUB_EVENT_PATH": event_path, }, ): - self.assertEqual(main.get_pr_head_sha(), "abc123") + self.assertEqual(context.get_pr_head_sha(), "abc123") finally: os.unlink(event_path) @@ -611,20 +619,20 @@ def test_reads_the_base_sha_from_the_event(self): os.environ, {"GITHUB_EVENT_NAME": "pull_request", "GITHUB_EVENT_PATH": event_path}, ): - self.assertEqual(main.get_pr_base_sha(), "base111") - self.assertIsNone(main.get_pr_head_sha()) + self.assertEqual(context.get_pr_base_sha(), "base111") + self.assertIsNone(context.get_pr_head_sha()) finally: os.unlink(event_path) def test_not_a_pr_event_returns_none(self): with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "push"}): - self.assertIsNone(main.get_pr_head_sha()) - self.assertIsNone(main.get_pr_base_sha()) + self.assertIsNone(context.get_pr_head_sha()) + self.assertIsNone(context.get_pr_base_sha()) def test_missing_event_path_returns_none(self): with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}): os.environ.pop("GITHUB_EVENT_PATH", None) - self.assertIsNone(main.get_pr_head_sha()) + self.assertIsNone(context.get_pr_head_sha()) def test_unreadable_event_returns_none(self): with patch.dict( @@ -634,7 +642,7 @@ def test_unreadable_event_returns_none(self): "GITHUB_EVENT_PATH": "/nonexistent.json", }, ): - self.assertIsNone(main.get_pr_head_sha()) + self.assertIsNone(context.get_pr_head_sha()) def _pr_event(pull_request: dict) -> str: @@ -657,18 +665,18 @@ def _env(self, pull_request: dict): def test_body(self): with self._env({"body": "Adds a parser."}): - self.assertEqual(main.get_pr_body(), "Adds a parser.") + self.assertEqual(context.get_pr_body(), "Adds a parser.") def test_no_description_is_none(self): for body in (None, "", " \n "): with self.subTest(body=body), self._env({"body": body}): - self.assertIsNone(main.get_pr_body()) + self.assertIsNone(context.get_pr_body()) def test_an_agent_app_opened_it(self): with self._env({"user": {"login": "Copilot-SWE-Agent[bot]"}}): - self.assertEqual(main.get_pr_opener_tool(), "GitHub Copilot") + self.assertEqual(context.get_pr_opener_tool(), "GitHub Copilot") def test_a_person_or_another_bot_opened_it(self): for user in ({"login": "octocat"}, {"login": "dependabot[bot]"}, None, {}): with self.subTest(user=user), self._env({"user": user}): - self.assertIsNone(main.get_pr_opener_tool()) + self.assertIsNone(context.get_pr_opener_tool()) diff --git a/tests/helpers.py b/tests/helpers.py index 7bdd430..f5069dc 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -2,7 +2,7 @@ import re -import main +from action import model HOOK_GUIDE = "https://commit-check.com/guides/integrations/#as-a-pre-commit-hook" @@ -40,12 +40,12 @@ def make_check( SHA_B = "5584f462cc3c947b2ba8d3d1a5735571803ee159" -def pass_scope(label: str = "Branch", value: str = "") -> main.ScopeResult: - return main.ScopeResult(label=label, checks=[make_check("branch", value=value)]) +def pass_scope(label: str = "Branch", value: str = "") -> model.ScopeResult: + return model.ScopeResult(label=label, checks=[make_check("branch", value=value)]) -def fail_scope(label: str = "Commit 1/1", sha: str = "") -> main.ScopeResult: - return main.ScopeResult( +def fail_scope(label: str = "Commit 1/1", sha: str = "") -> model.ScopeResult: + return model.ScopeResult( label=label, sha=sha, checks=[ @@ -62,10 +62,10 @@ def fail_scope(label: str = "Commit 1/1", sha: str = "") -> main.ScopeResult: ) -def fix_scope(label: str = "Commit 2/3", sha: str = SHA_B) -> main.ScopeResult: +def fix_scope(label: str = "Commit 2/3", sha: str = SHA_B) -> model.ScopeResult: """A CC002 failure as commit-check 2.17 reports it: a mechanical fix, and a ``suggest`` the engine derived from that same fix.""" - return main.ScopeResult( + return model.ScopeResult( label=label, sha=sha, checks=[ @@ -124,17 +124,17 @@ def read_github_output(path: str) -> dict[str, str]: return outputs -def skip_scope(label: str = "PR title", reason: str = "") -> main.ScopeResult: +def skip_scope(label: str = "PR title", reason: str = "") -> model.ScopeResult: """A scope whose every rule declined to run (e.g. author in ignore_authors).""" check = make_check("message", status="skip", rule_id="CC001", value="") if reason: check["reason"] = reason - return main.ScopeResult(label=label, checks=[check]) + return model.ScopeResult(label=label, checks=[check]) -def warn_scope(label: str = "Branch", value: str = "jsmith/fix-x") -> main.ScopeResult: +def warn_scope(label: str = "Branch", value: str = "jsmith/fix-x") -> model.ScopeResult: """A scope with one rule the config lists under the top-level ``warn``.""" - return main.ScopeResult( + return model.ScopeResult( label=label, checks=[ make_check( @@ -150,9 +150,9 @@ def warn_scope(label: str = "Branch", value: str = "jsmith/fix-x") -> main.Scope ) -def files_scope(sha: str = SHA_B, *checks) -> main.ScopeResult: +def files_scope(sha: str = SHA_B, *checks) -> model.ScopeResult: """One commit's files scope; by default the two findings of a bad commit.""" - return main.ScopeResult( + return model.ScopeResult( label="Files", sha=sha, checks=list(checks) diff --git a/tests/inputs_test.py b/tests/inputs_test.py index 2b3a2dd..48debff 100644 --- a/tests/inputs_test.py +++ b/tests/inputs_test.py @@ -3,25 +3,25 @@ import io import os import re -import sys import unittest from unittest.mock import patch import main +from action import cli, inputs class TestEnvFlag(unittest.TestCase): def test_true_value(self): with patch.dict(os.environ, {"FEATURE_FLAG": "true"}): - self.assertTrue(main.env_flag("FEATURE_FLAG")) + self.assertTrue(inputs.env_flag("FEATURE_FLAG")) def test_false_value(self): with patch.dict(os.environ, {"FEATURE_FLAG": "false"}): - self.assertFalse(main.env_flag("FEATURE_FLAG")) + self.assertFalse(inputs.env_flag("FEATURE_FLAG")) def test_missing_uses_default(self): with patch.dict(os.environ, {}, clear=True): - self.assertTrue(main.env_flag("FEATURE_FLAG", default="true")) + self.assertTrue(inputs.env_flag("FEATURE_FLAG", default="true")) class TestLogEnvVars(unittest.TestCase): @@ -36,7 +36,7 @@ def test_every_input_is_logged_as_a_debug_command(self): ), patch("sys.stdout", buffer), ): - main.log_env_vars() + inputs.log_env_vars() self.assertEqual( buffer.getvalue().splitlines(), [ @@ -57,92 +57,40 @@ def test_every_input_is_logged_as_a_debug_command(self): ) -class TestReconfigureIo(unittest.TestCase): - def test_reconfigures_streams_to_utf8(self): - class FakeStream: - def __init__(self): - self.reconfigured = None - - def reconfigure(self, **kwargs): - self.reconfigured = kwargs - - fake_out = FakeStream() - fake_err = FakeStream() - with ( - patch.object(sys, "stdout", fake_out), - patch.object(sys, "stderr", fake_err), - ): - main._reconfigure_io() - self.assertEqual( - fake_out.reconfigured, {"encoding": "utf-8", "errors": "replace"} - ) - self.assertEqual( - fake_err.reconfigured, {"encoding": "utf-8", "errors": "replace"} - ) - - def test_streams_without_reconfigure_are_ignored(self): - class NoopStream: - pass - - with ( - patch.object(sys, "stdout", NoopStream()), - patch.object(sys, "stderr", NoopStream()), - ): - main._reconfigure_io() # should not raise - - class TestBuildCheckArgs(unittest.TestCase): def test_all_true(self): with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.BRANCH_ENABLED", True), - patch("main.AUTHOR_NAME_ENABLED", True), - patch("main.AUTHOR_EMAIL_ENABLED", True), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", True), + patch("action.inputs.AUTHOR_NAME_ENABLED", True), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", True), ): - result = main.build_check_args() + result = cli.build_check_args() self.assertEqual( result, ["--message", "--branch", "--author-name", "--author-email"] ) def test_all_false(self): with ( - patch("main.MESSAGE_ENABLED", False), - patch("main.BRANCH_ENABLED", False), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), + patch("action.inputs.MESSAGE_ENABLED", False), + patch("action.inputs.BRANCH_ENABLED", False), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), ): - result = main.build_check_args() + result = cli.build_check_args() self.assertEqual(result, []) def test_message_and_branch(self): with ( - patch("main.MESSAGE_ENABLED", True), - patch("main.BRANCH_ENABLED", True), - patch("main.AUTHOR_NAME_ENABLED", False), - patch("main.AUTHOR_EMAIL_ENABLED", False), + patch("action.inputs.MESSAGE_ENABLED", True), + patch("action.inputs.BRANCH_ENABLED", True), + patch("action.inputs.AUTHOR_NAME_ENABLED", False), + patch("action.inputs.AUTHOR_EMAIL_ENABLED", False), ): - result = main.build_check_args() + result = cli.build_check_args() self.assertEqual(result, ["--message", "--branch"]) -class TestLogErrorAndExit(unittest.TestCase): - def test_exits_with_specified_code(self): - with self.assertRaises(SystemExit) as ctx: - main.log_error_and_exit(0) - self.assertEqual(ctx.exception.code, 0) - - def test_failure_exits_without_a_second_annotation(self): - """The findings are already one ::error each; a summary ::error on - top made GitHub count one more error than there were findings.""" - with ( - patch("builtins.print") as mock_print, - self.assertRaises(SystemExit) as ctx, - ): - main.log_error_and_exit(1) - self.assertEqual(ctx.exception.code, 1) - mock_print.assert_not_called() - - class TestAiLabelName(unittest.TestCase): def test_values(self): cases = { @@ -157,19 +105,19 @@ def test_values(self): } for value, expected in cases.items(): with self.subTest(value=value), patch.dict(os.environ, {"AI_LABEL": value}): - self.assertEqual(main.ai_label_name(), expected) + self.assertEqual(inputs.ai_label_name(), expected) def test_unset_is_off(self): with patch.dict(os.environ, {}, clear=True): - self.assertIsNone(main.ai_label_name()) + self.assertIsNone(inputs.ai_label_name()) class TestBooleanInputs(unittest.TestCase): """A boolean input is true or false; anything else fails the step.""" def setUp(self): - main.INVALID_FLAGS.clear() - self.addCleanup(main.INVALID_FLAGS.clear) + inputs.INVALID_FLAGS.clear() + self.addCleanup(inputs.INVALID_FLAGS.clear) def test_true_and_false_in_any_case_and_padding(self): for value, expected in ( @@ -179,20 +127,20 @@ def test_true_and_false_in_any_case_and_padding(self): ("false", False), ): with patch.dict(os.environ, {"MESSAGE": value}): - self.assertIs(main.env_flag("MESSAGE"), expected, value) - self.assertEqual(main.INVALID_FLAGS, []) + self.assertIs(inputs.env_flag("MESSAGE"), expected, value) + self.assertEqual(inputs.INVALID_FLAGS, []) def test_unset_input_takes_the_default(self): with patch.dict(os.environ, {}, clear=True): - self.assertFalse(main.env_flag("MESSAGE")) - self.assertEqual(main.INVALID_FLAGS, []) + self.assertFalse(inputs.env_flag("MESSAGE")) + self.assertEqual(inputs.INVALID_FLAGS, []) def test_other_values_are_recorded(self): for value in ("yes", "on", "1", "maybe"): with patch.dict(os.environ, {"MESSAGE": value}): - self.assertFalse(main.env_flag("MESSAGE")) + self.assertFalse(inputs.env_flag("MESSAGE")) self.assertEqual( - main.INVALID_FLAGS, + inputs.INVALID_FLAGS, [ ("MESSAGE", "yes"), ("MESSAGE", "on"), @@ -202,11 +150,11 @@ def test_other_values_are_recorded(self): ) def test_invalid_input_fails_before_any_check(self): - main.INVALID_FLAGS.append(("PR_TITLE", "yes")) + inputs.INVALID_FLAGS.append(("PR_TITLE", "yes")) out = io.StringIO() with ( patch("sys.stdout", out), - patch("main.run_commit_check") as run, + patch("action.cli.run_commit_check") as run, self.assertRaises(SystemExit) as cm, ): main.main() diff --git a/tests/integration_test.py b/tests/integration_test.py index 51bc7b8..57eefc6 100644 --- a/tests/integration_test.py +++ b/tests/integration_test.py @@ -12,6 +12,7 @@ from unittest.mock import patch import main +from action import cli, model, render class TestCommitCheckVersionPin(unittest.TestCase): @@ -77,7 +78,7 @@ def test_requirements_pin_can_report_warnings(self): class TestRealCommitCheckBinary(unittest.TestCase): """Run the pinned commit-check once, unmocked. - Every other test patches ``main.subprocess.run`` and feeds back the JSON + Every other test patches ``subprocess.run`` and feeds back the JSON shape ``make_check()`` hard-codes, so a renamed key or a new status in the CLI would leave the whole suite green while the action rendered "—" for every value. This is the one place that drift can fail a build. CI @@ -121,7 +122,7 @@ def setUp(self): self.addCleanup(env_patch.stop) def _run(self, message: str, check_type: str = "--message") -> tuple[int, dict]: - rc, data, raw = main.run_check_json( + rc, data, raw = cli.run_check_json( [check_type, "--config", self.config], input_text=message ) self.assertIsInstance(data, dict, f"CLI did not emit JSON:\n{raw}") @@ -143,9 +144,9 @@ def test_passing_message(self): self.assertEqual(rc, 0) self.assertEqual(data["status"], "pass") self.assertTrue(all(c["status"] == "pass" for c in data["checks"])) - scope = main.ScopeResult(label="Commit 1/1", checks=data["checks"]) + scope = model.ScopeResult(label="Commit 1/1", checks=data["checks"]) self.assertEqual(scope.status, "pass") - self.assertEqual(main.overall_status([scope]), "pass") + self.assertEqual(model.overall_status([scope]), "pass") def test_failing_message(self): rc, data = self._run("Bad subject\n") @@ -154,13 +155,13 @@ def test_failing_message(self): failed = [c for c in data["checks"] if c["status"] == "fail"] self.assertEqual([c["rule_id"] for c in failed], ["CC001"]) self.assertTrue(failed[0]["error"]) - scope = main.ScopeResult(label="Commit 1/1", checks=data["checks"]) + scope = model.ScopeResult(label="Commit 1/1", checks=data["checks"]) self.assertEqual(scope.status, "fail") - self.assertEqual(main.overall_status([scope]), "fail") + self.assertEqual(model.overall_status([scope]), "fail") # The rendered report must carry the rule link the CLI supplied. self.assertIn( "Rules: [CC001](https://commit-check.com/rules/#cc001)", - main.render_report([scope]), + render.render_report([scope]), ) def test_a_title_meets_only_the_rules_a_title_can(self): @@ -176,7 +177,7 @@ def test_a_title_meets_only_the_rules_a_title_can(self): ran = {c["rule_id"] for c in data["checks"]} self.assertEqual(rc, 0) self.assertFalse(ran & {"CC011", "CC012", "CC017"}) - scope = main.ScopeResult(label="PR title", checks=data["checks"]) + scope = model.ScopeResult(label="PR title", checks=data["checks"]) self.assertEqual(scope.status, "pass") def test_a_bad_title_still_fails(self): @@ -243,7 +244,7 @@ def test_each_commit_answers_for_the_files_it_changes(self): bad = self._commit("feat: key", {"key.pem": "k\n"}) gone = self._commit("fix: drop key", {"key.pem": None}) with patch("sys.stdout", io.StringIO()): - results = main.run_files_checks([good, bad, gone]) + results = cli.run_files_checks([good, bad, gone]) self.assertEqual( [(s.sha, s.status) for s in results], [(good, "pass"), (bad, "fail"), (gone, "skip")], @@ -252,15 +253,15 @@ def test_each_commit_answers_for_the_files_it_changes(self): [(c["rule_id"], c["value"]) for c in results[1].failures], [("CC303", "key.pem (pattern *.pem)")], ) - self.assertEqual(results[2].skip_reason, main.FILES_NOTHING_CHANGED) + self.assertEqual(results[2].skip_reason, cli.FILES_NOTHING_CHANGED) def test_no_rule_set_is_reported_as_skipped(self): sha = self._commit("chore: no rules", {"cchk.toml": ""}) with patch("sys.stdout", io.StringIO()), patch("sys.stderr", io.StringIO()): - results = main.run_files_checks([sha]) + results = cli.run_files_checks([sha]) self.assertEqual( [(s.status, s.skip_reason) for s in results], - [("skip", main.FILES_UNCONFIGURED)], + [("skip", cli.FILES_UNCONFIGURED)], ) def test_a_shallow_clone_skips_the_commit_at_its_edge(self): @@ -280,12 +281,12 @@ def test_a_shallow_clone_skips_the_commit_at_its_edge(self): cwd=os.path.dirname(self.repo), ) os.chdir(shallow) - self.assertEqual(main._shallow_boundary(), {tip}) + self.assertEqual(cli._shallow_boundary(), {tip}) out = io.StringIO() with patch("sys.stdout", out): - results = main.run_files_checks([tip]) + results = cli.run_files_checks([tip]) self.assertEqual( [(s.status, s.skip_reason) for s in results], - [("skip", main.FILES_NOT_IN_CLONE)], + [("skip", cli.FILES_NOT_IN_CLONE)], ) self.assertIn("fetch-depth: 0", out.getvalue()) diff --git a/tests/log_test.py b/tests/log_test.py index 901f9d6..5ac0ed6 100644 --- a/tests/log_test.py +++ b/tests/log_test.py @@ -16,14 +16,14 @@ warn_scope, ) -import main +from action import escape, model, render class TestRenderStepLog(unittest.TestCase): def _run(self, results, colours=False): buffer = io.StringIO() with patch("sys.stdout", buffer): - main.render_step_log(results) + render.render_step_log(results) output = buffer.getvalue() return output if colours else ANSI_CODES.sub("", output) @@ -82,7 +82,7 @@ def test_commit_text_cannot_issue_workflow_commands(self): # A failing rule prints the whole message, one line of the log per # line of the message. The runner skips leading whitespace before # looking for "::", and reads "##[" anywhere in a line. - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", checks=[ make_check( @@ -115,7 +115,7 @@ def test_commit_text_cannot_issue_workflow_commands(self): self.assertIn('::Commit 1/1 "bad subject": The commit message', output) def test_a_subject_that_starts_like_a_command_stays_text_in_its_row(self): - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", checks=[make_check("message", value="::error::x")] ) output = self._run([scope]) @@ -128,7 +128,7 @@ def test_log_safe_leaves_ordinary_text_alone(self): " ✔ branch feature/x", "tab\there", ]: - self.assertEqual(main._log_safe(text), text) + self.assertEqual(escape._log_safe(text), text) def test_annotation_names_the_commit_and_carries_the_fix(self): output = self._run([fix_scope("Commit 2/3", sha=SHA_B)]) @@ -141,7 +141,7 @@ def test_annotation_names_the_commit_and_carries_the_fix(self): def test_finding_lines_are_the_value_the_error_and_the_fix(self): self.assertEqual( - main._finding_lines(fix_scope().checks[0]), + render._finding_lines(fix_scope().checks[0]), [ "value: feat: add login page", "Subject must start with a capital letter", @@ -150,7 +150,7 @@ def test_finding_lines_are_the_value_the_error_and_the_fix(self): ) def test_annotation_without_an_error_still_names_the_kind_of_finding(self): - scope = main.ScopeResult( + scope = model.ScopeResult( label="Branch", checks=[ make_check("branch", status="fail", rule_id="CC201"), @@ -171,7 +171,7 @@ def test_fix_is_printed_once_when_suggest_only_repeats_it(self): self.assertNotIn("Suggest:", output) def test_bespoke_suggest_and_fix_are_both_printed(self): - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", checks=[ make_check( @@ -201,7 +201,7 @@ def test_bespoke_suggest_and_fix_are_both_printed(self): def test_a_multi_line_fix_takes_one_row_per_line(self): fix = "feat: add login page\n\nSigned-off-by: Jane Doe " - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", sha=SHA_A, checks=[ @@ -236,7 +236,7 @@ def test_tree_lines_carry_the_short_sha(self): results = [ pass_scope("Commit 1/3", value="fix: first"), fix_scope("Commit 2/3", sha=SHA_B), - main.ScopeResult(label="Commit 3/3", sha=SHA_A, raw_text="garbage"), + model.ScopeResult(label="Commit 3/3", sha=SHA_A, raw_text="garbage"), ] results[0].sha = "c" * 40 output = self._run(results) @@ -259,7 +259,7 @@ def test_failure_verdict_is_a_plain_line_not_an_annotation(self): self.assertNotIn("passed", output) def test_failure_verdict_says_where_the_fix_is(self): - with patch("main.JOB_SUMMARY_ENABLED", True): + with patch("action.inputs.JOB_SUMMARY_ENABLED", True): output = self._run([fail_scope("Commit 1/1")]) self.assertTrue( output.endswith( @@ -268,7 +268,7 @@ def test_failure_verdict_says_where_the_fix_is(self): ) ) # With no summary to send the reader to, the log is the report. - with patch("main.JOB_SUMMARY_ENABLED", False): + with patch("action.inputs.JOB_SUMMARY_ENABLED", False): output = self._run([fail_scope("Commit 1/1")]) self.assertIn("How to fix: see the findings above. ", output) @@ -302,7 +302,7 @@ def test_annotations_come_after_every_group(self): self.assertLess(output.rindex("::endgroup::"), output.index("::error ")) def test_annotation_payload_is_escaped(self): - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", checks=[ make_check( @@ -342,11 +342,11 @@ def test_title_and_description_share_one_group(self): pass_scope("PR description"), pass_scope("Commit 1/1"), ] - groups = [name for name, _ in main._grouped(results)] + groups = [name for name, _ in render._grouped(results)] self.assertEqual(groups, ["Pull request", "Commits"]) def test_raw_text_fallback_is_printed(self): - scope = main.ScopeResult(label="Branch", raw_text="unexpected output") + scope = model.ScopeResult(label="Branch", raw_text="unexpected output") output = self._run([scope]) self.assertIn(" ✖ branch\n", output) self.assertIn("unexpected output", output) @@ -359,7 +359,7 @@ def test_dry_run_downgrades_annotations_and_prints_verdict(self): toward the run's error total on a green job, and log_error_and_exit prints nothing for a zero exit — leaving the log with no verdict. """ - with patch("main.DRY_RUN_ENABLED", True): + with patch("action.inputs.DRY_RUN_ENABLED", True): output = self._run([fail_scope("Commit 1/1"), pass_scope("Branch")]) self.assertNotIn("::error", output) self.assertIn( @@ -375,7 +375,7 @@ def test_dry_run_downgrades_annotations_and_prints_verdict(self): self.assertNotIn("✖ Commit Check", output) def test_dry_run_without_failures_prints_the_usual_verdict(self): - with patch("main.DRY_RUN_ENABLED", True): + with patch("action.inputs.DRY_RUN_ENABLED", True): output = self._run([pass_scope("Branch")]) self.assertIn("✔ Commit Check: all checks passed", output) self.assertNotIn("dry-run", output) diff --git a/tests/main_test.py b/tests/main_test.py index e7e1657..99e7018 100644 --- a/tests/main_test.py +++ b/tests/main_test.py @@ -3,6 +3,7 @@ import io import os import runpy +import sys import unittest from unittest.mock import patch @@ -14,13 +15,13 @@ class TestMain(unittest.TestCase): def test_success_path(self): with ( - patch("main.log_env_vars"), - patch("main.run_commit_check", return_value=(0, [pass_scope()])), - patch("main.render_step_log"), - patch("main.set_result_output"), - patch("main.add_job_summary", return_value=0), - patch("main.add_pr_comments", return_value=0), - patch("main.DRY_RUN_ENABLED", False), + patch("action.inputs.log_env_vars"), + patch("action.cli.run_commit_check", return_value=(0, [pass_scope()])), + patch("action.render.render_step_log"), + patch("action.publish.set_result_output"), + patch("action.publish.add_job_summary", return_value=0), + patch("action.publish.add_pr_comments", return_value=0), + patch("action.inputs.DRY_RUN_ENABLED", False), self.assertRaises(SystemExit) as ctx, ): main.main() @@ -28,13 +29,13 @@ def test_success_path(self): def test_failure_path_exits_nonzero(self): with ( - patch("main.log_env_vars"), - patch("main.run_commit_check", return_value=(1, [fail_scope()])), - patch("main.render_step_log"), - patch("main.set_result_output"), - patch("main.add_job_summary", return_value=1), - patch("main.add_pr_comments", return_value=1), - patch("main.DRY_RUN_ENABLED", False), + patch("action.inputs.log_env_vars"), + patch("action.cli.run_commit_check", return_value=(1, [fail_scope()])), + patch("action.render.render_step_log"), + patch("action.publish.set_result_output"), + patch("action.publish.add_job_summary", return_value=1), + patch("action.publish.add_pr_comments", return_value=1), + patch("action.inputs.DRY_RUN_ENABLED", False), self.assertRaises(SystemExit) as ctx, ): main.main() @@ -42,13 +43,13 @@ def test_failure_path_exits_nonzero(self): def test_dry_run_forces_zero(self): with ( - patch("main.log_env_vars"), - patch("main.run_commit_check", return_value=(1, [fail_scope()])), - patch("main.render_step_log"), - patch("main.set_result_output"), - patch("main.add_job_summary", return_value=1), - patch("main.add_pr_comments", return_value=0), - patch("main.DRY_RUN_ENABLED", True), + patch("action.inputs.log_env_vars"), + patch("action.cli.run_commit_check", return_value=(1, [fail_scope()])), + patch("action.render.render_step_log"), + patch("action.publish.set_result_output"), + patch("action.publish.add_job_summary", return_value=1), + patch("action.publish.add_pr_comments", return_value=0), + patch("action.inputs.DRY_RUN_ENABLED", True), self.assertRaises(SystemExit) as ctx, ): main.main() @@ -75,3 +76,55 @@ def test_running_the_script_runs_main(self): ), out.getvalue(), ) + + +class TestReconfigureIo(unittest.TestCase): + def test_reconfigures_streams_to_utf8(self): + class FakeStream: + def __init__(self): + self.reconfigured = None + + def reconfigure(self, **kwargs): + self.reconfigured = kwargs + + fake_out = FakeStream() + fake_err = FakeStream() + with ( + patch.object(sys, "stdout", fake_out), + patch.object(sys, "stderr", fake_err), + ): + main._reconfigure_io() + self.assertEqual( + fake_out.reconfigured, {"encoding": "utf-8", "errors": "replace"} + ) + self.assertEqual( + fake_err.reconfigured, {"encoding": "utf-8", "errors": "replace"} + ) + + def test_streams_without_reconfigure_are_ignored(self): + class NoopStream: + pass + + with ( + patch.object(sys, "stdout", NoopStream()), + patch.object(sys, "stderr", NoopStream()), + ): + main._reconfigure_io() # should not raise + + +class TestLogErrorAndExit(unittest.TestCase): + def test_exits_with_specified_code(self): + with self.assertRaises(SystemExit) as ctx: + main.log_error_and_exit(0) + self.assertEqual(ctx.exception.code, 0) + + def test_failure_exits_without_a_second_annotation(self): + """The findings are already one ::error each; a summary ::error on + top made GitHub count one more error than there were findings.""" + with ( + patch("builtins.print") as mock_print, + self.assertRaises(SystemExit) as ctx, + ): + main.log_error_and_exit(1) + self.assertEqual(ctx.exception.code, 1) + mock_print.assert_not_called() diff --git a/tests/model_test.py b/tests/model_test.py index 350e976..7a56609 100644 --- a/tests/model_test.py +++ b/tests/model_test.py @@ -8,19 +8,19 @@ from helpers import fail_scope, make_check, pass_scope, read_github_output, skip_scope -import main +from action import inputs, model, publish class TestScopeResult(unittest.TestCase): def test_status_pass_when_all_checks_pass(self): - scope = main.ScopeResult( + scope = model.ScopeResult( label="Branch", checks=[make_check("branch"), make_check("merge_base")] ) self.assertEqual(scope.status, "pass") self.assertEqual(scope.failures, []) def test_status_fail_when_any_check_fails(self): - scope = main.ScopeResult( + scope = model.ScopeResult( label="Branch", checks=[ make_check("branch", status="fail"), @@ -31,7 +31,7 @@ def test_status_fail_when_any_check_fails(self): self.assertEqual(len(scope.failures), 1) def test_raw_text_fallback_is_failure(self): - scope = main.ScopeResult(label="Branch", raw_text="unexpected output") + scope = model.ScopeResult(label="Branch", raw_text="unexpected output") self.assertEqual(scope.status, "fail") @@ -45,21 +45,21 @@ class TestSkipCompletionSemantics(unittest.TestCase): """ def test_skipped_only_run_is_not_a_failure(self): - self.assertEqual(main.exit_code_for([skip_scope(), skip_scope("Branch")]), 0) + self.assertEqual(model.exit_code_for([skip_scope(), skip_scope("Branch")]), 0) def test_partial_skip_is_not_a_failure(self): - self.assertEqual(main.exit_code_for([pass_scope(), skip_scope()]), 0) + self.assertEqual(model.exit_code_for([pass_scope(), skip_scope()]), 0) def test_a_real_failure_still_fails(self): - self.assertEqual(main.exit_code_for([fail_scope(), skip_scope()]), 1) + self.assertEqual(model.exit_code_for([fail_scope(), skip_scope()]), 1) def test_result_output_status_reports_skip(self): self.assertEqual( - main.overall_status([skip_scope(), skip_scope("Branch")]), "skip" + model.overall_status([skip_scope(), skip_scope("Branch")]), "skip" ) def test_result_output_status_of_partial_skip_is_pass(self): - self.assertEqual(main.overall_status([pass_scope(), skip_scope()]), "pass") + self.assertEqual(model.overall_status([pass_scope(), skip_scope()]), "pass") def test_set_result_output_emits_skip(self): """The `result` action output must not call a skipped run failed.""" @@ -67,7 +67,7 @@ def test_set_result_output_emits_skip(self): out_path = f.name try: with patch.dict(os.environ, {"GITHUB_OUTPUT": out_path}): - main.set_result_output([skip_scope(), skip_scope("Branch")]) + publish.set_result_output([skip_scope(), skip_scope("Branch")]) payload = json.loads(read_github_output(out_path)["result"]) finally: os.unlink(out_path) @@ -78,10 +78,10 @@ def test_add_job_summary_returns_success_for_a_skipped_run(self): summary_path = f.name try: with ( - patch.object(main, "JOB_SUMMARY_ENABLED", True), - patch.object(main, "GITHUB_STEP_SUMMARY", summary_path), + patch.object(inputs, "JOB_SUMMARY_ENABLED", True), + patch.object(inputs, "GITHUB_STEP_SUMMARY", summary_path), ): - rc = main.add_job_summary([skip_scope(), skip_scope("Branch")]) + rc = publish.add_job_summary([skip_scope(), skip_scope("Branch")]) finally: os.unlink(summary_path) self.assertEqual(rc, 0) diff --git a/tests/publish_test.py b/tests/publish_test.py index 131b13e..de5d3a7 100644 --- a/tests/publish_test.py +++ b/tests/publish_test.py @@ -16,22 +16,22 @@ read_github_output, ) -import main +from action import cli, model, publish, render class TestAddJobSummary(unittest.TestCase): def test_false_skips(self): - with patch("main.JOB_SUMMARY_ENABLED", False): - rc = main.add_job_summary([pass_scope()]) + with patch("action.inputs.JOB_SUMMARY_ENABLED", False): + rc = publish.add_job_summary([pass_scope()]) self.assertEqual(rc, 0) def test_success_writes_policy_report(self): summary_path = os.path.join(tempfile.mkdtemp(), "summary.txt") with ( - patch("main.JOB_SUMMARY_ENABLED", True), - patch("main.GITHUB_STEP_SUMMARY", summary_path), + patch("action.inputs.JOB_SUMMARY_ENABLED", True), + patch("action.inputs.GITHUB_STEP_SUMMARY", summary_path), ): - rc = main.add_job_summary([pass_scope("Branch")]) + rc = publish.add_job_summary([pass_scope("Branch")]) self.assertEqual(rc, 0) with open(summary_path, encoding="utf-8") as file_obj: content = file_obj.read() @@ -40,10 +40,10 @@ def test_success_writes_policy_report(self): def test_failure_returns_nonzero(self): summary_path = os.path.join(tempfile.mkdtemp(), "summary.txt") with ( - patch("main.JOB_SUMMARY_ENABLED", True), - patch("main.GITHUB_STEP_SUMMARY", summary_path), + patch("action.inputs.JOB_SUMMARY_ENABLED", True), + patch("action.inputs.GITHUB_STEP_SUMMARY", summary_path), ): - rc = main.add_job_summary([fail_scope()]) + rc = publish.add_job_summary([fail_scope()]) self.assertEqual(rc, 1) with open(summary_path, encoding="utf-8") as file_obj: content = file_obj.read() @@ -55,7 +55,7 @@ class TestSetResultOutput(unittest.TestCase): def test_writes_heredoc_json(self): output_path = os.path.join(tempfile.mkdtemp(), "output.txt") with patch.dict(os.environ, {"GITHUB_OUTPUT": output_path}): - main.set_result_output([fail_scope("Commit 1/1"), pass_scope("Branch")]) + publish.set_result_output([fail_scope("Commit 1/1"), pass_scope("Branch")]) with open(output_path, encoding="utf-8") as file_obj: content = file_obj.read() self.assertRegex(content, r"(?m)^result< MagicMock: return comment def test_marked_comment_is_updated_and_older_ones_deleted(self): - first = self._comment(f"{main.COMMENT_MARKER}\nold") - second = self._comment(f"{main.COMMENT_MARKER}\nnewer") - target, stale = main._find_own_comments([first, second]) + first = self._comment(f"{render.COMMENT_MARKER}\nold") + second = self._comment(f"{render.COMMENT_MARKER}\nnewer") + target, stale = publish._find_own_comments([first, second]) self.assertIs(target, second) self.assertEqual(stale, [first]) def test_human_comment_with_the_old_title_is_never_deleted(self): """A person can type '# Commit Check'; deleting on that is destructive.""" human = self._comment("# Commit Check\nwhy is this failing?", user_type="User") - mine = self._comment(f"{main.COMMENT_MARKER}\nreport") - target, stale = main._find_own_comments([human, mine]) + mine = self._comment(f"{render.COMMENT_MARKER}\nreport") + target, stale = publish._find_own_comments([human, mine]) self.assertIs(target, mine) self.assertEqual(stale, []) def test_human_comment_with_the_old_title_is_not_adopted(self): human = self._comment("# Commit Check\nwhy is this failing?", user_type="User") - target, stale = main._find_own_comments([human]) + target, stale = publish._find_own_comments([human]) self.assertIsNone(target) self.assertEqual(stale, []) def test_bot_comment_from_an_older_version_is_adopted(self): legacy = self._comment("# Commit-Check\nold report") - target, stale = main._find_own_comments([legacy]) + target, stale = publish._find_own_comments([legacy]) self.assertIs(target, legacy) self.assertEqual(stale, []) def test_human_comment_with_the_marker_is_never_touched(self): """A person can paste the marker too, e.g. quoting a report.""" - quoted = self._comment(f"{main.COMMENT_MARKER}\nquoted", user_type="User") - mine = self._comment(f"{main.COMMENT_MARKER}\nreport") - self.assertEqual(main._find_own_comments([quoted, mine]), (mine, [])) - self.assertEqual(main._find_own_comments([mine, quoted]), (mine, [])) - self.assertEqual(main._find_own_comments([quoted]), (None, [])) + quoted = self._comment(f"{render.COMMENT_MARKER}\nquoted", user_type="User") + mine = self._comment(f"{render.COMMENT_MARKER}\nreport") + self.assertEqual(publish._find_own_comments([quoted, mine]), (mine, [])) + self.assertEqual(publish._find_own_comments([mine, quoted]), (mine, [])) + self.assertEqual(publish._find_own_comments([quoted]), (None, [])) def test_no_comments_yields_nothing_to_update(self): - target, stale = main._find_own_comments([]) + target, stale = publish._find_own_comments([]) self.assertIsNone(target) self.assertEqual(stale, []) @@ -683,45 +688,45 @@ def test_a_comment_without_an_author_is_not_a_bot(self): and not a licence to adopt the comment either.""" orphan = self._comment("# Commit Check\nold report") orphan.user = None - self.assertFalse(main._is_bot(orphan)) - self.assertEqual(main._find_own_comments([orphan]), (None, [])) + self.assertFalse(publish._is_bot(orphan)) + self.assertEqual(publish._find_own_comments([orphan]), (None, [])) class TestAiToolsFound(unittest.TestCase): def setUp(self): - main.PR_BODY_AI_TOOLS.clear() - self.addCleanup(main.PR_BODY_AI_TOOLS.clear) + cli.PR_BODY_AI_TOOLS.clear() + self.addCleanup(cli.PR_BODY_AI_TOOLS.clear) def test_union_of_scopes_description_and_opener(self): - main.PR_BODY_AI_TOOLS[:] = ["OpenAI Codex"] + cli.PR_BODY_AI_TOOLS[:] = ["OpenAI Codex"] results = [ - main.ScopeResult(label="Commit 1/2", ai_tools=["Claude Code"]), - main.ScopeResult(label="Commit 2/2", ai_tools=["Claude Code", "Cursor"]), + model.ScopeResult(label="Commit 1/2", ai_tools=["Claude Code"]), + model.ScopeResult(label="Commit 2/2", ai_tools=["Claude Code", "Cursor"]), ] with ( - patch("main.is_pr_event", return_value=True), - patch("main.get_pr_opener_tool", return_value="Devin"), + patch("action.context.is_pr_event", return_value=True), + patch("action.context.get_pr_opener_tool", return_value="Devin"), ): - found = main.ai_tools_found(results) + found = publish.ai_tools_found(results) self.assertEqual(found, ["Claude Code", "Cursor", "Devin", "OpenAI Codex"]) def test_outside_a_pull_request_only_the_scopes(self): - results = [main.ScopeResult(label="Commit message", ai_tools=["Aider"])] + results = [model.ScopeResult(label="Commit message", ai_tools=["Aider"])] with ( - patch("main.is_pr_event", return_value=False), - patch("main.get_pr_opener_tool") as opener, + patch("action.context.is_pr_event", return_value=False), + patch("action.context.get_pr_opener_tool") as opener, ): - self.assertEqual(main.ai_tools_found(results), ["Aider"]) + self.assertEqual(publish.ai_tools_found(results), ["Aider"]) opener.assert_not_called() def test_result_output_carries_them(self): output_path = os.path.join(tempfile.mkdtemp(), "output.txt") - results = [main.ScopeResult(label="Commit 1/1", ai_tools=["Claude Code"])] + results = [model.ScopeResult(label="Commit 1/1", ai_tools=["Claude Code"])] with ( patch.dict(os.environ, {"GITHUB_OUTPUT": output_path}), - patch("main.is_pr_event", return_value=False), + patch("action.context.is_pr_event", return_value=False), ): - main.set_result_output(results) + publish.set_result_output(results) payload = json.loads(read_github_output(output_path)["result"]) self.assertEqual(payload["ai_tools"], ["Claude Code"]) @@ -729,10 +734,10 @@ def test_result_output_carries_them(self): class TestAddAiLabel(unittest.TestCase): """``ai-label``: added when an AI tool wrote any of the PR, never removed.""" - AI_SCOPE = main.ScopeResult(label="Commit 1/1", ai_tools=["Claude Code"]) + AI_SCOPE = model.ScopeResult(label="Commit 1/1", ai_tools=["Claude Code"]) def setUp(self): - main.PR_BODY_AI_TOOLS.clear() + cli.PR_BODY_AI_TOOLS.clear() def _run( self, results, label="true", labels=(), get_label=None, add=None, create=None @@ -764,12 +769,12 @@ def _run( "GITHUB_API_URL": "https://ghe.example.com/api/v3", }, ), - patch("main.is_fork_pr_with_readonly_token", return_value=False), - patch("main.get_pr_opener_tool", return_value=None), + patch("action.publish.is_fork_pr_with_readonly_token", return_value=False), + patch("action.context.get_pr_opener_tool", return_value=None), patch.dict(sys.modules, {"github": github_module}), patch("builtins.print") as mock_print, ): - main.add_ai_label(results) + publish.add_ai_label(results) printed = [ c[0][0] for c in mock_print.call_args_list @@ -792,7 +797,7 @@ def test_creates_a_missing_label(self): [self.AI_SCOPE], get_label=_StubGithubException(404) ) repo.create_label.assert_called_once_with( - "ai-assisted", main.AI_LABEL_COLOR, "Written with the help of an AI tool" + "ai-assisted", publish.AI_LABEL_COLOR, "Written with the help of an AI tool" ) issue.add_to_labels.assert_called_once_with("ai-assisted") @@ -827,7 +832,7 @@ def test_already_labelled(self): def test_no_ai_no_label_and_no_api_call(self): _repo, _issue, printed, github_module = self._run( - [main.ScopeResult(label="Commit 1/1")] + [model.ScopeResult(label="Commit 1/1")] ) github_module.Github.assert_not_called() self.assertIn("No AI tool found in the pull request; no label added.", printed) @@ -842,7 +847,7 @@ def test_off_or_outside_a_pull_request_does_nothing(self): patch.dict(os.environ, {"AI_LABEL": "true", "GITHUB_EVENT_NAME": "push"}), patch("builtins.print") as mock_print, ): - main.add_ai_label([self.AI_SCOPE]) + publish.add_ai_label([self.AI_SCOPE]) mock_print.assert_not_called() def test_forbidden_names_the_permission(self): @@ -870,15 +875,15 @@ def test_missing_token_warns(self): {"AI_LABEL": "true", "GITHUB_EVENT_NAME": "pull_request"}, clear=True, ), - patch("main.is_fork_pr_with_readonly_token", return_value=False), - patch("main.get_pr_opener_tool", return_value=None), + patch("action.publish.is_fork_pr_with_readonly_token", return_value=False), + patch("action.context.get_pr_opener_tool", return_value=None), patch.dict( sys.modules, {"github": MagicMock(GithubException=_StubGithubException)}, ), patch("builtins.print") as mock_print, ): - main.add_ai_label([self.AI_SCOPE]) + publish.add_ai_label([self.AI_SCOPE]) self.assertIn("GITHUB_TOKEN is not set", mock_print.call_args[0][0]) def test_missing_repository_warns(self): @@ -892,15 +897,15 @@ def test_missing_repository_warns(self): }, clear=True, ), - patch("main.is_fork_pr_with_readonly_token", return_value=False), - patch("main.get_pr_opener_tool", return_value=None), + patch("action.publish.is_fork_pr_with_readonly_token", return_value=False), + patch("action.context.get_pr_opener_tool", return_value=None), patch.dict( sys.modules, {"github": MagicMock(GithubException=_StubGithubException)}, ), patch("builtins.print") as mock_print, ): - main.add_ai_label([self.AI_SCOPE]) + publish.add_ai_label([self.AI_SCOPE]) self.assertIn("GITHUB_REPOSITORY is not set", mock_print.call_args[0][0]) def test_fork_with_a_read_only_token_warns(self): @@ -908,11 +913,11 @@ def test_fork_with_a_read_only_token_warns(self): patch.dict( os.environ, {"AI_LABEL": "true", "GITHUB_EVENT_NAME": "pull_request"} ), - patch("main.is_fork_pr_with_readonly_token", return_value=True), - patch("main.get_pr_opener_tool", return_value=None), + patch("action.publish.is_fork_pr_with_readonly_token", return_value=True), + patch("action.context.get_pr_opener_tool", return_value=None), patch("builtins.print") as mock_print, ): - main.add_ai_label([self.AI_SCOPE]) + publish.add_ai_label([self.AI_SCOPE]) warning = mock_print.call_args[0][0] self.assertIn("::warning::AI tools found (Claude Code)", warning) self.assertIn("read-only", warning) @@ -922,12 +927,12 @@ def test_a_missing_pygithub_warns(self): patch.dict( os.environ, {"AI_LABEL": "true", "GITHUB_EVENT_NAME": "pull_request"} ), - patch("main.is_fork_pr_with_readonly_token", return_value=False), - patch("main.get_pr_opener_tool", return_value=None), + patch("action.publish.is_fork_pr_with_readonly_token", return_value=False), + patch("action.context.get_pr_opener_tool", return_value=None), patch.dict(sys.modules, {"github": None}), patch("builtins.print") as mock_print, ): - main.add_ai_label([self.AI_SCOPE]) + publish.add_ai_label([self.AI_SCOPE]) self.assertIn("Unable to add the AI label", mock_print.call_args[0][0]) @@ -940,9 +945,9 @@ def test_comment_client_uses_github_api_url(self): pull_request.get_comments.return_value = [] github_module.Github.return_value.get_repo.return_value.get_issue.return_value = pull_request with ( - patch("main.PR_COMMENTS_ENABLED", True), - patch("main.is_fork_pr_with_readonly_token", return_value=False), - patch("main.get_pr_number", return_value=7), + patch("action.inputs.PR_COMMENTS_ENABLED", True), + patch("action.publish.is_fork_pr_with_readonly_token", return_value=False), + patch("action.publish.get_pr_number", return_value=7), patch.dict( os.environ, { @@ -954,6 +959,6 @@ def test_comment_client_uses_github_api_url(self): ), patch.dict(sys.modules, {"github": github_module}), ): - main.add_pr_comments([fail_scope()]) + publish.add_pr_comments([fail_scope()]) _, kwargs = github_module.Github.call_args self.assertEqual(kwargs["base_url"], "https://ghe.example.com/api/v3") diff --git a/tests/report_test.py b/tests/report_test.py index 0ac5994..4789534 100644 --- a/tests/report_test.py +++ b/tests/report_test.py @@ -24,7 +24,7 @@ warn_scope, ) -import main +from action import cli, model, publish, render #: The report footer names the installed commit-check version, which differs #: between a contributor's machine and CI. Golden tests pin it so they assert on @@ -56,7 +56,7 @@ def group_line(glyph: str, word: str, text: str) -> str: ) -pin_version = patch("main._commit_check_version", new=lambda: PINNED_VERSION) +pin_version = patch("action.render._commit_check_version", new=lambda: PINNED_VERSION) #: Fixed lines of the report's "How to fix" section. AGENT_PROMPT = "Fix these Commit Check findings without changing any code:" @@ -78,10 +78,10 @@ def test_success_golden_output(self): pass_scope("Branch", value="feature/add-login"), ] results[1].sha, results[2].sha = SHA_A, SHA_B - body = main.render_report(results) + body = render.render_report(results) self.assertEqual( body, - f"{main.COMMENT_MARKER}\n" + f"{render.COMMENT_MARKER}\n" f"{heading('✔', 'passed', 'passed')}\n" "\n" f"{group_line('✔', 'passed', 'Pull request: passed')}
" @@ -115,10 +115,10 @@ def test_failure_golden_output(self): fail_scope("Commit 2/2"), pass_scope("Branch", value="feature/add-login"), ] - body = main.render_report(results) + body = render.render_report(results) self.assertEqual( body, - f"{main.COMMENT_MARKER}\n" + f"{render.COMMENT_MARKER}\n" f"{heading('✖', 'failed', 'failed')}\n" "\n" f"{group_line('✔', 'passed', 'Pull request: passed')}
" @@ -190,11 +190,11 @@ def test_failure_golden_output_with_commits(self): results[3].sha = "37d6def82ffcc6dbfa0af2ea1ec90512d89979ae" env = {"GITHUB_REPOSITORY": "acme/widgets", "GITHUB_SERVER_URL": ""} with patch.dict(os.environ, env): - body = main.render_report(results) + body = render.render_report(results) commits = "https://github.com/acme/widgets/commit" self.assertEqual( body, - f"{main.COMMENT_MARKER}\n" + f"{render.COMMENT_MARKER}\n" f"{heading('✖', 'failed', 'failed')}\n" "\n" f"{group_line('✔', 'passed', 'Pull request: passed')}
" @@ -273,7 +273,7 @@ def test_commit_link_honours_the_server_url(self): "GITHUB_SERVER_URL": "https://ghe.example.com/", } with patch.dict(os.environ, env): - body = main.render_report([fix_scope("Commit 1/1", sha=SHA_B)]) + body = render.render_report([fix_scope("Commit 1/1", sha=SHA_B)]) self.assertIn( f"Commits: [`5584f46`](https://ghe.example.com/acme/widgets/commit/{SHA_B}) ", body, @@ -281,14 +281,14 @@ def test_commit_link_honours_the_server_url(self): def test_no_commit_link_without_a_repository_to_link_into(self): with patch.dict(os.environ, {"GITHUB_REPOSITORY": ""}): - body = main.render_report([fix_scope("Commit 1/1", sha=SHA_B)]) + body = render.render_report([fix_scope("Commit 1/1", sha=SHA_B)]) self.assertIn("@@ 5584f46 @@\n- feat: add login page\n", body) self.assertIn("\nRules: [CC002](", body) self.assertNotIn("/commit/", body) def test_scopes_without_a_commit_are_never_linked(self): with patch.dict(os.environ, {"GITHUB_REPOSITORY": "acme/widgets"}): - body = main.render_report([fail_scope("Branch")]) + body = render.render_report([fail_scope("Branch")]) self.assertIn("@@ Branch @@\n- bad message\n", body) self.assertNotIn("/commit/", body) @@ -296,7 +296,7 @@ def test_an_author_scope_is_named_by_its_label_not_its_commit(self): """An author check runs on a commit, but the finding is the author.""" scope = fail_scope("Author email", sha=SHA_A) with patch.dict(os.environ, {"GITHUB_REPOSITORY": "acme/widgets"}): - body = main.render_report([scope]) + body = render.render_report([scope]) self.assertIn("@@ Author email @@\n", body) self.assertIn(" ✖ email bad message\n", body) self.assertNotIn("/commit/", body) @@ -304,7 +304,7 @@ def test_an_author_scope_is_named_by_its_label_not_its_commit(self): def test_skipped_scope_carries_the_sha_too(self): scope = skip_scope("Commit 1/1") scope.sha = SHA_A - self.assertIn(" ⊘ d87faca skipped\n", main.render_report([scope])) + self.assertIn(" ⊘ d87faca skipped\n", render.render_report([scope])) def test_a_check_is_a_thing_checked_not_a_rule_evaluation(self): """The total counts scopes, so it tracks the policy, not the PR size. @@ -315,14 +315,14 @@ def test_a_check_is_a_thing_checked_not_a_rule_evaluation(self): commit out of fifteen look negligible. Two rules failing on one commit is still one thing to go and fix. """ - two_failures = main.ScopeResult( + two_failures = model.ScopeResult( label="Commit 1/2", checks=[ make_check("message", status="fail", rule_id="CC001"), make_check("subject_min_length", status="fail", rule_id="CC005"), ], ) - body = main.render_report( + body = render.render_report( [pass_scope("Branch"), two_failures, pass_scope("Commit 2/2")] ) self.assertIn("> Commits: 1 of 2 failed", body) @@ -336,7 +336,7 @@ def test_total_does_not_grow_with_the_number_of_rules(self): """Adding rules to one scope must not change the totals.""" one_rule = [pass_scope("Branch")] many_rules = [ - main.ScopeResult( + model.ScopeResult( label="Branch", checks=[ make_check(f"rule_{i}", rule_id=f"CC{i:03d}") for i in range(9) @@ -344,13 +344,13 @@ def test_total_does_not_grow_with_the_number_of_rules(self): ) ] for results in (one_rule, many_rules): - body = main.render_report(results) + body = render.render_report(results) self.assertIn("> Branch: passed\n", body) self.assertIn("All 1 check", body) def test_body_opens_with_hidden_marker(self): - body = main.render_job_summary([pass_scope("Branch")]) - self.assertTrue(body.startswith(main.COMMENT_MARKER)) + body = render.render_job_summary([pass_scope("Branch")]) + self.assertTrue(body.startswith(render.COMMENT_MARKER)) def test_the_heading_is_the_verdict(self): """The mark carries the status, so no tick ever sits next to a failure.""" @@ -362,11 +362,11 @@ def test_the_heading_is_the_verdict(self): ] for results, expected in cases: with self.subTest(expected=expected): - lines = main.render_report(results).splitlines() + lines = render.render_report(results).splitlines() self.assertEqual(lines[1], expected) def test_all_pass(self): - body = main.render_job_summary([pass_scope("Branch", value="main")]) + body = render.render_job_summary([pass_scope("Branch", value="main")]) self.assertIn("Commit Check passed\n", body) self.assertIn("
", body) self.assertIn("All 1 check", body) @@ -384,7 +384,7 @@ def test_all_pass_groups_scopes_like_step_log(self): pass_scope("Author name", value="Jane Doe"), pass_scope("Author email", value="jane@example.com"), ] - body = main.render_job_summary(results) + body = render.render_job_summary(results) listing = body.split("```text\n")[1] # Group headers in the listing mirror the step log ordering. self.assertLess(listing.index("Commits\n"), listing.index("Branch\n")) @@ -396,15 +396,15 @@ def test_all_pass_groups_scopes_like_step_log(self): def test_all_pass_truncates_long_values(self): long_value = "x" * 200 - body = main.render_job_summary([pass_scope("Commit 1/1", value=long_value)]) + body = render.render_job_summary([pass_scope("Commit 1/1", value=long_value)]) self.assertIn(f" ✔ 1/1 {'x' * 79}…\n", body) def test_all_pass_without_value_shows_plain_label(self): - body = main.render_job_summary([pass_scope("Branch")]) + body = render.render_job_summary([pass_scope("Branch")]) self.assertIn(" ✔ branch\n", body) def test_failure_shows_the_diff_and_the_rule_links(self): - body = main.render_job_summary([fail_scope("Commit 1/1")]) + body = render.render_job_summary([fail_scope("Commit 1/1")]) self.assertIn("Commit Check failed\n", body) self.assertIn("> Commits: failed\n", body) self.assertIn( @@ -429,7 +429,7 @@ def test_a_failing_value_is_printed_in_full(self): """It is the one value the reader has to act on; the cap is for the rows that passed.""" subject = "feat: " + "x" * 100 - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", checks=[ make_check( @@ -437,7 +437,7 @@ def test_a_failing_value_is_printed_in_full(self): ) ], ) - body = main.render_report([scope]) + body = render.render_report([scope]) self.assertIn(f"- {subject}\n", body) self.assertIn(f" ✖ 1/1 {subject}\n", body) @@ -446,22 +446,24 @@ def test_failure_details_show_all_scopes_and_values(self): fail_scope("Commit 1/2"), pass_scope("Commit 2/2", value="fix: resolve timeout"), ] - body = main.render_job_summary(results) + body = render.render_job_summary(results) self.assertIn(" ✔ 2/2 fix: resolve timeout\n", body) self.assertIn(" ✖ 1/2 bad message\n", body) def test_passing_scopes_stay_out_of_the_diff(self): - body = main.render_job_summary([pass_scope("Branch"), fail_scope("Commit 1/1")]) + body = render.render_job_summary( + [pass_scope("Branch"), fail_scope("Commit 1/1")] + ) diff = body.split("```diff\n")[1].split("```")[0] self.assertEqual(diff.count("@@ "), 1) self.assertIn("@@ Commit 1/1 @@", diff) self.assertIn(" ✔ branch\n", body) -def ai_scope(label: str = "Commit 1/1", sha: str = SHA_A) -> main.ScopeResult: +def ai_scope(label: str = "Commit 1/1", sha: str = SHA_A) -> model.ScopeResult: """A commit that credits an AI co-author, under ``ai_attribution = "forbid"``: the rule's value is the tool, and its fix the message without the trailer.""" - return main.ScopeResult( + return model.ScopeResult( label=label, sha=sha, text=( @@ -491,13 +493,13 @@ def test_a_subject_rule_is_compared_with_the_subject_alone(self): scope = fix_scope() scope.text = "feat: add login page\n\nThe body stays.\n" self.assertEqual( - main._line_edits(scope, scope.checks[0]), + render._line_edits(scope, scope.checks[0]), (["feat: add login page"], ["feat: Add login page"]), ) def test_a_whole_message_fix_is_compared_with_the_whole_message(self): message = "feat: add login page\n\nThe body stays." - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", text=message + "\n", checks=[ @@ -511,7 +513,7 @@ def test_a_whole_message_fix_is_compared_with_the_whole_message(self): ], ) self.assertEqual( - main._line_edits(scope, scope.checks[0]), + render._line_edits(scope, scope.checks[0]), ([], ["Signed-off-by: Jane Doe "]), ) @@ -519,16 +521,16 @@ def test_an_ai_rule_is_compared_with_the_message_not_with_its_value(self): """The value is the tool's name; the fix drops the trailer.""" scope = ai_scope() self.assertEqual( - main._line_edits(scope, scope.checks[0]), + render._line_edits(scope, scope.checks[0]), (["Co-authored-by: Claude "], []), ) def test_an_ai_rule_without_the_message_has_no_line_to_name(self): scope = ai_scope() scope.text = "" - self.assertEqual(main._line_edits(scope, scope.checks[0]), ([], [])) + self.assertEqual(render._line_edits(scope, scope.checks[0]), ([], [])) self.assertEqual( - main._instruction(scope, scope.checks[0]), + render._instruction(scope, scope.checks[0]), "Remove the AI trailer lines and re-commit.", ) @@ -539,20 +541,20 @@ def test_the_message_rule_supplies_the_text_outside_a_pull_request(self): scope.checks.insert(0, make_check("message", value=scope.text.strip())) scope.text = "" self.assertEqual( - main._line_edits(scope, scope.checks[1]), + render._line_edits(scope, scope.checks[1]), (["Co-authored-by: Claude "], []), ) - self.assertEqual(main._first_value(scope), "feat: add OAuth providers") + self.assertEqual(render._first_value(scope), "feat: add OAuth providers") def test_a_rule_without_a_fix_has_no_edits(self): scope = fail_scope() - self.assertEqual(main._line_edits(scope, scope.checks[0]), ([], [])) + self.assertEqual(render._line_edits(scope, scope.checks[0]), ([], [])) def test_a_fix_with_nothing_to_compare_it_with_has_no_edits(self): - scope = main.ScopeResult( + scope = model.ScopeResult( label="Branch", checks=[make_check("branch", status="fail", fix="x")] ) - self.assertEqual(main._line_edits(scope, scope.checks[0]), ([], [])) + self.assertEqual(render._line_edits(scope, scope.checks[0]), ([], [])) def test_recorded_edits_win_over_the_fix(self): """A description is too long to carry as a fix, so its line changes @@ -560,7 +562,7 @@ def test_recorded_edits_win_over_the_fix(self): scope = fail_scope("PR description") scope.edits["CC001"] = (["Generated with Claude Code"], []) self.assertEqual( - main._line_edits(scope, scope.checks[0]), + render._line_edits(scope, scope.checks[0]), (["Generated with Claude Code"], []), ) @@ -576,7 +578,7 @@ def test_instruction_names_each_kind_of_change(self): for edits, expected in cases: with self.subTest(expected=expected): scope.edits["CC001"] = edits - self.assertEqual(main._instruction(scope, check), expected) + self.assertEqual(render._instruction(scope, check), expected) def test_advice_drops_what_only_the_rule_page_needs(self): cases = { @@ -593,7 +595,7 @@ def test_advice_drops_what_only_the_rule_page_needs(self): for suggest, expected in cases.items(): with self.subTest(suggest=suggest): check = make_check("message", status="fail", suggest=suggest) - self.assertEqual(main._advice(check), expected) + self.assertEqual(render._advice(check), expected) def test_advice_falls_back_to_the_error_without_its_link(self): check = make_check( @@ -601,12 +603,12 @@ def test_advice_falls_back_to_the_error_without_its_link(self): status="fail", error="Follow Conventional Commits. See https://www.conventionalcommits.org", ) - self.assertEqual(main._advice(check), "Follow Conventional Commits.") + self.assertEqual(render._advice(check), "Follow Conventional Commits.") class TestDiffBlock(unittest.TestCase): def _hunks(self, results, status="fail"): - lines = main._diff_block(results, status) + lines = render._diff_block(results, status) return lines[1 : lines.index("```")] def test_a_fix_on_another_line_leaves_the_subject_as_context(self): @@ -642,7 +644,7 @@ def test_advice_is_about_the_value_so_the_value_is_red(self): def test_an_ai_author_leaves_the_subject_as_context(self): # CC017 is about who made the commit, not what its subject says. - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", sha=SHA_A, text="fix: handle the empty case\n", @@ -666,7 +668,7 @@ def test_an_ai_author_leaves_the_subject_as_context(self): def test_an_ai_rules_value_never_stands_in_for_the_subject(self): # An empty message has no subject; the author CC017 reports is not one. - scope = main.ScopeResult( + scope = model.ScopeResult( label="Commit 1/1", sha=SHA_A, checks=[ @@ -676,8 +678,8 @@ def test_an_ai_rules_value_never_stands_in_for_the_subject(self): ), ], ) - self.assertEqual(main._first_value(scope), "") - self.assertEqual(main._render_scopes([scope], False), [" ✔ d87faca"]) + self.assertEqual(render._first_value(scope), "") + self.assertEqual(render._render_scopes([scope], False), [" ✔ d87faca"]) def test_two_rules_that_ask_for_the_same_line_show_it_once(self): scope = ai_scope() @@ -696,21 +698,21 @@ def test_a_description_is_named_by_its_label_and_shows_only_the_lines(self): def test_a_long_list_is_cut_and_the_rest_folded(self): results = [fail_scope(f"Commit {n}/8", sha=f"{n}" * 40) for n in range(1, 9)] with patch.dict(os.environ, {"GITHUB_REPOSITORY": "acme/widgets"}): - lines = main._diff_block(results) + lines = render._diff_block(results) body = "\n".join(lines) shown, folded = body.split("
") - self.assertEqual(shown.count("@@ "), main.MAX_HUNKS) + self.assertEqual(shown.count("@@ "), render.MAX_HUNKS) self.assertIn("and 3 more\n\n```diff\n@@ 6666666 @@", folded) self.assertEqual(folded.count("@@ "), 3) # Only the commits in view are linked; the rule is named once. links = lines[-1] - self.assertEqual(links.count("/commit/"), main.MAX_HUNKS) + self.assertEqual(links.count("/commit/"), render.MAX_HUNKS) self.assertNotIn("6666666", links) self.assertEqual(links.count("[CC001]"), 1) def test_one_or_two_leftovers_are_not_worth_a_fold(self): results = [fail_scope(f"Commit {n}/7", sha=f"{n}" * 40) for n in range(1, 8)] - body = "\n".join(main._diff_block(results)) + body = "\n".join(render._diff_block(results)) self.assertEqual(body.count("@@ "), 7) self.assertNotIn("
", body) @@ -723,10 +725,10 @@ def test_warnings_get_the_same_block(self): class TestHowToFix(unittest.TestCase): def _body(self, results): - return "\n".join(main._how_to_fix(results)) + return "\n".join(render._how_to_fix(results)) def test_nothing_failed_nothing_to_fix(self): - self.assertEqual(main._how_to_fix([pass_scope(), warn_scope()]), []) + self.assertEqual(render._how_to_fix([pass_scope(), warn_scope()]), []) def test_the_prompt_lists_every_failing_scope_with_its_instruction(self): results = [ @@ -810,17 +812,17 @@ def test_one_pull_request_field_is_it_not_them(self): class TestRenderPrComment(unittest.TestCase): def test_all_pass_matches_job_summary(self): - comment = main.render_pr_comment([pass_scope("Branch")]) - summary = main.render_job_summary([pass_scope("Branch")]) + comment = render.render_pr_comment([pass_scope("Branch")]) + summary = render.render_job_summary([pass_scope("Branch")]) self.assertEqual(comment, summary) - self.assertTrue(comment.startswith(main.COMMENT_MARKER)) + self.assertTrue(comment.startswith(render.COMMENT_MARKER)) self.assertIn("Commit Check passed\n", comment) def test_failure_matches_job_summary(self): - comment = main.render_pr_comment([fail_scope("Commit 1/1")]) - summary = main.render_job_summary([fail_scope("Commit 1/1")]) + comment = render.render_pr_comment([fail_scope("Commit 1/1")]) + summary = render.render_job_summary([fail_scope("Commit 1/1")]) self.assertEqual(comment, summary) - self.assertTrue(comment.startswith(main.COMMENT_MARKER)) + self.assertTrue(comment.startswith(render.COMMENT_MARKER)) self.assertIn("Commit Check failed\n", comment) self.assertIn("```diff\n@@ Commit 1/1 @@\n", comment) @@ -837,12 +839,12 @@ def setUp(self): "GITHUB_SERVER_URL": "https://github.com", } - def _failing_commits(self, count: int) -> list[main.ScopeResult]: + def _failing_commits(self, count: int) -> list[model.ScopeResult]: body = "\n".join( f"Line {i} of a body that explains the change." for i in range(8) ) return [ - main.ScopeResult( + model.ScopeResult( label=f"Commit {i}/{count}", sha=f"{i:040x}", checks=[ @@ -862,20 +864,22 @@ def _failing_commits(self, count: int) -> list[main.ScopeResult]: def test_a_report_that_fits_is_the_job_summary(self): results = self._failing_commits(3) self.assertEqual( - main.render_pr_comment(results), main.render_job_summary(results) + render.render_pr_comment(results), render.render_job_summary(results) ) def test_dozens_of_failing_commits_still_fit(self): results = self._failing_commits(60) - self.assertGreater(len(main.render_job_summary(results)), main.COMMENT_LIMIT) + self.assertGreater( + len(render.render_job_summary(results)), render.COMMENT_LIMIT + ) with ( patch.dict(os.environ, self.RUN), - patch("main.JOB_SUMMARY_ENABLED", True), - patch("main.GITHUB_STEP_SUMMARY", "/tmp/summary.md"), + patch("action.inputs.JOB_SUMMARY_ENABLED", True), + patch("action.inputs.GITHUB_STEP_SUMMARY", "/tmp/summary.md"), ): - comment = main.render_pr_comment(results) - self.assertLessEqual(main._comment_length(comment), main.COMMENT_LIMIT) - self.assertTrue(comment.startswith(main.COMMENT_MARKER)) + comment = render.render_pr_comment(results) + self.assertLessEqual(render._comment_length(comment), render.COMMENT_LIMIT) + self.assertTrue(comment.startswith(render.COMMENT_MARKER)) self.assertIn("Commit Check failed", comment) self.assertNotIn("All 60 checks", comment) self.assertIn( @@ -887,11 +891,11 @@ def test_the_diff_goes_too_when_the_listing_was_not_enough(self): results = self._failing_commits(2) with ( patch.dict(os.environ, self.RUN), - patch("main.JOB_SUMMARY_ENABLED", False), + patch("action.inputs.JOB_SUMMARY_ENABLED", False), ): - short = main.render_report(results, "short") - with patch("main.COMMENT_LIMIT", len(short) - 1): - comment = main.render_pr_comment(results) + short = render.render_report(results, "short") + with patch("action.render.COMMENT_LIMIT", len(short) - 1): + comment = render.render_pr_comment(results) self.assertNotIn("```diff", comment) self.assertNotIn("How to fix", comment) self.assertIn( @@ -905,21 +909,21 @@ def test_a_passing_headline_names_no_findings(self): env = {k: v for k, v in os.environ.items() if k != "GITHUB_RUN_ID"} with ( patch.dict(os.environ, env, clear=True), - patch("main.JOB_SUMMARY_ENABLED", False), + patch("action.inputs.JOB_SUMMARY_ENABLED", False), ): - body = main.render_report([pass_scope("Branch")], "headline") + body = render.render_report([pass_scope("Branch")], "headline") self.assertIn("All checks are in the step log of this run.", body) def test_length_is_counted_as_github_counts_it(self): - self.assertEqual(main._comment_length("a🤖"), 3) + self.assertEqual(render._comment_length("a🤖"), 3) class TestUnparsableScopeInTheReport(unittest.TestCase): """A CLI response that is not JSON is a failure with no rule to link.""" def test_the_diff_points_at_the_step_log(self): - scope = main.ScopeResult(label="Branch", raw_text="Error: cchk.toml: oops") - body = main.render_report([scope]) + scope = model.ScopeResult(label="Branch", raw_text="Error: cchk.toml: oops") + body = render.render_report([scope]) self.assertIn("Commit Check failed\n", body) self.assertIn( "```diff\n" @@ -935,17 +939,17 @@ def test_the_diff_points_at_the_step_log(self): self.assertIn(" ✖ branch\n Error: cchk.toml: oops\n", body) def test_it_never_reaches_the_warnings(self): - scope = main.ScopeResult(label="Branch", raw_text="garbage") - self.assertNotIn("**Warnings**", main.render_report([scope])) - self.assertEqual(main._diff_block([scope], "warn")[:2], ["```diff", "```"]) + scope = model.ScopeResult(label="Branch", raw_text="garbage") + self.assertNotIn("**Warnings**", render.render_report([scope])) + self.assertEqual(render._diff_block([scope], "warn")[:2], ["```diff", "```"]) class TestReportFooter(unittest.TestCase): def test_names_the_installed_commit_check(self): with patch("importlib.metadata.version", return_value="9.8.7") as version: - self.assertEqual(main._commit_check_version(), "9.8.7") + self.assertEqual(render._commit_check_version(), "9.8.7") self.assertEqual( - main._report_footer(), + render._report_footer(), "Checked by [Commit Check](https://commit-check.com) 9.8.7 · " "[Rules](https://commit-check.com/rules/) · " f"[Check before you push]({HOOK_GUIDE})", @@ -956,9 +960,9 @@ def test_without_a_version_it_still_links_the_rules(self): """The footer is decoration: an unknown version drops out of it.""" missing = importlib.metadata.PackageNotFoundError("commit-check") with patch("importlib.metadata.version", side_effect=missing): - self.assertEqual(main._commit_check_version(), "") + self.assertEqual(render._commit_check_version(), "") self.assertEqual( - main._report_footer(), + render._report_footer(), "Checked by [Commit Check](https://commit-check.com) · " "[Rules](https://commit-check.com/rules/) · " f"[Check before you push]({HOOK_GUIDE})", @@ -978,7 +982,7 @@ def test_scope_status_is_skip_not_pass(self): def test_one_real_verdict_outranks_the_skips(self): """A scope only counts as skipped when nothing in it ran.""" - mixed = main.ScopeResult( + mixed = model.ScopeResult( label="PR title", checks=[ make_check("message", status="skip", value=""), @@ -991,10 +995,10 @@ def test_one_real_verdict_outranks_the_skips(self): def test_all_skipped_golden_output(self): """Pin the fully skipped report: no ✔, no pass claim.""" results = [skip_scope("PR title"), skip_scope("Commit 1/1")] - body = main.render_report(results) + body = render.render_report(results) self.assertEqual( body, - f"{main.COMMENT_MARKER}\n" + f"{render.COMMENT_MARKER}\n" f"{heading('⊘', 'skipped', 'skipped')}\n" "\n" "Nothing was validated.\n" @@ -1020,7 +1024,7 @@ def test_all_skipped_golden_output(self): def test_partial_skip_does_not_claim_all_passed(self): results = [pass_scope("Branch", value="main"), skip_scope("PR title")] results.append(pass_scope("PR description")) - body = main.render_report(results) + body = render.render_report(results) self.assertIn("Commit Check passed\n", body) self.assertIn("> Branch: passed
", body) # Two scopes in the group, one of which ran: never "2 passed". @@ -1028,14 +1032,14 @@ def test_partial_skip_does_not_claim_all_passed(self): def test_failure_still_wins_over_skips(self): results = [fail_scope("Commit 1/1"), skip_scope("PR title")] - body = main.render_report(results) + body = render.render_report(results) self.assertIn("Commit Check failed\n", body) self.assertIn("> Commits: failed
", body) self.assertIn("> Pull request: skipped\n", body) def test_skipped_scope_reports_no_checked_value(self): """The ⊘ line carries no value, because nothing was examined.""" - body = main.render_report([skip_scope("PR title")]) + body = render.render_report([skip_scope("PR title")]) self.assertIn(" ⊘ title skipped\n", body) def test_skip_reason_is_shown_on_the_scope_and_under_the_verdict(self): @@ -1047,7 +1051,7 @@ def test_skip_reason_is_shown_on_the_scope_and_under_the_verdict(self): skip_scope("Commit 1/1", reason=commit), skip_scope("Branch", reason=branch), ] - body = main.render_report(results) + body = render.render_report(results) self.assertIn("Commit Check skipped\n\nNothing was validated.\n", body) self.assertIn( "> Branch: skipped\n\n" @@ -1060,7 +1064,7 @@ def test_skip_reason_is_shown_on_the_scope_and_under_the_verdict(self): def test_skip_reason_follows_a_partial_skip_verdict(self): reason = "author dependabot[bot] is in [branch].ignore_authors" results = [pass_scope("PR title"), skip_scope("Branch", reason=reason)] - body = main.render_report(results) + body = render.render_report(results) self.assertIn( "> Branch: skipped\n\n" "Skipped because author dependabot[bot] is in ignore_authors.\n", @@ -1070,7 +1074,7 @@ def test_skip_reason_follows_a_partial_skip_verdict(self): def test_skip_reason_reaches_the_step_log(self): reason = "author dependabot[bot] is in [commit].ignore_authors" with patch("sys.stdout", new_callable=io.StringIO) as out: - main.render_step_log([skip_scope("PR title", reason=reason)]) + render.render_step_log([skip_scope("PR title", reason=reason)]) self.assertIn("::group::⊘ Pull request: skipped\n", out.getvalue()) self.assertIn( f" ⊘ title skipped: {reason}\n", ANSI_CODES.sub("", out.getvalue()) @@ -1084,7 +1088,7 @@ def test_skip_reason_follows_a_partial_skip_in_the_step_log(self): reason = "author dependabot[bot] is in [branch].ignore_authors" results = [pass_scope("PR title"), skip_scope("Branch", reason=reason)] with patch("sys.stdout", new_callable=io.StringIO) as out: - main.render_step_log(results) + render.render_step_log(results) self.assertIn( "Skipped because author dependabot[bot] is in ignore_authors.", out.getvalue(), @@ -1096,7 +1100,7 @@ def test_a_passing_scope_has_no_skip_reason(self): def test_older_engine_without_skip_is_unaffected(self): """Back-compat: engines that only emit pass/fail render as before.""" results = [pass_scope("Branch", value="main")] - self.assertIn("Commit Check passed\n", main.render_report(results)) + self.assertIn("Commit Check passed\n", render.render_report(results)) class TestWarnedScopes(unittest.TestCase): @@ -1108,7 +1112,7 @@ def test_scope_status_is_warn_not_fail_or_pass(self): def test_a_real_failure_outranks_a_warning_in_the_same_scope(self): """CC2xx groups both branch and merge_base; the two can disagree.""" - mixed = main.ScopeResult( + mixed = model.ScopeResult( label="Branch", checks=[ make_check("branch", status="warn", rule_id="CC201"), @@ -1123,7 +1127,7 @@ def test_a_warning_survives_reporting_on_a_scope_that_also_fails(self): listing. Filtering any of those on ``scope.status == "warn"`` drops this scope's warning the moment its sibling rule fails. """ - mixed = main.ScopeResult( + mixed = model.ScopeResult( label="Branch", checks=[ make_check( @@ -1145,9 +1149,9 @@ def test_a_warning_survives_reporting_on_a_scope_that_also_fails(self): ), ], ) - self.assertEqual(main._warn_count([mixed]), 1) + self.assertEqual(render._warn_count([mixed]), 1) - body = main.render_report([mixed]) + body = render.render_report([mixed]) self.assertIn("Commit Check failed\n", body) failed, warned = body.split("**Warnings**") self.assertIn( @@ -1179,7 +1183,7 @@ def test_a_warning_survives_reporting_on_a_scope_that_also_fails(self): def test_step_log_and_report_agree_on_a_mixed_scope(self): """The step log's ::warning annotation must not be the only surface that shows this scope's warning — the report has to as well.""" - mixed = main.ScopeResult( + mixed = model.ScopeResult( label="Branch", checks=[ make_check("branch", status="warn", rule_id="CC201", error="e1"), @@ -1188,17 +1192,17 @@ def test_step_log_and_report_agree_on_a_mixed_scope(self): ) buf = io.StringIO() with patch("sys.stdout", buf): - main.render_step_log([mixed]) + render.render_step_log([mixed]) step_log = buf.getvalue() self.assertIn("::warning title=CC201 branch::", step_log) self.assertIn("::error title=CC202 merge-base::", step_log) - body = main.render_report([mixed]) + body = render.render_report([mixed]) self.assertIn("CC201 branch", body) self.assertIn("CC202 merge-base", body) def test_a_warning_outranks_a_skip_in_the_same_scope(self): - mixed = main.ScopeResult( + mixed = model.ScopeResult( label="Author", checks=[ make_check("author_name", status="skip"), @@ -1208,7 +1212,7 @@ def test_a_warning_outranks_a_skip_in_the_same_scope(self): self.assertEqual(mixed.status, "warn") def test_warnings_property_lists_only_the_warned_checks(self): - mixed = main.ScopeResult( + mixed = model.ScopeResult( label="Branch", checks=[ make_check("branch", status="warn", rule_id="CC201"), @@ -1220,25 +1224,25 @@ def test_warnings_property_lists_only_the_warned_checks(self): def test_overall_status_is_warn_but_the_exit_code_is_still_zero(self): """``warn`` is for downstream steps; it must never fail the job.""" results = [pass_scope("PR title"), warn_scope()] - self.assertEqual(main.overall_status(results), "warn") - self.assertEqual(main.exit_code_for(results), 0) + self.assertEqual(model.overall_status(results), "warn") + self.assertEqual(model.exit_code_for(results), 0) def test_a_warning_outranks_a_skip_but_not_an_all_skipped_run(self): - self.assertEqual(main.overall_status([warn_scope(), skip_scope()]), "warn") - self.assertEqual(main.overall_status([skip_scope()]), "skip") + self.assertEqual(model.overall_status([warn_scope(), skip_scope()]), "warn") + self.assertEqual(model.overall_status([skip_scope()]), "skip") def test_result_output_reports_warn(self): output_path = os.path.join(tempfile.mkdtemp(), "output.txt") with patch.dict(os.environ, {"GITHUB_OUTPUT": output_path}): - main.set_result_output([pass_scope("PR title"), warn_scope()]) + publish.set_result_output([pass_scope("PR title"), warn_scope()]) payload = json.loads(read_github_output(output_path)["result"]) self.assertEqual(payload["status"], "warn") self.assertEqual([s["status"] for s in payload["scopes"]], ["pass", "warn"]) def test_a_real_failure_still_fails_the_run_alongside_a_warning(self): results = [fail_scope("Commit 1/1"), warn_scope()] - self.assertEqual(main.overall_status(results), "fail") - self.assertEqual(main.exit_code_for(results), 1) + self.assertEqual(model.overall_status(results), "fail") + self.assertEqual(model.exit_code_for(results), 1) @pin_version def test_warning_only_golden_output(self): @@ -1247,10 +1251,10 @@ def test_warning_only_golden_output(self): pass_scope("PR title", value="feat: add login page"), warn_scope("Branch"), ] - body = main.render_report(results) + body = render.render_report(results) self.assertEqual( body, - f"{main.COMMENT_MARKER}\n" + f"{render.COMMENT_MARKER}\n" f"{heading('⚠', 'warned', 'passed with warnings')}\n" "\n" f"{group_line('✔', 'passed', 'Pull request: passed')}
" @@ -1287,7 +1291,7 @@ def test_warning_only_golden_output(self): def test_warning_and_skip_each_get_their_own_group_line(self): results = [pass_scope("PR title"), warn_scope(), skip_scope("Author name")] - body = main.render_report(results) + body = render.render_report(results) self.assertIn("Commit Check passed with warnings\n", body) self.assertIn( f"{group_line('✔', 'passed', 'Pull request: passed')}
" @@ -1298,7 +1302,7 @@ def test_warning_and_skip_each_get_their_own_group_line(self): def test_a_failure_still_fails_and_names_the_warning_too(self): results = [fail_scope("Commit 1/1"), warn_scope()] - body = main.render_report(results) + body = render.render_report(results) self.assertIn("Commit Check failed\n", body) self.assertEqual(body.count("```diff\n"), 2) # The failures come first, the warnings under their own heading, and @@ -1311,7 +1315,7 @@ def test_a_failure_still_fails_and_names_the_warning_too(self): def test_step_log_prints_a_warning_annotation_not_an_error(self): buf = io.StringIO() with patch("sys.stdout", buf): - main.render_step_log([warn_scope()]) + render.render_step_log([warn_scope()]) out = buf.getvalue() self.assertIn( '::warning title=CC201 branch::Branch "jsmith/fix-x": ' @@ -1326,7 +1330,7 @@ def test_step_log_prints_a_warning_annotation_not_an_error(self): def test_step_log_friendly_line_mentions_the_warning(self): buf = io.StringIO() with patch("sys.stdout", buf): - main.render_step_log([pass_scope("PR title"), warn_scope()]) + render.render_step_log([pass_scope("PR title"), warn_scope()]) out = buf.getvalue() self.assertIn("1 of 2 checks passed, 1 warning", out) self.assertNotIn("all checks passed", out) @@ -1342,8 +1346,8 @@ class TestMarkdownEscaping(unittest.TestCase): so the CC001 outcome is flipped to make it a finding). """ - def _scope(self, value: str) -> main.ScopeResult: - return main.ScopeResult( + def _scope(self, value: str) -> model.ScopeResult: + return model.ScopeResult( label="Commit 1/1", sha=SHA_B, checks=[ @@ -1360,13 +1364,13 @@ def _scope(self, value: str) -> main.ScopeResult: ) def test_diff_fence_outgrows_a_triple_backtick_in_the_subject(self): - diff = main._diff_block([self._scope("docs: show ``` usage")]) + diff = render._diff_block([self._scope("docs: show ``` usage")]) self.assertEqual(diff[0], "````diff") self.assertEqual(diff[2], "- docs: show ``` usage") self.assertEqual(diff[4], "````") def test_prompt_fence_outgrows_a_triple_backtick_in_the_subject(self): - how = main._how_to_fix([self._scope("docs: show ``` usage")]) + how = render._how_to_fix([self._scope("docs: show ``` usage")]) self.assertIn("````text", how) self.assertEqual(how.count("````"), 1) # The commands quote nothing of the user's, so their fence stays. @@ -1375,7 +1379,7 @@ def test_prompt_fence_outgrows_a_triple_backtick_in_the_subject(self): def test_a_subject_with_a_pipe_or_backticks_is_shown_as_it_is(self): """Every place a value lands is a code block, so nothing is escaped.""" subject = "fix: handle `None` | retry" - body = main.render_report([self._scope(subject)]) + body = render.render_report([self._scope(subject)]) self.assertIn(f"- {subject}\n", body) self.assertIn(f" ✖ 5584f46 {subject}\n", body) @@ -1383,21 +1387,21 @@ def test_capped_value_with_an_unbalanced_backtick_stays_in_its_block(self): """The cap can cut inside a backtick run.""" value = "fix: `" + "x " * 60 + "`" scope = pass_scope("Commit 1/1", value=value) - capped = main._scope_value(scope) + capped = render._scope_value(scope) self.assertTrue(capped.endswith("x…"), capped) # cut mid-span - listing = main._all_checks([scope]) + listing = render._all_checks([scope]) self.assertEqual(listing[3], "```text") self.assertEqual(listing[-3], "```") def test_details_fence_outgrows_a_triple_backtick_in_the_value(self): - details = "\n".join(main._all_checks([self._scope("docs: show ``` usage")])) + details = "\n".join(render._all_checks([self._scope("docs: show ``` usage")])) lines = details.splitlines() self.assertEqual(lines[3], "````text") self.assertEqual(lines[-3], "````") self.assertIn("value: docs: show ``` usage", details) def test_details_fence_stays_three_backticks_for_ordinary_values(self): - lines = main._all_checks([pass_scope(value="feat: add `login`")]) + lines = render._all_checks([pass_scope(value="feat: add `login`")]) self.assertEqual(lines[3], "```text") self.assertEqual(lines[-3], "```") @@ -1406,7 +1410,7 @@ class TestSkipRenderingEdgeCases(unittest.TestCase): def test_the_diff_omits_skipped_scopes(self): """A skipped scope has no failed checks, so it must not get a hunk: a blank accusation among what failed otherwise.""" - diff = main._diff_block([fail_scope("Commit 1/1"), skip_scope("PR title")]) + diff = render._diff_block([fail_scope("Commit 1/1"), skip_scope("PR title")]) self.assertEqual( diff[:5], [ @@ -1420,7 +1424,7 @@ def test_the_diff_omits_skipped_scopes(self): def test_empty_result_set_is_not_reported_as_all_skipped(self): """`skipped == total` is trivially true for no scopes at all.""" - body = main.render_report([]) + body = render.render_report([]) self.assertNotIn("skipped", body) self.assertIn("Commit Check passed\n\n
\n", body) self.assertIn("Details", body) @@ -1428,7 +1432,7 @@ def test_empty_result_set_is_not_reported_as_all_skipped(self): def test_step_log_partial_skip_does_not_claim_all_passed(self): buf = io.StringIO() with patch("sys.stdout", buf): - main.render_step_log([pass_scope(), skip_scope()]) + render.render_step_log([pass_scope(), skip_scope()]) out = buf.getvalue() self.assertIn("1 of 2 checks passed, 1 skipped", out) self.assertNotIn("all checks passed", out) @@ -1436,7 +1440,7 @@ def test_step_log_partial_skip_does_not_claim_all_passed(self): def test_step_log_all_skipped_claims_no_pass(self): buf = io.StringIO() with patch("sys.stdout", buf): - main.render_step_log([skip_scope(), skip_scope("Branch")]) + render.render_step_log([skip_scope(), skip_scope("Branch")]) out = buf.getvalue() self.assertIn(" \x1b[90m⊘\x1b[0m title skipped\n", out) self.assertTrue( @@ -1452,20 +1456,20 @@ class TestFilesInTheReport(unittest.TestCase): def test_the_first_finding_stands_for_the_scope(self): scope = files_scope(SHA_B, files_pass("3 file(s)"), *files_scope().checks) - self.assertEqual(main._first_value(scope), "big.bin (4 KB)") + self.assertEqual(render._first_value(scope), "big.bin (4 KB)") self.assertEqual( - main._first_value(files_scope(SHA_A, files_pass())), "2 file(s)" + render._first_value(files_scope(SHA_A, files_pass())), "2 file(s)" ) warned = files_scope( SHA_A, files_pass("3 file(s)"), files_pass("a.pem (pattern *.pem)", "warn") ) - self.assertEqual(main._first_value(warned), "a.pem (pattern *.pem)") - self.assertEqual(main._first_value(main.skipped_files_scope("why")), "") + self.assertEqual(render._first_value(warned), "a.pem (pattern *.pem)") + self.assertEqual(render._first_value(cli.skipped_files_scope("why")), "") def test_the_listing_names_each_commit_by_its_hash(self): results = [files_scope(SHA_A, files_pass()), files_scope()] self.assertEqual( - main._render_tree(results, include_docs=False), + render._render_tree(results, include_docs=False), [ "Files", " ✔ d87faca 2 file(s)", @@ -1484,13 +1488,13 @@ def test_the_listing_names_each_commit_by_its_hash(self): ], ) self.assertEqual( - main._render_tree([main.skipped_files_scope("why")], include_docs=False), + render._render_tree([cli.skipped_files_scope("why")], include_docs=False), ["Files", " ⊘ files skipped: why"], ) def test_the_diff_shows_each_path_with_its_advice(self): with patch.dict(os.environ, {"GITHUB_REPOSITORY": "o/r"}): - lines = main._diff_block( + lines = render._diff_block( [fail_scope("Commit 1/1", sha=SHA_B), files_scope()] ) self.assertEqual( @@ -1520,7 +1524,7 @@ def test_the_diff_shows_each_path_with_its_advice(self): def test_a_warned_finding_goes_in_the_warning_diff(self): warned = files_scope(SHA_A, files_pass("a.pem (pattern *.pem)", "warn")) warned.checks[0]["suggest"] = "Remove the file from the commit" - lines = main._diff_block([warned], "warn") + lines = render._diff_block([warned], "warn") self.assertEqual( lines[1:4], [ @@ -1533,23 +1537,23 @@ def test_a_warned_finding_goes_in_the_warning_diff(self): def test_a_finding_that_names_nothing_still_gives_its_advice(self): scope = files_scope(SHA_A, make_check("file_size", "fail", "CC302")) self.assertEqual( - main._hunk(scope, "fail"), ["@@ d87faca files @@", "# check failed"] + render._hunk(scope, "fail"), ["@@ d87faca files @@", "# check failed"] ) def test_without_a_commit_the_scope_goes_by_its_label(self): scope = files_scope("") - self.assertEqual(main._hunk(scope, "fail")[0], "@@ Files @@") + self.assertEqual(render._hunk(scope, "fail")[0], "@@ Files @@") self.assertEqual( - main._agent_prompt([scope])[1], + render._agent_prompt([scope])[1], '- Files "big.bin (4 KB)": Keep files under 1 KB, or raise max_size ' "in the [files] config", ) - self.assertEqual(main._row_label(scope), "files") + self.assertEqual(render._row_label(scope), "files") def test_unparsable_output_points_to_the_step_log(self): - scope = main.ScopeResult(label="Files", sha=SHA_A, raw_text="Traceback ...") + scope = model.ScopeResult(label="Files", sha=SHA_A, raw_text="Traceback ...") self.assertEqual( - main._hunk(scope, "fail"), + render._hunk(scope, "fail"), [ "@@ d87faca files @@", "# the output could not be parsed, see the step log", @@ -1557,7 +1561,7 @@ def test_unparsable_output_points_to_the_step_log(self): ) def test_how_to_fix_gives_each_finding_a_line_and_no_reword_commands(self): - how = "\n".join(main._how_to_fix([files_scope()])) + how = "\n".join(render._how_to_fix([files_scope()])) self.assertIn( '- Files of commit 5584f46 "big.bin (4 KB)": Keep files under 1 KB, ' "or raise max_size in the [files] config\n" @@ -1565,23 +1569,25 @@ def test_how_to_fix_gives_each_finding_a_line_and_no_reword_commands(self): "from the commit", how, ) - self.assertIn(main.FILES_HELP, how) + self.assertIn(render.FILES_HELP, how) self.assertNotIn("Reword", how) - self.assertNotIn(main.FILES_HELP, "\n".join(main._how_to_fix([fail_scope()]))) + self.assertNotIn( + render.FILES_HELP, "\n".join(render._how_to_fix([fail_scope()])) + ) def test_the_prompt_lets_the_named_files_change(self): """Taking a file out of a commit cannot be done "without changing any code".""" - self.assertEqual(main._agent_prompt([fail_scope()])[0], AGENT_PROMPT) + self.assertEqual(render._agent_prompt([fail_scope()])[0], AGENT_PROMPT) for failing in ([files_scope()], [fail_scope(), files_scope()]): self.assertEqual( - main._agent_prompt(failing)[0], + render._agent_prompt(failing)[0], "Fix these Commit Check findings, changing only the files they name:", ) def test_each_finding_is_an_annotation_about_its_own_path(self): out = io.StringIO() - with patch("sys.stdout", out), patch("main.DRY_RUN_ENABLED", False): - main.render_step_log([files_scope()]) + with patch("sys.stdout", out), patch("action.inputs.DRY_RUN_ENABLED", False): + render.render_step_log([files_scope()]) log = ANSI_CODES.sub("", out.getvalue()) self.assertIn("::group::✖ Files: failed", log) self.assertIn( @@ -1601,7 +1607,7 @@ def test_the_result_output_carries_the_commit(self): with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "output") with patch.dict(os.environ, {"GITHUB_OUTPUT": path}): - main.set_result_output([files_scope()]) + publish.set_result_output([files_scope()]) with open(path, encoding="utf-8") as f: payload = json.loads(f.read().split("\n", 1)[1].rsplit("\n", 2)[0]) self.assertEqual( @@ -1615,13 +1621,13 @@ class TestListingRows(unittest.TestCase): REASON = "author pre-commit-ci[bot] is in [commit].ignore_authors" - def _skipped_commit(self, reason: str = REASON) -> main.ScopeResult: + def _skipped_commit(self, reason: str = REASON) -> model.ScopeResult: scope = skip_scope("Commit 2/2", reason=reason) scope.sha = SHA_B scope.text = "chore: auto fixes from pre-commit.com hooks\n" return scope - def _skipped_author(self, label: str, subject: str) -> main.ScopeResult: + def _skipped_author(self, label: str, subject: str) -> model.ScopeResult: scope = skip_scope(label, reason=self.REASON) scope.sha = SHA_B scope.subject = subject @@ -1634,7 +1640,7 @@ def test_one_reason_is_said_once_and_rows_show_what_was_skipped(self): self._skipped_author("Author name", "pre-commit-ci[bot]"), self._skipped_author("Author email", "bot@users.noreply.github.com"), ] - body = main.render_report(results) + body = render.render_report(results) self.assertEqual(body.count("ignore_authors"), 1, body) self.assertIn( "Skipped because author pre-commit-ci[bot] is in ignore_authors.", body @@ -1646,7 +1652,7 @@ def test_one_reason_is_said_once_and_rows_show_what_was_skipped(self): self.assertIn(" ⊘ name pre-commit-ci[bot]\n", body) self.assertIn(" ⊘ email bot@users.noreply.github.com\n", body) with patch("sys.stdout", new_callable=io.StringIO) as out: - main.render_step_log(results) + render.render_step_log(results) self.assertIn( " ⊘ name pre-commit-ci[bot]\n", ANSI_CODES.sub("", out.getvalue()) ) @@ -1654,49 +1660,51 @@ def test_one_reason_is_said_once_and_rows_show_what_was_skipped(self): def test_rows_keep_their_reason_when_the_reasons_differ(self): other = "author dependabot[bot] is in [commit].ignore_authors" results = [self._skipped_commit(), self._skipped_commit(other)] - body = main.render_report(results) + body = render.render_report(results) self.assertIn(f"skipped: {self.REASON}\n", body) self.assertIn(f"skipped: {other}\n", body) def test_a_skip_nobody_explained_still_says_skipped(self): scope = self._skipped_commit(reason="") - self.assertFalse(main._one_skip_reason([scope])) - self.assertIn(" ⊘ ", main.render_report([scope])) - self.assertIn("skipped\n", main.render_report([scope])) + self.assertFalse(render._one_skip_reason([scope])) + self.assertIn(" ⊘ ", render.render_report([scope])) + self.assertIn("skipped\n", render.render_report([scope])) def test_a_long_subject_is_cut_at_a_word(self): subject = ( "feat: add a config-source input that reads the config from the base branch" ) scope = pass_scope("Commit 1/1", value=subject) - self.assertEqual(main._scope_value(scope), subject) # 75 characters fit + self.assertEqual(render._scope_value(scope), subject) # 75 characters fit scope = pass_scope("Commit 1/1", value=subject + " for every run") self.assertEqual( - main._scope_value(scope), + render._scope_value(scope), "feat: add a config-source input that reads the config from the base " "branch for…", ) def test_a_passing_description_says_what_was_found(self): - scope = main.ScopeResult( + scope = model.ScopeResult( label="PR description", checks=[make_check("ai_attribution", value="")] ) - self.assertEqual(main._scope_value(scope), "no AI attribution") + self.assertEqual(render._scope_value(scope), "no AI attribution") scope.ai_tools = ["Claude Code"] - self.assertEqual(main._scope_value(scope), "AI attribution: Claude Code") + self.assertEqual(render._scope_value(scope), "AI attribution: Claude Code") def test_each_author_scope_carries_the_author_it_checked(self): with ( - patch("main._local_author", return_value=("Dev", "dev@example.org")), - patch("main._rev_resolves", return_value=True), patch( - "main.check_scope", - side_effect=lambda label, args, sha: main.ScopeResult( + "action.context._local_author", return_value=("Dev", "dev@example.org") + ), + patch("action.context._rev_resolves", return_value=True), + patch( + "action.cli.check_scope", + side_effect=lambda label, args, sha: model.ScopeResult( label=label, sha=sha ), ), ): - results = main.run_pr_author_checks( + results = cli.run_pr_author_checks( ["--author-name", "--author-email"], [("a1", "feat: one")] ) self.assertEqual(