commit-check 2.22.0__py3-none-any.whl → 2.23.0__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/ci.py +487 -0
- commit_check/engine.py +8 -1
- {commit_check-2.22.0.dist-info → commit_check-2.23.0.dist-info}/METADATA +2 -2
- {commit_check-2.22.0.dist-info → commit_check-2.23.0.dist-info}/RECORD +8 -7
- {commit_check-2.22.0.dist-info → commit_check-2.23.0.dist-info}/entry_points.txt +1 -0
- {commit_check-2.22.0.dist-info → commit_check-2.23.0.dist-info}/WHEEL +0 -0
- {commit_check-2.22.0.dist-info → commit_check-2.23.0.dist-info}/licenses/LICENSE +0 -0
- {commit_check-2.22.0.dist-info → commit_check-2.23.0.dist-info}/top_level.txt +0 -0
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
|
@@ -2077,7 +2077,14 @@ class ValidationEngine:
|
|
|
2077
2077
|
and not context.compact
|
|
2078
2078
|
and not print_error_header.has_been_called
|
|
2079
2079
|
):
|
|
2080
|
-
|
|
2080
|
+
# A pull request title or description is no commit, so the
|
|
2081
|
+
# header must not send the reader to look for one.
|
|
2082
|
+
headline = (
|
|
2083
|
+
"Rejected by Commit Check"
|
|
2084
|
+
if context.not_a_commit
|
|
2085
|
+
else rejection_headline(failed)
|
|
2086
|
+
)
|
|
2087
|
+
print_error_header(headline, failed=len(failed))
|
|
2081
2088
|
for rule_dict, value in blocks:
|
|
2082
2089
|
_print_failure(
|
|
2083
2090
|
rule_dict,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: commit-check
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.23.0
|
|
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
|
|
@@ -87,7 +87,7 @@ Stop bad commits before they exist. In `.pre-commit-config.yaml`:
|
|
|
87
87
|
```yaml
|
|
88
88
|
repos:
|
|
89
89
|
- repo: https://github.com/commit-check/commit-check
|
|
90
|
-
rev: v2.
|
|
90
|
+
rev: v2.23.0
|
|
91
91
|
hooks:
|
|
92
92
|
- id: check-message
|
|
93
93
|
- id: check-branch
|
|
@@ -4,9 +4,10 @@ commit_check/ai_policy.py,sha256=gYC3ROLgGL1TDyhPkFXkV-NiYbvMt80Qt0MFrJcbJY4,813
|
|
|
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=mDCqn-X5knUEvGpkPsiY8DUlnGgBzoeJWRYPfQs7lrs,89771
|
|
10
11
|
commit_check/fixes.py,sha256=BpbdoHsKDyw2WfsqymwYpnrW73aHdCDGr8tMF6Ho2RU,7305
|
|
11
12
|
commit_check/imperatives.py,sha256=dEd_ssu4G0j6Cann6jqPdB97lw5Adua43K0_Odg_FyA,9518
|
|
12
13
|
commit_check/main.py,sha256=x3BuJUHE2am1c5FZgK4cuoXz55jChJW3s0vaILb7YEc,33080
|
|
@@ -14,9 +15,9 @@ commit_check/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
|
14
15
|
commit_check/rule_builder.py,sha256=GkAWmaHLHXzBp-UlynVUg4UdtKngUD151cjW5fk6wog,38117
|
|
15
16
|
commit_check/rules_catalog.py,sha256=lmx3-YljVFhh62pWh6trJUehSmO7lx2qReJE6PO_2tc,13897
|
|
16
17
|
commit_check/util.py,sha256=o0DkiDBARiXgNpdGWwGU7eez5P9YO5hrG43pk2DJVCY,36536
|
|
17
|
-
commit_check-2.
|
|
18
|
-
commit_check-2.
|
|
19
|
-
commit_check-2.
|
|
20
|
-
commit_check-2.
|
|
21
|
-
commit_check-2.
|
|
22
|
-
commit_check-2.
|
|
18
|
+
commit_check-2.23.0.dist-info/licenses/LICENSE,sha256=9mdTva71kQhrpWh_nZulxrdCnUrl5c6xJYh5hdo4p_s,1070
|
|
19
|
+
commit_check-2.23.0.dist-info/METADATA,sha256=Jz8kVHQ6Y-xLLu_-oIrvfXCvZOPkhqxnWYgFX3xLykE,19169
|
|
20
|
+
commit_check-2.23.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
21
|
+
commit_check-2.23.0.dist-info/entry_points.txt,sha256=-4RWjQDhmngfCnTx46iCz3RrI8WZoiMZo0nhsg6hmUw,125
|
|
22
|
+
commit_check-2.23.0.dist-info/top_level.txt,sha256=Wf46u-ooHBMJNHbhfrBNQw3wC5_m8wt-o_Lfbc4QpRg,13
|
|
23
|
+
commit_check-2.23.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|