Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·2557 lines (2153 loc) · 101 KB
/
Copy pathmain.py
File metadata and controls
executable file
·2557 lines (2153 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""GitHub Action that runs commit-check and renders results.
The action runs ``commit-check --format json`` to collect structured check
results (rule IDs, error messages, suggestions, docs links), then renders
them to three output surfaces:
* **step log** — grouped sections, then one ``::error`` annotation per finding
* **job summary** — a Markdown report: the verdict, then a diff of what failed
* **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 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 = "<!-- commit-check-action -->"
#: 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",
}
#: 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")
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")
#: 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)
@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",
"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}")
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/<number>/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 <noreply@github.com>`` 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)
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 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)
#: Rules about a commit rather than about a line of text: it has a body
#: (CC011), a sign-off (CC012), an author that is no AI tool (CC017). A pull
#: request title has neither body nor trailers nor an author of its own, so
#: judged as a commit message it could never pass the first two, and the
#: third would judge whatever git identity the runner has.
COMMIT_ONLY_RULE_IDS = frozenset({"CC011", "CC012", "CC017"})
def drop_commit_only_rules(scope: ScopeResult) -> ScopeResult:
"""Narrow the PR title scope to the rules a one-line title can meet."""
scope.checks = [
c for c in scope.checks if c.get("rule_id") not in COMMIT_ONLY_RULE_IDS
]
return 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/<base-ref>`` 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"] + 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 []
return [
check_scope(CHECK_LABELS[flag], [flag, "--rev", sha], sha=sha)
for flag in flags
for sha in revs
]
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. 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:
scope = check_scope("PR title", ["--message"], input_text=pr_title)
results.append(drop_commit_only_rules(scope))
# ---- 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:
scope = check_scope(
"PR description", ["--ai-attribution-only"], input_text=pr_body
)