commit-check 2.22.0__py3-none-any.whl → 2.23.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- commit_check/__init__.py +11 -0
- commit_check/ci.py +487 -0
- commit_check/engine.py +138 -4
- commit_check/main.py +38 -2
- commit_check/rule_builder.py +2 -3
- commit_check/util.py +63 -10
- {commit_check-2.22.0.dist-info → commit_check-2.23.1.dist-info}/METADATA +9 -8
- {commit_check-2.22.0.dist-info → commit_check-2.23.1.dist-info}/RECORD +12 -11
- {commit_check-2.22.0.dist-info → commit_check-2.23.1.dist-info}/entry_points.txt +1 -0
- {commit_check-2.22.0.dist-info → commit_check-2.23.1.dist-info}/WHEEL +0 -0
- {commit_check-2.22.0.dist-info → commit_check-2.23.1.dist-info}/licenses/LICENSE +0 -0
- {commit_check-2.22.0.dist-info → commit_check-2.23.1.dist-info}/top_level.txt +0 -0
commit_check/__init__.py
CHANGED
|
@@ -65,6 +65,10 @@ DEFAULT_COMMIT_TYPES = [
|
|
|
65
65
|
"perf",
|
|
66
66
|
"build",
|
|
67
67
|
"ci",
|
|
68
|
+
# The type the Conventional Commits FAQ recommends for a revert written
|
|
69
|
+
# by hand ("revert: ..."), also in commitlint's config-conventional.
|
|
70
|
+
# v1 accepted it; git's own 'Revert "..."' subjects are a separate case.
|
|
71
|
+
"revert",
|
|
68
72
|
]
|
|
69
73
|
# Follow conventional branch (https://conventionalbranch.org/)
|
|
70
74
|
# Includes AI agent prefixes (spec v1.1.0) and bot prefixes
|
|
@@ -131,6 +135,13 @@ GIT_MERGE_SUBJECT_PATTERN = (
|
|
|
131
135
|
r"|[a-z][a-z0-9+.-]*://|[\w.-]+@[\w.-]+:)"
|
|
132
136
|
)
|
|
133
137
|
|
|
138
|
+
# The subjects `git revert` writes: 'Revert "<subject>"', and since git 2.43
|
|
139
|
+
# 'Reapply "<subject>"' when the commit reverted is itself a revert. GitHub's
|
|
140
|
+
# and GitLab's revert buttons write the same 'Revert "' subject. Their length
|
|
141
|
+
# and format are git's doing, not the author's; CC007 alone decides whether
|
|
142
|
+
# they are allowed. Unanchored, like GIT_MERGE_SUBJECT_PATTERN.
|
|
143
|
+
GIT_REVERT_SUBJECT_PATTERN = r'(?:Revert|Reapply) "'
|
|
144
|
+
|
|
134
145
|
# Push-related defaults
|
|
135
146
|
DEFAULT_PUSH_RULES = {
|
|
136
147
|
"allow_force_push": True,
|
commit_check/ci.py
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""Check the merge or pull request a CI job runs for: ``commit-check-ci``.
|
|
2
|
+
|
|
3
|
+
GitHub has the Commit Check Action for this. On GitLab CI and Bitbucket
|
|
4
|
+
Pipelines a job runs this command instead: it finds the request from the
|
|
5
|
+
variables the CI system sets, and runs ``commit-check`` on the source branch,
|
|
6
|
+
on the request's title and description, and once for every commit the request
|
|
7
|
+
adds.
|
|
8
|
+
|
|
9
|
+
Each check is switched on or off by an option named after the Action's input:
|
|
10
|
+
``--author-email`` or ``--author-email=true`` to run it, ``--message=false``
|
|
11
|
+
to leave it out. The ``=true`` and ``=false`` forms are there for CI templates,
|
|
12
|
+
which fill in a value.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import urllib.error
|
|
24
|
+
import urllib.request
|
|
25
|
+
from collections.abc import Mapping, Sequence
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from .config_merger import ConfigMerger
|
|
30
|
+
from .main import _VersionAction
|
|
31
|
+
|
|
32
|
+
# Option name -> on by default. The names are the Action's input names.
|
|
33
|
+
CHECKS: dict[str, bool] = {
|
|
34
|
+
"message": True,
|
|
35
|
+
"branch": True,
|
|
36
|
+
"author-name": False,
|
|
37
|
+
"author-email": False,
|
|
38
|
+
"files": False,
|
|
39
|
+
"pr-title": False,
|
|
40
|
+
"pr-body-ai-attribution": False,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
# The checks that run once for every commit, with the commit-check flag each one is.
|
|
44
|
+
COMMIT_CHECKS = ("message", "author-name", "author-email", "files")
|
|
45
|
+
|
|
46
|
+
HELP = {
|
|
47
|
+
"message": "check the message of every commit the request adds",
|
|
48
|
+
"branch": "check the name of the source branch",
|
|
49
|
+
"author-name": "check the author name of every commit",
|
|
50
|
+
"author-email": "check the author email of every commit",
|
|
51
|
+
"files": "check the files every commit changes against the [files] rules",
|
|
52
|
+
"pr-title": "check the title against the commit message rules",
|
|
53
|
+
"pr-body-ai-attribution": (
|
|
54
|
+
"check the description against the AI attribution rules"
|
|
55
|
+
),
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
BITBUCKET_API = "https://api.bitbucket.org/2.0"
|
|
59
|
+
|
|
60
|
+
# GitLab passes at most this much of a description to a job.
|
|
61
|
+
GITLAB_DESCRIPTION_LIMIT = 2700
|
|
62
|
+
|
|
63
|
+
# What marks a GitLab merge request as a draft. A draft cannot be merged, so
|
|
64
|
+
# the marker is never part of the title that lands.
|
|
65
|
+
GITLAB_DRAFT_MARKER = re.compile(
|
|
66
|
+
r"\A\s*(?:(?:\[draft\]|\(draft\)|draft:)\s*)+", re.IGNORECASE
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Stop(Exception):
|
|
71
|
+
"""The job cannot do what it was asked; the message says why."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
75
|
+
"""Refuse every redirect: one would carry the access token elsewhere."""
|
|
76
|
+
|
|
77
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
|
|
78
|
+
raise urllib.error.URLError(f"redirect to {newurl} refused")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class Request:
|
|
83
|
+
"""The merge or pull request this job runs for."""
|
|
84
|
+
|
|
85
|
+
forge: str
|
|
86
|
+
noun: str
|
|
87
|
+
target: str
|
|
88
|
+
"""The branch it merges into."""
|
|
89
|
+
base: str
|
|
90
|
+
"""The commit its own commits start after."""
|
|
91
|
+
head: str
|
|
92
|
+
"""Its own last commit, which is not always the commit checked out."""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def parse_bool(option: str, text: str) -> bool:
|
|
96
|
+
value = text.strip().lower()
|
|
97
|
+
if value == "true":
|
|
98
|
+
return True
|
|
99
|
+
if value == "false":
|
|
100
|
+
return False
|
|
101
|
+
raise Stop(f"--{option} must be true or false, got {text!r}")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_settings(argv: Sequence[str] | None) -> dict[str, bool]:
|
|
105
|
+
"""Which checks to run: the option when it is given, else the default."""
|
|
106
|
+
parser = argparse.ArgumentParser(
|
|
107
|
+
prog="commit-check-ci",
|
|
108
|
+
description=(
|
|
109
|
+
"Check the merge or pull request this CI job runs for, on GitLab CI "
|
|
110
|
+
"or Bitbucket Pipelines: the source branch, the title, the "
|
|
111
|
+
"description, and every commit the request adds. Outside a merge or "
|
|
112
|
+
"pull request it checks the branch and the last commit."
|
|
113
|
+
),
|
|
114
|
+
epilog=(
|
|
115
|
+
"Rules come from cchk.toml, as for commit-check. On Bitbucket the "
|
|
116
|
+
"title and description are read from its API with the access token "
|
|
117
|
+
"in $BITBUCKET_ACCESS_TOKEN. Docs: https://commit-check.com/"
|
|
118
|
+
),
|
|
119
|
+
allow_abbrev=False,
|
|
120
|
+
)
|
|
121
|
+
parser.add_argument("-v", "--version", action=_VersionAction)
|
|
122
|
+
for option, default in CHECKS.items():
|
|
123
|
+
parser.add_argument(
|
|
124
|
+
f"--{option}",
|
|
125
|
+
nargs="?",
|
|
126
|
+
const="true",
|
|
127
|
+
metavar="true|false",
|
|
128
|
+
help=f"{HELP[option]} (default: {str(default).lower()})",
|
|
129
|
+
)
|
|
130
|
+
args = vars(parser.parse_args(argv))
|
|
131
|
+
settings = {}
|
|
132
|
+
for option, default in CHECKS.items():
|
|
133
|
+
given = args[option.replace("-", "_")]
|
|
134
|
+
settings[option] = default if given is None else parse_bool(option, given)
|
|
135
|
+
return settings
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def find_request(env: Mapping[str, str]) -> Request | None:
|
|
139
|
+
"""The merge or pull request named by the CI system's variables."""
|
|
140
|
+
if env.get("CI_MERGE_REQUEST_IID"):
|
|
141
|
+
return Request(
|
|
142
|
+
forge="GitLab",
|
|
143
|
+
noun="merge request",
|
|
144
|
+
target=env.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", ""),
|
|
145
|
+
base=env.get("CI_MERGE_REQUEST_DIFF_BASE_SHA", ""),
|
|
146
|
+
# A merged results pipeline checks out a merge commit GitLab made
|
|
147
|
+
# and names the request's own last commit here. In any other merge
|
|
148
|
+
# request pipeline this is empty and the checkout is that commit.
|
|
149
|
+
head=env.get("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA")
|
|
150
|
+
or env.get("CI_COMMIT_SHA", ""),
|
|
151
|
+
)
|
|
152
|
+
if env.get("BITBUCKET_PR_ID"):
|
|
153
|
+
return Request(
|
|
154
|
+
forge="Bitbucket",
|
|
155
|
+
noun="pull request",
|
|
156
|
+
target=env.get("BITBUCKET_PR_DESTINATION_BRANCH", ""),
|
|
157
|
+
base=env.get("BITBUCKET_PR_DESTINATION_COMMIT", ""),
|
|
158
|
+
# Bitbucket merges the destination into the checkout before the
|
|
159
|
+
# step runs; this is the pull request's own last commit.
|
|
160
|
+
head=env.get("BITBUCKET_COMMIT", ""),
|
|
161
|
+
)
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def git(*args: str) -> subprocess.CompletedProcess[str]:
|
|
166
|
+
return subprocess.run(
|
|
167
|
+
["git", *args],
|
|
168
|
+
capture_output=True,
|
|
169
|
+
text=True,
|
|
170
|
+
encoding="utf-8",
|
|
171
|
+
errors="replace",
|
|
172
|
+
check=False,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def resolve_commit(rev: str) -> str:
|
|
177
|
+
"""The full id of the commit ``rev`` names, or ``""`` when the clone lacks it."""
|
|
178
|
+
if not rev:
|
|
179
|
+
return ""
|
|
180
|
+
result = git(
|
|
181
|
+
"rev-parse", "--verify", "--quiet", "--end-of-options", f"{rev}^{{commit}}"
|
|
182
|
+
)
|
|
183
|
+
return result.stdout.strip() if result.returncode == 0 else ""
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def subject_of(rev: str) -> str:
|
|
187
|
+
"""The commit's subject line, safe to print: it is text anyone can write."""
|
|
188
|
+
subject = git("log", "-1", "--format=%s", "--end-of-options", rev).stdout.strip()
|
|
189
|
+
return "".join(char if char.isprintable() else "?" for char in subject)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def is_ancestor(commit: str, of: str) -> bool:
|
|
193
|
+
return git("merge-base", "--is-ancestor", commit, of).returncode == 0
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def shallow_ends() -> set[str]:
|
|
197
|
+
"""The commits a shallow clone stops at: their parents were not fetched."""
|
|
198
|
+
path = git("rev-parse", "--git-path", "shallow").stdout.strip()
|
|
199
|
+
try:
|
|
200
|
+
return set(Path(path).read_text(encoding="ascii").split())
|
|
201
|
+
except OSError:
|
|
202
|
+
return set()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def shallow_hint(request: Request) -> str:
|
|
206
|
+
if git("rev-parse", "--is-shallow-repository").stdout.strip() != "true":
|
|
207
|
+
return ""
|
|
208
|
+
if request.forge == "GitLab":
|
|
209
|
+
return ' The clone is shallow: set GIT_DEPTH to "0" for this job.'
|
|
210
|
+
return " The clone is shallow: set `clone: depth: full` on this step."
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def rebase_check_is_on() -> bool:
|
|
214
|
+
"""Whether ``require_rebase_target`` is set, by the file or the environment.
|
|
215
|
+
|
|
216
|
+
It is the one rule that reads the target branch.
|
|
217
|
+
"""
|
|
218
|
+
try:
|
|
219
|
+
config = ConfigMerger.from_all_sources(argparse.Namespace())
|
|
220
|
+
except (OSError, ValueError):
|
|
221
|
+
# commit-check says what is wrong with the configuration when it runs.
|
|
222
|
+
return True
|
|
223
|
+
branch = config.get("branch")
|
|
224
|
+
return isinstance(branch, dict) and bool(branch.get("require_rebase_target"))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def prepare_target(request: Request, env: Mapping[str, str]) -> None:
|
|
228
|
+
"""Make ``origin/<target>`` exist, which the rebase check (CC202) reads.
|
|
229
|
+
|
|
230
|
+
Neither system fetches the target branch for a merge or pull request.
|
|
231
|
+
Without it the rule reports itself as skipped and the job would pass with
|
|
232
|
+
a branch that was never compared.
|
|
233
|
+
"""
|
|
234
|
+
if not request.target:
|
|
235
|
+
raise Stop(f"the {request.noun}'s target branch is not set in the environment")
|
|
236
|
+
ref = f"refs/remotes/origin/{request.target}"
|
|
237
|
+
if request.forge == "GitLab":
|
|
238
|
+
# A pipeline that runs in a fork has the fork as origin; the target
|
|
239
|
+
# branch lives in the project the merge request was opened against.
|
|
240
|
+
source = "origin"
|
|
241
|
+
target_project = env.get("CI_MERGE_REQUEST_PROJECT_ID")
|
|
242
|
+
if target_project and target_project != env.get("CI_PROJECT_ID"):
|
|
243
|
+
source = env.get("CI_MERGE_REQUEST_PROJECT_URL", "") + ".git"
|
|
244
|
+
fetch = git(
|
|
245
|
+
"fetch",
|
|
246
|
+
"--quiet",
|
|
247
|
+
"--no-tags",
|
|
248
|
+
source,
|
|
249
|
+
f"+refs/heads/{request.target}:{ref}",
|
|
250
|
+
)
|
|
251
|
+
if fetch.returncode != 0:
|
|
252
|
+
raise Stop(
|
|
253
|
+
f"could not fetch the target branch {request.target!r} from {source}, "
|
|
254
|
+
f"which the rebase check needs: {fetch.stderr.strip()}"
|
|
255
|
+
)
|
|
256
|
+
return
|
|
257
|
+
# Nothing is fetched on Bitbucket: the step already merged the destination
|
|
258
|
+
# commit into the checkout, so the clone holds it.
|
|
259
|
+
commit = resolve_commit(request.base)
|
|
260
|
+
if not commit:
|
|
261
|
+
raise Stop(
|
|
262
|
+
f"the destination commit {request.base!r} is not in the clone, "
|
|
263
|
+
f"so the rebase check has nothing to compare with.{shallow_hint(request)}"
|
|
264
|
+
)
|
|
265
|
+
if resolve_commit(ref) and is_ancestor(commit, ref):
|
|
266
|
+
# The clone's own ref is at the destination commit or past it. One
|
|
267
|
+
# that is behind it would let a branch pass that is not rebased.
|
|
268
|
+
return
|
|
269
|
+
update = git("update-ref", ref, commit)
|
|
270
|
+
if update.returncode != 0:
|
|
271
|
+
raise Stop(f"could not write {ref}: {update.stderr.strip()}")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def request_commits(request: Request) -> list[str]:
|
|
275
|
+
"""The commits the request adds, oldest first."""
|
|
276
|
+
result = git(
|
|
277
|
+
"rev-list", "--reverse", "--end-of-options", f"{request.base}..{request.head}"
|
|
278
|
+
)
|
|
279
|
+
if not request.base or not request.head or result.returncode != 0:
|
|
280
|
+
raise Stop(
|
|
281
|
+
f"could not list the {request.noun}'s commits "
|
|
282
|
+
f"({request.base or '?'}..{request.head or '?'}).{shallow_hint(request)}"
|
|
283
|
+
)
|
|
284
|
+
commits = result.stdout.split()
|
|
285
|
+
# git lists a range that runs into the end of a shallow clone without an
|
|
286
|
+
# error: the commits beyond it are simply absent, and would go unchecked.
|
|
287
|
+
if shallow_ends().intersection(commits):
|
|
288
|
+
raise Stop(
|
|
289
|
+
f"the clone ends inside the {request.noun}, so its older commits "
|
|
290
|
+
f"cannot be read.{shallow_hint(request)}"
|
|
291
|
+
)
|
|
292
|
+
return commits
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def bitbucket_pull_request(env: Mapping[str, str]) -> dict[str, object]:
|
|
296
|
+
"""Read the pull request from the Bitbucket API, which is where its text is."""
|
|
297
|
+
token = env.get("BITBUCKET_ACCESS_TOKEN", "").strip()
|
|
298
|
+
if not token:
|
|
299
|
+
raise Stop(
|
|
300
|
+
"Bitbucket does not pass a pull request's title or description to "
|
|
301
|
+
"the step. Set BITBUCKET_ACCESS_TOKEN to an access token with the "
|
|
302
|
+
"Pull requests: Read scope so they can be read from the API."
|
|
303
|
+
)
|
|
304
|
+
repository = env.get("BITBUCKET_REPO_FULL_NAME") or "/".join(
|
|
305
|
+
(
|
|
306
|
+
env.get("BITBUCKET_WORKSPACE") or env.get("BITBUCKET_REPO_OWNER", ""),
|
|
307
|
+
env.get("BITBUCKET_REPO_SLUG", ""),
|
|
308
|
+
)
|
|
309
|
+
)
|
|
310
|
+
number = env.get("BITBUCKET_PR_ID", "")
|
|
311
|
+
if (
|
|
312
|
+
not number.isdigit()
|
|
313
|
+
or repository.count("/") != 1
|
|
314
|
+
or "" in repository.split("/")
|
|
315
|
+
):
|
|
316
|
+
raise Stop("the pull request's repository or id is not set in the environment")
|
|
317
|
+
api_request = urllib.request.Request(
|
|
318
|
+
f"{BITBUCKET_API}/repositories/{repository}/pullrequests/{number}",
|
|
319
|
+
headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
|
|
320
|
+
)
|
|
321
|
+
try:
|
|
322
|
+
with urllib.request.build_opener(NoRedirect()).open(
|
|
323
|
+
api_request, timeout=30
|
|
324
|
+
) as response:
|
|
325
|
+
pull_request = json.load(response)
|
|
326
|
+
except (urllib.error.URLError, TimeoutError, ValueError) as error:
|
|
327
|
+
raise Stop(
|
|
328
|
+
f"could not read the pull request from the Bitbucket API: {error}"
|
|
329
|
+
) from None
|
|
330
|
+
if not isinstance(pull_request, dict):
|
|
331
|
+
raise Stop("the Bitbucket API did not return a pull request")
|
|
332
|
+
return pull_request
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class Job:
|
|
336
|
+
"""Runs the checks and remembers the worst result."""
|
|
337
|
+
|
|
338
|
+
def __init__(self, settings: dict[str, bool], env: Mapping[str, str]) -> None:
|
|
339
|
+
self.settings = settings
|
|
340
|
+
self.env = env
|
|
341
|
+
self.ran = 0
|
|
342
|
+
self.failed = 0
|
|
343
|
+
self.exit_code = 0
|
|
344
|
+
self._pull_request: dict[str, object] | None = None
|
|
345
|
+
|
|
346
|
+
def check(self, heading: str, args: list[str], text: str | None = None) -> None:
|
|
347
|
+
"""Run one ``commit-check`` call under a heading of its own."""
|
|
348
|
+
print(heading, flush=True)
|
|
349
|
+
result = subprocess.run(
|
|
350
|
+
# -P: -m would otherwise put the working directory, which is the
|
|
351
|
+
# request's checkout, ahead of the installed package and the
|
|
352
|
+
# standard library on the module search path.
|
|
353
|
+
[sys.executable, "-P", "-m", "commit_check.main", *args, "--no-banner"],
|
|
354
|
+
# A check that is given no text reads none: whatever the runner
|
|
355
|
+
# left on standard input is not the branch name or the message.
|
|
356
|
+
input=b"" if text is None else text.encode("utf-8"),
|
|
357
|
+
check=False,
|
|
358
|
+
)
|
|
359
|
+
self.ran += 1
|
|
360
|
+
if result.returncode == 0:
|
|
361
|
+
print(" passed", flush=True)
|
|
362
|
+
return
|
|
363
|
+
self.failed += 1
|
|
364
|
+
# A commit-check killed by a signal reports a negative code; it failed too.
|
|
365
|
+
self.exit_code = max(self.exit_code, result.returncode, 1)
|
|
366
|
+
|
|
367
|
+
def stop(self, heading: str, error: Stop) -> None:
|
|
368
|
+
"""Count a check that could not run as failed, and say why."""
|
|
369
|
+
print(heading, flush=True)
|
|
370
|
+
print(f" Error: {error}", flush=True)
|
|
371
|
+
self.ran += 1
|
|
372
|
+
self.failed += 1
|
|
373
|
+
self.exit_code = max(self.exit_code, 1)
|
|
374
|
+
|
|
375
|
+
def request_text(self, request: Request, field: str) -> str:
|
|
376
|
+
"""The request's ``title`` or ``description``."""
|
|
377
|
+
if request.forge == "GitLab":
|
|
378
|
+
text = self.env.get(f"CI_MERGE_REQUEST_{field.upper()}", "")
|
|
379
|
+
return GITLAB_DRAFT_MARKER.sub("", text) if field == "title" else text
|
|
380
|
+
if self._pull_request is None:
|
|
381
|
+
self._pull_request = bitbucket_pull_request(self.env)
|
|
382
|
+
value = self._pull_request.get(field)
|
|
383
|
+
return value if isinstance(value, str) else ""
|
|
384
|
+
|
|
385
|
+
def run(self) -> int:
|
|
386
|
+
request = find_request(self.env)
|
|
387
|
+
if request is None:
|
|
388
|
+
self.run_without_request()
|
|
389
|
+
else:
|
|
390
|
+
self.run_for(request)
|
|
391
|
+
if self.ran == 0:
|
|
392
|
+
print("Every check is switched off; nothing was checked.", flush=True)
|
|
393
|
+
elif self.failed:
|
|
394
|
+
print(f"\n{self.failed} of {self.ran} failed.", flush=True)
|
|
395
|
+
else:
|
|
396
|
+
print(f"\nAll {self.ran} passed.", flush=True)
|
|
397
|
+
return self.exit_code
|
|
398
|
+
|
|
399
|
+
def run_for(self, request: Request) -> None:
|
|
400
|
+
if self.settings["branch"]:
|
|
401
|
+
self.check_branch(request)
|
|
402
|
+
if self.settings["pr-title"]:
|
|
403
|
+
self.check_title(request)
|
|
404
|
+
if self.settings["pr-body-ai-attribution"]:
|
|
405
|
+
self.check_description(request)
|
|
406
|
+
flags = [f"--{name}" for name in COMMIT_CHECKS if self.settings[name]]
|
|
407
|
+
if flags:
|
|
408
|
+
self.check_commits(request, flags)
|
|
409
|
+
|
|
410
|
+
def check_branch(self, request: Request) -> None:
|
|
411
|
+
try:
|
|
412
|
+
prepare_target(request, self.env)
|
|
413
|
+
except Stop as error:
|
|
414
|
+
# Only the rebase check reads the target branch. A pipeline that
|
|
415
|
+
# runs in a fork of a private project cannot fetch it at all, and
|
|
416
|
+
# without that rule there is nothing the fetch was needed for.
|
|
417
|
+
if rebase_check_is_on():
|
|
418
|
+
self.stop("Branch", error)
|
|
419
|
+
return
|
|
420
|
+
self.check("Branch", ["--branch"])
|
|
421
|
+
|
|
422
|
+
def check_title(self, request: Request) -> None:
|
|
423
|
+
heading = f"{request.noun.capitalize()} title"
|
|
424
|
+
try:
|
|
425
|
+
title = self.request_text(request, "title")
|
|
426
|
+
except Stop as error:
|
|
427
|
+
self.stop(heading, error)
|
|
428
|
+
return
|
|
429
|
+
self.check(heading, ["--pr-title"], text=title + "\n")
|
|
430
|
+
|
|
431
|
+
def check_description(self, request: Request) -> None:
|
|
432
|
+
heading = f"{request.noun.capitalize()} description"
|
|
433
|
+
try:
|
|
434
|
+
description = self.request_text(request, "description")
|
|
435
|
+
except Stop as error:
|
|
436
|
+
self.stop(heading, error)
|
|
437
|
+
return
|
|
438
|
+
if self.env.get("CI_MERGE_REQUEST_DESCRIPTION_IS_TRUNCATED") == "true":
|
|
439
|
+
print(
|
|
440
|
+
f"Note: GitLab passed only the first {GITLAB_DESCRIPTION_LIMIT} "
|
|
441
|
+
"characters of the description, so only that part is checked.",
|
|
442
|
+
flush=True,
|
|
443
|
+
)
|
|
444
|
+
self.check(heading, ["--ai-attribution-only"], text=description + "\n")
|
|
445
|
+
|
|
446
|
+
def check_commits(self, request: Request, flags: list[str]) -> None:
|
|
447
|
+
"""Run the per-commit checks on every commit the request adds."""
|
|
448
|
+
try:
|
|
449
|
+
commits = request_commits(request)
|
|
450
|
+
except Stop as error:
|
|
451
|
+
self.stop("Commits", error)
|
|
452
|
+
return
|
|
453
|
+
if not commits:
|
|
454
|
+
print(f"The {request.noun} adds no commits.", flush=True)
|
|
455
|
+
for sha in commits:
|
|
456
|
+
self.check(f"Commit {sha[:8]} {subject_of(sha)}", [*flags, "--rev", sha])
|
|
457
|
+
|
|
458
|
+
def run_without_request(self) -> None:
|
|
459
|
+
"""Outside a merge or pull request there is one commit to check: HEAD."""
|
|
460
|
+
print(
|
|
461
|
+
"Not a merge or pull request pipeline: checking the last commit only.",
|
|
462
|
+
flush=True,
|
|
463
|
+
)
|
|
464
|
+
if self.settings["branch"]:
|
|
465
|
+
self.check("Branch", ["--branch"])
|
|
466
|
+
flags = [f"--{name}" for name in COMMIT_CHECKS if self.settings[name]]
|
|
467
|
+
if flags:
|
|
468
|
+
self.check(
|
|
469
|
+
f"Commit {resolve_commit('HEAD')[:8]} {subject_of('HEAD')}",
|
|
470
|
+
# --rev: without it the author checks read the identity the
|
|
471
|
+
# runner would commit with, not the author of this commit.
|
|
472
|
+
[*flags, "--rev", "HEAD"],
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
477
|
+
"""The ``commit-check-ci`` command. Exits 0, 1 (a check failed) or 2."""
|
|
478
|
+
try:
|
|
479
|
+
settings = read_settings(argv)
|
|
480
|
+
except Stop as error:
|
|
481
|
+
print(f"Error: {error}", file=sys.stderr)
|
|
482
|
+
return 2
|
|
483
|
+
return Job(settings, os.environ).run()
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
if __name__ == "__main__": # pragma: no cover
|
|
487
|
+
sys.exit(main())
|
commit_check/engine.py
CHANGED
|
@@ -18,6 +18,7 @@ from commit_check import (
|
|
|
18
18
|
DEFAULT_AI_DISCLOSURE_TRAILERS,
|
|
19
19
|
DEPENDENCY_UPDATE_BOTS,
|
|
20
20
|
GIT_MERGE_SUBJECT_PATTERN,
|
|
21
|
+
GIT_REVERT_SUBJECT_PATTERN,
|
|
21
22
|
ai_policy,
|
|
22
23
|
)
|
|
23
24
|
from commit_check.ai_signatures import (
|
|
@@ -56,11 +57,13 @@ from commit_check.util import (
|
|
|
56
57
|
git_rev_parse_verify,
|
|
57
58
|
has_commits,
|
|
58
59
|
print_error_header,
|
|
60
|
+
print_quoted_message,
|
|
59
61
|
read_commit_message_file,
|
|
60
62
|
rejection_headline,
|
|
61
63
|
)
|
|
62
64
|
|
|
63
65
|
_GIT_MERGE_SUBJECT = re.compile(GIT_MERGE_SUBJECT_PATTERN)
|
|
66
|
+
_GIT_REVERT_SUBJECT = re.compile(GIT_REVERT_SUBJECT_PATTERN)
|
|
64
67
|
|
|
65
68
|
|
|
66
69
|
def is_merge_subject(subject: str) -> bool:
|
|
@@ -73,6 +76,16 @@ def is_merge_subject(subject: str) -> bool:
|
|
|
73
76
|
return _GIT_MERGE_SUBJECT.match(subject) is not None
|
|
74
77
|
|
|
75
78
|
|
|
79
|
+
def is_revert_subject(subject: str) -> bool:
|
|
80
|
+
"""Whether *subject* is one ``git revert`` wrote, not the author.
|
|
81
|
+
|
|
82
|
+
'Revert "<subject>"', or 'Reapply "<subject>"' for the revert of a
|
|
83
|
+
revert. The quote is part of the match: "Revert the parser change" is
|
|
84
|
+
the author's, and is judged like any other subject.
|
|
85
|
+
"""
|
|
86
|
+
return _GIT_REVERT_SUBJECT.match(subject) is not None
|
|
87
|
+
|
|
88
|
+
|
|
76
89
|
# A work-in-progress marker at the start of the subject (CC010). "^" without
|
|
77
90
|
# re.MULTILINE and "[ \t]*" rather than "\s*" keep the match on the first
|
|
78
91
|
# line, so a body that merely mentions WIP is not a WIP commit.
|
|
@@ -453,6 +466,8 @@ class BaseValidator(ABC):
|
|
|
453
466
|
rule_dict["error"] = error
|
|
454
467
|
if fix or suggest:
|
|
455
468
|
rule_dict["suggest"] = suggest or f'Use "{fix}"'
|
|
469
|
+
if fix:
|
|
470
|
+
rule_dict["fix"] = fix
|
|
456
471
|
|
|
457
472
|
# Always store structured failure details for programmatic consumers.
|
|
458
473
|
self._last_failure = {
|
|
@@ -700,8 +715,10 @@ class SubjectLengthValidator(SubjectValidator):
|
|
|
700
715
|
return True
|
|
701
716
|
|
|
702
717
|
def _validate_subject(self, subject: str) -> ValidationResult:
|
|
703
|
-
# A merge subject's length is git's doing, not the
|
|
704
|
-
|
|
718
|
+
# A merge or revert subject's length is git's doing, not the
|
|
719
|
+
# author's: 'Revert "..."' adds nine characters to a subject that
|
|
720
|
+
# already fit.
|
|
721
|
+
if is_merge_subject(subject) or is_revert_subject(subject):
|
|
705
722
|
return ValidationResult.SKIP
|
|
706
723
|
|
|
707
724
|
suffix = _SQUASH_PR_NUMBER.search(subject)
|
|
@@ -1527,7 +1544,9 @@ class CommitTypeValidator(BaseValidator):
|
|
|
1527
1544
|
|
|
1528
1545
|
def _is_revert_commit_allowed(self, message: str) -> bool:
|
|
1529
1546
|
"""Check if revert commits are allowed."""
|
|
1530
|
-
|
|
1547
|
+
# 'Reapply "..."' is git's subject for reverting a revert, so it is
|
|
1548
|
+
# one too.
|
|
1549
|
+
is_revert = message.lower().startswith("revert ") or is_revert_subject(message)
|
|
1531
1550
|
return not is_revert or self.rule.value
|
|
1532
1551
|
|
|
1533
1552
|
def _is_empty_commit_allowed(self, message: str) -> bool:
|
|
@@ -1977,6 +1996,101 @@ class AiDeclarationValidator(BaseValidator):
|
|
|
1977
1996
|
return ValidationResult.FAIL
|
|
1978
1997
|
|
|
1979
1998
|
|
|
1999
|
+
#: Checks whose value is the commit message, or its subject line.
|
|
2000
|
+
_MESSAGE_CHECKS = frozenset(
|
|
2001
|
+
{
|
|
2002
|
+
"message",
|
|
2003
|
+
"subject_capitalized",
|
|
2004
|
+
"subject_imperative",
|
|
2005
|
+
"subject_max_length",
|
|
2006
|
+
"subject_min_length",
|
|
2007
|
+
"allow_merge_commits",
|
|
2008
|
+
"allow_revert_commits",
|
|
2009
|
+
"allow_empty_commits",
|
|
2010
|
+
"allow_fixup_commits",
|
|
2011
|
+
"allow_wip_commits",
|
|
2012
|
+
"require_body",
|
|
2013
|
+
"require_signed_off_by",
|
|
2014
|
+
}
|
|
2015
|
+
)
|
|
2016
|
+
|
|
2017
|
+
#: Of those, the ones that find fault with the subject line itself.
|
|
2018
|
+
_SUBJECT_CHECKS = _MESSAGE_CHECKS - {"require_body", "require_signed_off_by"}
|
|
2019
|
+
|
|
2020
|
+
|
|
2021
|
+
def _quotes(message: str, check: str, value: str) -> bool:
|
|
2022
|
+
"""Whether the quoted *message* already shows this failure's *value*."""
|
|
2023
|
+
if check not in _MESSAGE_CHECKS:
|
|
2024
|
+
return False
|
|
2025
|
+
return value in (message, message.split("\n", 1)[0])
|
|
2026
|
+
|
|
2027
|
+
|
|
2028
|
+
def _shared_message(blocks: list[tuple[dict, str]]) -> str | None:
|
|
2029
|
+
"""The commit message to quote once above the failure blocks, if any.
|
|
2030
|
+
|
|
2031
|
+
When two or more message rules fail, each block used to repeat the
|
|
2032
|
+
message after its rule name. Quoting it once reads like a diff: the
|
|
2033
|
+
message, then what is wrong with it. Rules that report something else
|
|
2034
|
+
(an AI tool's name, a branch) keep their own value on their own line.
|
|
2035
|
+
"""
|
|
2036
|
+
candidates = [
|
|
2037
|
+
value
|
|
2038
|
+
for rule_dict, value in blocks
|
|
2039
|
+
if rule_dict["check"] in _MESSAGE_CHECKS and value.strip()
|
|
2040
|
+
]
|
|
2041
|
+
# The longest is the whole message; a subject-only value is its first line.
|
|
2042
|
+
for message in sorted(set(candidates), key=len, reverse=True):
|
|
2043
|
+
covered = sum(1 for value in candidates if _quotes(message, "message", value))
|
|
2044
|
+
if covered >= 2:
|
|
2045
|
+
return message
|
|
2046
|
+
return None
|
|
2047
|
+
|
|
2048
|
+
|
|
2049
|
+
def _missing_lines(message: str, blocks: list[tuple[dict, str]]) -> list[str]:
|
|
2050
|
+
"""The trailer lines a sign-off rule's fix adds to *message*."""
|
|
2051
|
+
present = set(message.split("\n"))
|
|
2052
|
+
missing: list[str] = []
|
|
2053
|
+
for rule_dict, _ in blocks:
|
|
2054
|
+
if rule_dict["check"] != "require_signed_off_by":
|
|
2055
|
+
continue
|
|
2056
|
+
for line in (rule_dict.get("fix") or "").split("\n"):
|
|
2057
|
+
if line.strip() and line not in present and line not in missing:
|
|
2058
|
+
missing.append(line)
|
|
2059
|
+
return missing
|
|
2060
|
+
|
|
2061
|
+
|
|
2062
|
+
def _marked_lines(message: str, blocks: list[tuple[dict, str]]) -> set[int]:
|
|
2063
|
+
"""The line numbers of *message* that a failing rule points at.
|
|
2064
|
+
|
|
2065
|
+
The subject when a subject rule failed on it, and the lines an AI rule's
|
|
2066
|
+
fix would remove: those are what to change, not a guess at them.
|
|
2067
|
+
"""
|
|
2068
|
+
lines = message.split("\n")
|
|
2069
|
+
marked: set[int] = set()
|
|
2070
|
+
for rule_dict, value in blocks:
|
|
2071
|
+
check = rule_dict["check"]
|
|
2072
|
+
if check in _SUBJECT_CHECKS and _quotes(message, check, value):
|
|
2073
|
+
marked.add(0)
|
|
2074
|
+
fix = rule_dict.get("fix") or ""
|
|
2075
|
+
if check.startswith("ai_") and fix:
|
|
2076
|
+
marked |= _removed_lines(lines, fix)
|
|
2077
|
+
return marked
|
|
2078
|
+
|
|
2079
|
+
|
|
2080
|
+
def _removed_lines(lines: list[str], fix: str) -> set[int]:
|
|
2081
|
+
"""The numbers of the non-blank *lines* that the *fix* message drops."""
|
|
2082
|
+
kept = fix.split("\n")
|
|
2083
|
+
removed: set[int] = set()
|
|
2084
|
+
for number, line in enumerate(lines):
|
|
2085
|
+
if not line.strip():
|
|
2086
|
+
continue
|
|
2087
|
+
if line in kept:
|
|
2088
|
+
kept.remove(line)
|
|
2089
|
+
else:
|
|
2090
|
+
removed.add(number)
|
|
2091
|
+
return removed
|
|
2092
|
+
|
|
2093
|
+
|
|
1980
2094
|
class ValidationEngine:
|
|
1981
2095
|
"""Main validation engine that orchestrates all validations."""
|
|
1982
2096
|
|
|
@@ -2077,13 +2191,33 @@ class ValidationEngine:
|
|
|
2077
2191
|
and not context.compact
|
|
2078
2192
|
and not print_error_header.has_been_called
|
|
2079
2193
|
):
|
|
2080
|
-
|
|
2194
|
+
# A pull request title or description is no commit, so the
|
|
2195
|
+
# header must not send the reader to look for one.
|
|
2196
|
+
headline = (
|
|
2197
|
+
"Rejected by Commit Check"
|
|
2198
|
+
if context.not_a_commit
|
|
2199
|
+
else rejection_headline(failed)
|
|
2200
|
+
)
|
|
2201
|
+
print_error_header(headline, failed=len(failed))
|
|
2202
|
+
message = None if context.compact else _shared_message(blocks)
|
|
2203
|
+
if message is not None and "\n" not in message:
|
|
2204
|
+
# Only subject rules reported it: quote the whole message, so a
|
|
2205
|
+
# trailer an AI rule points at is on screen too.
|
|
2206
|
+
message = BaseValidator._get_commit_message(context) or message
|
|
2207
|
+
if message is not None:
|
|
2208
|
+
print_quoted_message(
|
|
2209
|
+
message,
|
|
2210
|
+
_marked_lines(message, blocks),
|
|
2211
|
+
_missing_lines(message, blocks),
|
|
2212
|
+
)
|
|
2081
2213
|
for rule_dict, value in blocks:
|
|
2082
2214
|
_print_failure(
|
|
2083
2215
|
rule_dict,
|
|
2084
2216
|
value,
|
|
2085
2217
|
no_banner=context.no_banner,
|
|
2086
2218
|
compact=context.compact,
|
|
2219
|
+
value_shown=message is not None
|
|
2220
|
+
and _quotes(message, rule_dict["check"], value),
|
|
2087
2221
|
)
|
|
2088
2222
|
|
|
2089
2223
|
@staticmethod
|
commit_check/main.py
CHANGED
|
@@ -35,7 +35,7 @@ from commit_check.util import (
|
|
|
35
35
|
split_message_comments,
|
|
36
36
|
)
|
|
37
37
|
|
|
38
|
-
from . import AI_ATTRIBUTION_POLICIES
|
|
38
|
+
from . import AI_ATTRIBUTION_POLICIES, BOLD, DIM, RESET_COLOR
|
|
39
39
|
|
|
40
40
|
# Exit codes. ``1`` is a verdict on the commit; ``2`` means the run could not
|
|
41
41
|
# be set up at all -- the same code argparse uses for a bad command line -- so
|
|
@@ -163,10 +163,46 @@ class _VersionAction(argparse.Action):
|
|
|
163
163
|
parser.exit()
|
|
164
164
|
|
|
165
165
|
|
|
166
|
+
def _print_intro(config: str | None) -> None:
|
|
167
|
+
"""What a bare ``commit-check`` prints: one screen, not the full help.
|
|
168
|
+
|
|
169
|
+
Someone who types the name to see what it is gets the version, the few
|
|
170
|
+
commands that cover most uses, which config the run would read and where
|
|
171
|
+
the docs are. ``--help`` still lists every option.
|
|
172
|
+
"""
|
|
173
|
+
from . import __version__
|
|
174
|
+
|
|
175
|
+
examples = (
|
|
176
|
+
("commit-check -m -b", "check the last commit message and the branch"),
|
|
177
|
+
("commit-check -m < msg.txt", "check a message before you commit it"),
|
|
178
|
+
("commit-check --help", "list every option"),
|
|
179
|
+
)
|
|
180
|
+
width = max(len(cmd) for cmd, _ in examples)
|
|
181
|
+
title = f"{BOLD}Commit Check{RESET_COLOR} {__version__}"
|
|
182
|
+
lines = [f"{title}{DIM} · commit policy as code{RESET_COLOR}", ""]
|
|
183
|
+
lines += [
|
|
184
|
+
f" {cmd.ljust(width)} {DIM}{what}{RESET_COLOR}" for cmd, what in examples
|
|
185
|
+
]
|
|
186
|
+
lines.append("")
|
|
187
|
+
found = find_config_path(config or "")
|
|
188
|
+
if found:
|
|
189
|
+
lines.append(f" {DIM}Config{RESET_COLOR} {os.path.relpath(found)}")
|
|
190
|
+
else:
|
|
191
|
+
lines.append(
|
|
192
|
+
f" {DIM}Config{RESET_COLOR} none found, using the defaults: Conventional Commits,"
|
|
193
|
+
)
|
|
194
|
+
lines.append(" Conventional Branch, subjects up to 80 characters")
|
|
195
|
+
lines.append(
|
|
196
|
+
f" {DIM}Docs{RESET_COLOR} https://commit-check.com/getting-started/"
|
|
197
|
+
)
|
|
198
|
+
print("\n".join(lines))
|
|
199
|
+
|
|
200
|
+
|
|
166
201
|
def _get_parser() -> argparse.ArgumentParser:
|
|
167
202
|
"""Get parser to interpret CLI args."""
|
|
168
203
|
parser = argparse.ArgumentParser(
|
|
169
204
|
prog="commit-check",
|
|
205
|
+
usage="%(prog)s [options] [commit_msg_file]",
|
|
170
206
|
description="Check commit message, branch name, author name, email, and more.",
|
|
171
207
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
172
208
|
epilog=(
|
|
@@ -875,7 +911,7 @@ def main() -> int:
|
|
|
875
911
|
# Determine which checks to run
|
|
876
912
|
requested_checks = _get_requested_checks(args)
|
|
877
913
|
if not requested_checks:
|
|
878
|
-
|
|
914
|
+
_print_intro(args.config)
|
|
879
915
|
return 0
|
|
880
916
|
|
|
881
917
|
# Filter rules to only include requested checks
|
commit_check/rule_builder.py
CHANGED
|
@@ -19,6 +19,7 @@ from commit_check import (
|
|
|
19
19
|
DEFAULT_PUSH_RULES,
|
|
20
20
|
DEFAULT_TAG_REGEX,
|
|
21
21
|
GIT_MERGE_SUBJECT_PATTERN,
|
|
22
|
+
GIT_REVERT_SUBJECT_PATTERN,
|
|
22
23
|
)
|
|
23
24
|
from commit_check.config import ConfigError
|
|
24
25
|
from commit_check.config_merger import get_default_config
|
|
@@ -915,9 +916,7 @@ class RuleBuilder:
|
|
|
915
916
|
# prefix exactly as below, trailing space or quote included, so author
|
|
916
917
|
# prose such as "Merged ...", "Merge the parser tables" or
|
|
917
918
|
# "fixup!! ..." is still held to the format.
|
|
918
|
-
git_prefixes = (
|
|
919
|
-
rf'^(?:{GIT_MERGE_SUBJECT_PATTERN}|Revert "|fixup! |squash! |amend! )'
|
|
920
|
-
)
|
|
919
|
+
git_prefixes = rf"^(?:{GIT_MERGE_SUBJECT_PATTERN}|{GIT_REVERT_SUBJECT_PATTERN}|fixup! |squash! |amend! )"
|
|
921
920
|
return (
|
|
922
921
|
rf"^({types_pattern})(\([\w\-\.]+\))?(!)?: [^\n]+([\s\S]*)|{git_prefixes}"
|
|
923
922
|
)
|
commit_check/util.py
CHANGED
|
@@ -51,9 +51,14 @@ def _print_failure(
|
|
|
51
51
|
actual: str,
|
|
52
52
|
no_banner: bool = False,
|
|
53
53
|
compact: bool = False,
|
|
54
|
+
value_shown: bool = False,
|
|
54
55
|
) -> None:
|
|
55
56
|
"""Print a standardized failure message.
|
|
56
57
|
|
|
58
|
+
``value_shown`` says the value is already on screen, quoted above the
|
|
59
|
+
blocks by :func:`print_quoted_message`, so the block's first line names
|
|
60
|
+
the rule only instead of repeating the value.
|
|
61
|
+
|
|
57
62
|
A rule whose ``severity`` is ``"warn"`` prints the same block with the
|
|
58
63
|
word ``warning`` in place of ``failed``, no rejection header, and one
|
|
59
64
|
closing line saying the run is not failed by it.
|
|
@@ -81,6 +86,7 @@ def _print_failure(
|
|
|
81
86
|
warn=warn,
|
|
82
87
|
spec_name=check.get("spec_name", "") or "",
|
|
83
88
|
spec_url=check.get("spec_url", "") or "",
|
|
89
|
+
show_value=not value_shown,
|
|
84
90
|
)
|
|
85
91
|
if check.get("suggest"):
|
|
86
92
|
print_suggestion(printable(check["suggest"]))
|
|
@@ -927,6 +933,7 @@ def print_error_message(
|
|
|
927
933
|
warn: bool = False,
|
|
928
934
|
spec_name: str = "",
|
|
929
935
|
spec_url: str = "",
|
|
936
|
+
show_value: bool = True,
|
|
930
937
|
) -> None:
|
|
931
938
|
"""Print error message.
|
|
932
939
|
|
|
@@ -942,6 +949,8 @@ def print_error_message(
|
|
|
942
949
|
from the name when the terminal supports it
|
|
943
950
|
:param spec_url: address of that specification; ``error`` carries it as a
|
|
944
951
|
trailing ``. See {spec_url}``, dropped once the name is a link
|
|
952
|
+
:param show_value: print ``reason`` after the verdict; off when the value
|
|
953
|
+
is already quoted above, so the line names the rule only
|
|
945
954
|
|
|
946
955
|
:returns: Give error messages to user
|
|
947
956
|
"""
|
|
@@ -954,17 +963,20 @@ def print_error_message(
|
|
|
954
963
|
marker, verdict, colour = _symbol("▲", "!"), "warning", YELLOW
|
|
955
964
|
else:
|
|
956
965
|
marker, verdict, colour = _symbol("✖", "x"), "failed", RED
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
first, _, rest = reason.partition("\n")
|
|
960
|
-
more = sum(1 for line in rest.splitlines() if line.strip())
|
|
961
|
-
tail = ""
|
|
962
|
-
if more:
|
|
963
|
-
tail = f" {DIM}(+{more} more line{'s' if more > 1 else ''}){RESET_COLOR}"
|
|
964
|
-
print(
|
|
965
|
-
f"{colour}{marker}{RESET_COLOR} {prefix}{YELLOW}{name}{RESET_COLOR} "
|
|
966
|
-
f"{verdict}: {colour}{first}{RESET_COLOR}{tail}"
|
|
966
|
+
head = (
|
|
967
|
+
f"{colour}{marker}{RESET_COLOR} {prefix}{YELLOW}{name}{RESET_COLOR} {verdict}"
|
|
967
968
|
)
|
|
969
|
+
if show_value:
|
|
970
|
+
# A whole commit message is the value of several rules; its subject
|
|
971
|
+
# names the commit, and the rest would push the explanation off the
|
|
972
|
+
# screen.
|
|
973
|
+
first, _, rest = reason.partition("\n")
|
|
974
|
+
more = sum(1 for line in rest.splitlines() if line.strip())
|
|
975
|
+
tail = ""
|
|
976
|
+
if more:
|
|
977
|
+
tail = f" {DIM}(+{more} more line{'s' if more > 1 else ''}){RESET_COLOR}"
|
|
978
|
+
head += f": {colour}{first}{RESET_COLOR}{tail}"
|
|
979
|
+
print(head)
|
|
968
980
|
if error:
|
|
969
981
|
# Same trade-off as the Docs: line above — once the spec name is a
|
|
970
982
|
# link, spelling out its address only adds noise; without hyperlink
|
|
@@ -975,6 +987,47 @@ def print_error_message(
|
|
|
975
987
|
print(f"{_DETAIL_INDENT}{error}")
|
|
976
988
|
|
|
977
989
|
|
|
990
|
+
#: Lines of a quoted message shown before the rest is folded into one
|
|
991
|
+
#: ``…`` line. A line a rule points at is shown wherever it is.
|
|
992
|
+
_QUOTE_MAX_LINES = 12
|
|
993
|
+
|
|
994
|
+
|
|
995
|
+
def print_quoted_message(
|
|
996
|
+
message: str, marked: Iterable[int] = (), missing: Iterable[str] = ()
|
|
997
|
+
) -> None:
|
|
998
|
+
"""Print a commit message once, in a gutter, above the rules it failed.
|
|
999
|
+
|
|
1000
|
+
Several rules read the same message. Quoting it here lets each failure
|
|
1001
|
+
block name its rule without repeating the message, and the lines a rule
|
|
1002
|
+
points at (the ``marked`` line numbers, from 0) are shown in red, the
|
|
1003
|
+
way a diff shows what to change. Lines a rule requires and the message
|
|
1004
|
+
lacks (a ``Signed-off-by`` trailer) follow in green, marked missing.
|
|
1005
|
+
"""
|
|
1006
|
+
lines = printable(message).split("\n")
|
|
1007
|
+
while lines and not lines[-1].strip():
|
|
1008
|
+
lines.pop()
|
|
1009
|
+
marked = set(marked)
|
|
1010
|
+
shown = set(range(min(len(lines), _QUOTE_MAX_LINES))) | marked
|
|
1011
|
+
bar = f"{DIM}{_symbol('│', '|')}{RESET_COLOR}"
|
|
1012
|
+
folded = 0
|
|
1013
|
+
for number, line in enumerate(lines):
|
|
1014
|
+
if number not in shown:
|
|
1015
|
+
folded += 1
|
|
1016
|
+
continue
|
|
1017
|
+
if folded:
|
|
1018
|
+
print(f"{_DETAIL_INDENT}{bar} {DIM}… {folded} more{RESET_COLOR}")
|
|
1019
|
+
folded = 0
|
|
1020
|
+
if number in marked:
|
|
1021
|
+
line = f"{RED}{line}{RESET_COLOR}"
|
|
1022
|
+
print(f"{_DETAIL_INDENT}{bar} {line}".rstrip())
|
|
1023
|
+
if folded:
|
|
1024
|
+
print(f"{_DETAIL_INDENT}{bar} {DIM}… {folded} more{RESET_COLOR}")
|
|
1025
|
+
for line in missing:
|
|
1026
|
+
note = f"{DIM}{_symbol('←', '<-')} missing{RESET_COLOR}"
|
|
1027
|
+
print(f"{_DETAIL_INDENT}{bar} {GREEN}{printable(line)}{RESET_COLOR} {note}")
|
|
1028
|
+
print()
|
|
1029
|
+
|
|
1030
|
+
|
|
978
1031
|
def print_suggestion(suggest: str) -> None:
|
|
979
1032
|
"""Print suggestion to user
|
|
980
1033
|
:param suggest: what message to print out
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: commit-check
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.23.1
|
|
4
4
|
Summary: Commit policy as code for teams and AI agents: check commit messages, branch names, authors, tags, files and AI attribution.
|
|
5
5
|
Author-email: Xianpeng Shen <xianpeng.shen@gmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
7
|
-
Project-URL:
|
|
8
|
-
Project-URL:
|
|
9
|
-
Project-URL:
|
|
7
|
+
Project-URL: Documentation, https://commit-check.com/
|
|
8
|
+
Project-URL: Changelog, https://commit-check.com/changelog/
|
|
9
|
+
Project-URL: Source, https://github.com/commit-check/commit-check
|
|
10
|
+
Project-URL: Issues, https://github.com/commit-check/commit-check/issues
|
|
10
11
|
Keywords: commit conventions,conventional commits,conventional branch,branch naming,commit-check,message,lint message,devops,policy as code,ai agents
|
|
11
12
|
Classifier: Development Status :: 5 - Production/Stable
|
|
12
13
|
Classifier: Intended Audience :: Developers
|
|
@@ -87,7 +88,7 @@ Stop bad commits before they exist. In `.pre-commit-config.yaml`:
|
|
|
87
88
|
```yaml
|
|
88
89
|
repos:
|
|
89
90
|
- repo: https://github.com/commit-check/commit-check
|
|
90
|
-
rev: v2.
|
|
91
|
+
rev: v2.23.1
|
|
91
92
|
hooks:
|
|
92
93
|
- id: check-message
|
|
93
94
|
- id: check-branch
|
|
@@ -159,11 +160,11 @@ Priority: CLI > env > TOML > default. Booleans accept `true/false`, `yes/no`,
|
|
|
159
160
|
| `commit.message_pattern` | `""` | — | `CCHK_MESSAGE_PATTERN` | Custom regex the whole message must match; when set it replaces the Conventional Commits check (still reported as CC001) |
|
|
160
161
|
| `commit.subject_capitalized` | `false` | `--subject-capitalized` | `CCHK_SUBJECT_CAPITALIZED` | Require the subject to start with a capital letter (CC002) |
|
|
161
162
|
| `commit.subject_imperative` | `false` | `--subject-imperative` | `CCHK_SUBJECT_IMPERATIVE` | Require the subject to use the imperative mood (CC003) |
|
|
162
|
-
| `commit.subject_max_length` | `80` | `--subject-max-length` | `CCHK_SUBJECT_MAX_LENGTH` | Maximum subject length (CC004), not counting the ` (#123)` a GitHub squash merge adds; `0` turns it off. Commits by `dependabot[bot]` and `renovate[bot]` skip both length rules |
|
|
163
|
+
| `commit.subject_max_length` | `80` | `--subject-max-length` | `CCHK_SUBJECT_MAX_LENGTH` | Maximum subject length (CC004), not counting the ` (#123)` a GitHub squash merge adds; the `Revert "..."` and `Reapply "..."` subjects `git revert` writes are not measured; `0` turns it off. Commits by `dependabot[bot]` and `renovate[bot]` skip both length rules |
|
|
163
164
|
| `commit.subject_min_length` | `5` | `--subject-min-length` | `CCHK_SUBJECT_MIN_LENGTH` | Minimum subject length (CC005); `0` turns it off |
|
|
164
|
-
| `commit.allow_commit_types` | `feat, fix, docs, style, refactor, test, chore, perf, build, ci` | `--allow-commit-types` | `CCHK_ALLOW_COMMIT_TYPES` | Allowed `<type>` values in the subject |
|
|
165
|
+
| `commit.allow_commit_types` | `feat, fix, docs, style, refactor, test, chore, perf, build, ci, revert` | `--allow-commit-types` | `CCHK_ALLOW_COMMIT_TYPES` | Allowed `<type>` values in the subject |
|
|
165
166
|
| `commit.allow_merge_commits` | `true` | `--allow-merge-commits` | `CCHK_ALLOW_MERGE_COMMITS` | Allow merge commits (CC006) |
|
|
166
|
-
| `commit.allow_revert_commits` | `true` | `--allow-revert-commits` | `CCHK_ALLOW_REVERT_COMMITS` | Allow
|
|
167
|
+
| `commit.allow_revert_commits` | `true` | `--allow-revert-commits` | `CCHK_ALLOW_REVERT_COMMITS` | Allow the `Revert "..."` and `Reapply "..."` commits `git revert` writes (CC007) |
|
|
167
168
|
| `commit.allow_empty_commits` | `true` | `--allow-empty-commits` | `CCHK_ALLOW_EMPTY_COMMITS` | Allow empty commit messages (CC008) |
|
|
168
169
|
| `commit.allow_fixup_commits` | `true` | `--allow-fixup-commits` | `CCHK_ALLOW_FIXUP_COMMITS` | Allow `fixup!`, `squash!` and `amend!` commits (CC009) |
|
|
169
170
|
| `commit.allow_wip_commits` | `true` | `--allow-wip-commits` | `CCHK_ALLOW_WIP_COMMITS` | Allow WIP commits (CC010) |
|
|
@@ -1,22 +1,23 @@
|
|
|
1
|
-
commit_check/__init__.py,sha256=
|
|
1
|
+
commit_check/__init__.py,sha256=lKMivNHT2PY_0ngRRMvTdQVdrYeE_5eS3MtNY3CaLQw,7092
|
|
2
2
|
commit_check/_https.py,sha256=Eyi-zKEfDcwXJ_3b82UOo9_RxFQkD8uF4zU7MGUVDj0,1215
|
|
3
3
|
commit_check/ai_policy.py,sha256=gYC3ROLgGL1TDyhPkFXkV-NiYbvMt80Qt0MFrJcbJY4,8131
|
|
4
4
|
commit_check/ai_signatures.py,sha256=y_iqVVmMXhcutcKoNvdp5dUUEwgsDwj1HGwYGyN5oCA,11708
|
|
5
5
|
commit_check/ai_signatures_data.py,sha256=fZ9TpKNGqk0sYuko5PoHUFEEL_uRu9HK9RYGSvZTp3w,23170
|
|
6
6
|
commit_check/api.py,sha256=07bvBtV8PrhZIOwCDHiHfu_7CXsX_4U2_K2xMAucd6c,12905
|
|
7
|
+
commit_check/ci.py,sha256=i9cIlMbIn_nHA4cln2YUgCReYm22efkPqKyjh-gq3kQ,19022
|
|
7
8
|
commit_check/config.py,sha256=R8FSnHRwC1NOwNdMBlcLnhfxmY_WxLaHBeBi2qanTdo,13331
|
|
8
9
|
commit_check/config_merger.py,sha256=apuL6bAvNWgeP2VoEg9eht1k1TUER70G_waXitI8UMk,13772
|
|
9
|
-
commit_check/engine.py,sha256=
|
|
10
|
+
commit_check/engine.py,sha256=_EFBVROqOFCN2tozVbrRkmwEMmrpvPB1qTs8CQc6LD8,94600
|
|
10
11
|
commit_check/fixes.py,sha256=BpbdoHsKDyw2WfsqymwYpnrW73aHdCDGr8tMF6Ho2RU,7305
|
|
11
12
|
commit_check/imperatives.py,sha256=dEd_ssu4G0j6Cann6jqPdB97lw5Adua43K0_Odg_FyA,9518
|
|
12
|
-
commit_check/main.py,sha256=
|
|
13
|
+
commit_check/main.py,sha256=2ejov6i3WPR3VgXw257YJkyp4SiKB25gB_EhIbreuCE,34570
|
|
13
14
|
commit_check/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
-
commit_check/rule_builder.py,sha256=
|
|
15
|
+
commit_check/rule_builder.py,sha256=z5hajjCn1wlief12-7Kvn7HjkHmSjcWucR7SeXVwE4Q,38145
|
|
15
16
|
commit_check/rules_catalog.py,sha256=lmx3-YljVFhh62pWh6trJUehSmO7lx2qReJE6PO_2tc,13897
|
|
16
|
-
commit_check/util.py,sha256=
|
|
17
|
-
commit_check-2.
|
|
18
|
-
commit_check-2.
|
|
19
|
-
commit_check-2.
|
|
20
|
-
commit_check-2.
|
|
21
|
-
commit_check-2.
|
|
22
|
-
commit_check-2.
|
|
17
|
+
commit_check/util.py,sha256=VE0qNx2HpyDB1CPFF_p7I2EOJzAPs_yKDCJ1zFyCdok,38710
|
|
18
|
+
commit_check-2.23.1.dist-info/licenses/LICENSE,sha256=9mdTva71kQhrpWh_nZulxrdCnUrl5c6xJYh5hdo4p_s,1070
|
|
19
|
+
commit_check-2.23.1.dist-info/METADATA,sha256=OT4g_1hyL7EvkApoGhyKwWdK0eVDblvnqzId-o7LQvw,19374
|
|
20
|
+
commit_check-2.23.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
21
|
+
commit_check-2.23.1.dist-info/entry_points.txt,sha256=-4RWjQDhmngfCnTx46iCz3RrI8WZoiMZo0nhsg6hmUw,125
|
|
22
|
+
commit_check-2.23.1.dist-info/top_level.txt,sha256=Wf46u-ooHBMJNHbhfrBNQw3wC5_m8wt-o_Lfbc4QpRg,13
|
|
23
|
+
commit_check-2.23.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|