-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1643 lines (1387 loc) · 64.9 KB
/
Copy pathmain.py
File metadata and controls
executable file
·1643 lines (1387 loc) · 64.9 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 policy report table
* **PR comment** — a compact Markdown summary (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 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 -->"
#: Report heading. h2 rather than h1: this renders inside a PR comment, where an
#: h1 is louder than anything else on the page.
#
# Deliberately carries no logo. The org mark is a check inside a rounded tile,
# which is the same object GitHub's ✅ is — same shape, same silhouette, only
# the hue differs. Putting it immediately above the verdict line meant a failing
# report opened with a tick and then said "❌ 2 of 4 checks failed": the first
# symbol the eye lands on contradicted the second, and it did so precisely when
# the reader most needs to read the result quickly.
#
# The verdict line is the one status signal in this report, and one is the right
# number. "Commit Check" in words is unambiguous branding; a checkmark next to a
# failure is not.
#
# Do not "fix" this by showing the logo only on success — that makes the logo's
# presence itself a status signal, which is the same defect wearing a hat.
REPORT_TITLE = "## Commit Check"
#: 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",
}
def env_flag(name: str, default: str = "false") -> bool:
"""Read a GitHub Action boolean-style environment variable."""
return os.getenv(name, default).lower() == "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")
@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 = ""
@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 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",
):
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:
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}}"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
check=False,
)
except OSError:
return False
return result.returncode == 0
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.
``None`` when the clone is too shallow to hold either.
"""
sha = get_pr_head_sha()
if sha and _rev_resolves(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": "",
}
],
)
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:
print(f"::warning::Failed to read PR title from event: {e}", file=sys.stderr)
return None
#: 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. Commits are paired
before empty messages are dropped, so a blank message never shifts the
hashes of the commits after 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 message
]
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],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
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"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
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")
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.
"""
if not is_pr_event():
return []
try:
messages = get_messages_from_event_range()
if messages:
return messages
messages = get_messages_from_merge_ref()
if messages:
return messages
base_ref = os.getenv("GITHUB_BASE_REF", "")
if base_ref:
return get_messages_from_head_ref(base_ref)
except Exception as e:
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: {line}", file=sys.stderr)
def run_check_json(
args: list[str], input_text: 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,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
check=False,
)
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 = ""
) -> 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)
if isinstance(data, dict):
return ScopeResult(label=label, checks=data.get("checks", []), sha=sha)
return ScopeResult(label=label, raw_text=raw, sha=sha)
def run_pr_message_checks(pr_commits: list[Commit]) -> list[ScopeResult]:
"""Check each PR commit message individually via commit-check --message."""
results: list[ScopeResult] = []
total = len(pr_commits)
for index, (sha, msg) in enumerate(pr_commits, start=1):
results.append(
check_scope(
f"Commit {index}/{total}", ["--message"], input_text=msg, sha=sha
)
)
return results
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),
("--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. Individual PR commit messages (when ``message: true`` and in a PR event)
3. All remaining checks (branch, author name/email, etc.)
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:
results.append(check_scope("PR title", ["--message"], input_text=pr_title))
# ---- 2. Commit message checks -----------------------------------------
if MESSAGE_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"
)
# ---- 3. Remaining checks (branch, author, etc.) -----------------------
# Outside a PR, check the HEAD commit message directly.
if "--message" in args:
results.append(check_scope("Commit message", ["--message"], sha=head_sha()))
args = [a for a in args if a != "--message"]
rev = None
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
# ---------------------------------------------------------------------------
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_markdown_link(check: dict[str, str]) -> str:
"""Markdown link for a check: ``[CC001 message](docs_url)``."""
label = _rule_label(check)
docs_url = check.get("docs_url", "")
return f"[{label}]({docs_url})" if docs_url else label
def _scope_group(label: str) -> str:
"""Group name for a scope label, used to fold the step log output."""
if label == "PR title" or label.startswith("Commit"):
return "Commit message"
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 _finding_lines(check: dict[str, str], include_error: bool) -> list[str]:
"""The detail a reader needs to act on one finding, one item per line.
``value:`` (what was checked), the error (when ``include_error``),
``Suggest:`` and ``Fix:`` — each only when the CLI filled it in. This is
the single source for both the tree and the annotation payload, so the
two cannot drift; the error is optional because the annotation carries
its first line in the headline instead.
``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 "<fix>"``,
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)
if include_error:
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:
lines.append(f" {_rule_label(check)}")
detail = _finding_lines(check, include_error=True)
lines.extend(f" {line}" for line in detail)
if include_docs and check.get("docs_url"):
lines.append(f" Docs: {check['docs_url']}")
return lines
def _render_scopes(scopes: list[ScopeResult], include_docs: bool) -> 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 details block are the same tree, and the only difference is the
docs link, which the Markdown report already carries on the rule ID in the
table above it.
A failing or warned scope shows its value in full rather than truncated.
It is the one value the reader has to act on, and the table's 60-character
cap can cut off the part that explains it.
"""
lines: list[str] = []
for scope in scopes:
label = scope.display_label
if scope.status == "skip":
# Deliberately not a ✔. Nothing was validated here, and a tick
# claiming otherwise is what made a bypassed policy look enforced.
lines.append(f" ⊘ {label} (skipped)")
continue
if scope.status == "pass":
value = _scope_value(scope)
lines.append(f" ✔ {label}{f' ({value})' if value else ''}")
continue
if scope.raw_text and not scope.checks:
# Defensive fallback: commit-check produced unexpected output.
lines.append(f" ✖ {label}")
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. Render whichever of the
# two lists is non-empty, rather than only the one the status names —
# a warning on an otherwise-failing scope is still a finding to fix.
failures = scope.failures
if failures:
count = f" ({len(failures)} failure{'s' if len(failures) != 1 else ''})"
lines.append(f" ✖ {label}{count}")
lines.extend(_render_findings(failures, include_docs))
warnings = scope.warnings
if warnings:
count = f" ({len(warnings)} warning{'s' if len(warnings) != 1 else ''})"
lines.append(f" ⚠ {label}{count}")
lines.extend(_render_findings(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] = []
for group_name, scopes in _grouped(results):
lines.append(group_name)
lines.extend(_render_scopes(scopes, include_docs))
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")
def _annotation_body(scope: ScopeResult, check: dict[str, str]) -> str:
"""The message of one finding's annotation, before escaping.
First line: which commit and what rule said, ``Commit 2/3 (5584f46):
Subject must start with a capital letter``. Then the same value /
Suggest / Fix rows the tree prints, so the annotation on the Files
changed tab is enough to act on without opening the step log. GitHub
renders the escaped newlines as line breaks.
"""
error = check.get("error", "")
fallback = "check warning" if check.get("status") == "warn" else "check failed"
first_line = error.splitlines()[0] if error else fallback
lines = [f"{scope.display_label}: {first_line}"]
lines.extend(_finding_lines(check, include_error=False))
return "\n".join(lines)
def render_step_log(results: list[ScopeResult]) -> None:
"""Print results to the step log, then emit one annotation per finding.
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=`` \u2014 which is what carries the rule ID \u2014 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 in the run summary and on the Files changed tab — where
the annotation is all a reader has, so its message repeats the value,
suggestion and fix from the tree (``_annotation_body``), one per line.
A failure becomes an ``::error``, a warning a ``::warning`` \u2014 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.
for group_name, scopes in _grouped(results):
print(f"::group::{group_name}")
for line in _render_scopes(scopes, include_docs=True):
print(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", {warned} warning{'s' if warned != 1 else ''}"
print(verdict)
if not errors:
skipped, warned, total = (
_skip_count(results),
_warn_count(results),
len(results),
)
if total and skipped == total:
print("\u2298 commit-check: all checks skipped, nothing was validated")
elif warned or skipped:
passed = total - skipped - warned
tail = []
if warned:
tail.append(f"{warned} warning{'s' if warned != 1 else ''}")
if skipped:
tail.append(f"{skipped} skipped")
print(
f"\u2714 commit-check: {passed} of {total} checks passed, {', '.join(tail)}"
)
else:
print("\u2714 commit-check: all checks passed")
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 \u2014 one commit message, the branch, the author name
\u2014 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 \u2014 one bad commit out of fifteen reads very differently from
1 of 100.
This number matches what the reader can count: the rows in the table plus
the \u2714/\u2716 lines in the details block. Which rules failed is not lost, it is
just reported where it belongs \u2014 in the table and the details.
"""
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 _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 and the table use
to decide whether to show them.
"""
return sum(1 for scope in results if scope.warnings)
def _markdown_table(
results: list[ScopeResult], status: str = "fail", header: str = "Failed checks"
) -> str:
"""Render the failure or warning table shared by summary and PR comment.
A scope appears when it has an entry of the requested kind \u2014 checked via
``scope.failures`` / ``scope.warnings``, not ``scope.status`` \u2014 so a scope
that both failed and warned gets a row in both tables. Filtering on the
scope's single overall status would silently drop its warnings once a
failure in the same scope outranked them.
"""
rows = [