Repository navigation
Expand file tree
/
Copy pathcheck_commits.py
More file actions
executable file
·188 lines (160 loc) · 6.58 KB
/
Copy pathcheck_commits.py
File metadata and controls
executable file
·188 lines (160 loc) · 6.58 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
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-3-Clause
"""Validate git commit messages against sof-utils conventions.
Checks enforced for each non-merge commit in the requested git revision range:
1. Subject line:
- Non-empty and at most 75 characters (exempting 'Revert "..."' commits).
- Follows '<prefix>: <short description>' (e.g. 'sof-top: ...',
'sof-builder: parser: ...', 'build, packaging: ...').
- Does not start with 'WIP', 'fixup!', or 'squash!' prefixes.
- Does not end with a trailing period.
2. Separator line:
- Line 2 must be blank when a commit body or trailer is present.
3. Body line wrap:
- Body lines must be at most 75 characters, exempting standard git
trailers (Signed-off-by, Co-authored-by, Reviewed-by, Fixes, Link,
etc.), lines containing URLs, and single unbreakable tokens.
- Rejects stray Gerrit 'Change-Id:' lines.
4. Sign-off (DCO):
- Must contain a valid 'Signed-off-by: Full Name <email@domain>' trailer.
"""
from __future__ import annotations
import argparse
import re
import subprocess
import sys
from typing import List, Sequence, Tuple
MAX_SUBJECT_LEN = 75
MAX_BODY_LINE_LEN = 75
# Prefix format: '<prefix>: <description>' (supports nested 'a: b: desc' and
# comma-separated multi-tool prefixes like 'sof-top, sof-remote-server: desc').
SUBJECT_PREFIX_RE = re.compile(r"^([^:\s][^:]*):\s+(\S.*)$")
FORBIDDEN_PREFIX_RE = re.compile(r"^(?:wip\b|fixup!|squash!|amend!)", re.IGNORECASE)
SOB_RE = re.compile(r"^Signed-off-by:\s+\S+(?:\s+\S+)+\s+<[^<>\s@]+@[^<>\s@]+\.[^<>\s@]+>$")
TRAILER_EXEMPT_RE = re.compile(
r"^(?:Signed-off-by|Co-authored-by|Reviewed-by|Acked-by|Tested-by|"
r"Reported-by|Suggested-by|Fixes|Closes|Link|Cc|Helped-by):",
re.IGNORECASE,
)
URL_RE = re.compile(r"https?://\S+")
BLOCKED_TAG_RE = re.compile(r"^\s*Change-Id:", re.IGNORECASE)
def validate_commit_message(sha: str, raw_message: str) -> List[str]:
"""Validate a single commit message and return a list of error strings."""
errors: List[str] = []
lines = raw_message.rstrip("\n").splitlines()
if not lines or not lines[0].strip():
return [f"{sha}: commit subject is empty"]
subject = lines[0]
is_revert = subject.startswith('Revert "')
if FORBIDDEN_PREFIX_RE.match(subject):
errors.append(
f"{sha}: line 1: subject contains forbidden prefix (WIP/fixup!/squash!): {subject!r}"
)
if not is_revert:
if len(subject) > MAX_SUBJECT_LEN:
errors.append(
f"{sha}: line 1: subject exceeds {MAX_SUBJECT_LEN} characters "
f"({len(subject)} > {MAX_SUBJECT_LEN}): {subject!r}"
)
if not SUBJECT_PREFIX_RE.match(subject):
errors.append(
f"{sha}: line 1: subject must follow '<prefix>: <description>' "
f"(e.g. 'sof-top: short description'): {subject!r}"
)
if subject.endswith("."):
errors.append(
f"{sha}: line 1: subject must not end with a trailing period: {subject!r}"
)
if len(lines) >= 2 and lines[1].strip() != "":
errors.append(
f"{sha}: line 2: expected a blank line between subject and body, "
f"got {lines[1]!r}"
)
has_valid_sob = False
has_malformed_sob = False
for idx, line in enumerate(lines[1:], start=2):
if BLOCKED_TAG_RE.match(line):
errors.append(f"{sha}: line {idx}: blocked tag 'Change-Id:' found")
if line.lower().startswith("signed-off-by:"):
if SOB_RE.match(line):
has_valid_sob = True
else:
has_malformed_sob = True
errors.append(
f"{sha}: line {idx}: malformed Signed-off-by trailer "
f"(expected 'Signed-off-by: Full Name <email@domain>'): {line!r}"
)
continue
if len(line) > MAX_BODY_LINE_LEN:
if TRAILER_EXEMPT_RE.match(line) or URL_RE.search(line):
continue
# Allow a single unbreakable token (e.g., long path or identifier)
if len(line.strip().split()) <= 1:
continue
errors.append(
f"{sha}: line {idx}: body line exceeds {MAX_BODY_LINE_LEN} characters "
f"({len(line)} > {MAX_BODY_LINE_LEN}): {line!r}"
)
if not has_valid_sob and not has_malformed_sob:
errors.append(
f"{sha}: missing 'Signed-off-by: Full Name <email@domain>' trailer "
"(use 'git commit -s')"
)
return errors
def iter_commits(rev_range: str) -> List[Tuple[str, str, str]]:
"""Return list of (short_sha, author_name, commit_message) for rev_range."""
sep = "\x1e"
field_sep = "\x1f"
cmd = [
"git",
"log",
"--no-merges",
f"--format=%h{field_sep}%an{field_sep}%B{sep}",
rev_range,
]
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
commits: List[Tuple[str, str, str]] = []
for entry in res.stdout.split(sep):
entry = entry.strip("\n")
if not entry:
continue
parts = entry.split(field_sep, 2)
if len(parts) != 3:
continue
commits.append((parts[0], parts[1], parts[2]))
return commits
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Check git commit messages for subject format, 75-char wrap, and Signed-off-by."
)
parser.add_argument(
"rev_range",
nargs="?",
default="origin/main..HEAD",
help="Git revision range to validate (default: origin/main..HEAD)",
)
args = parser.parse_args(argv)
try:
commits = iter_commits(args.rev_range)
except subprocess.CalledProcessError as exc:
print(f"ERROR: git log failed for {args.rev_range!r}: {exc.stderr.strip()}", file=sys.stderr)
return 2
if not commits:
print(f"No non-merge commits found in range {args.rev_range!r}.")
return 0
all_errors: List[str] = []
checked = 0
for sha, author, msg in commits:
if author == "dependabot[bot]":
continue
checked += 1
all_errors.extend(validate_commit_message(sha, msg))
if all_errors:
print(f"Commit message check FAILED ({len(all_errors)} issue(s) across {checked} commit(s)):\n")
for err in all_errors:
print(f" - {err}")
return 1
print(f"Commit message check PASSED ({checked} commit(s) in {args.rev_range}).")
return 0
if __name__ == "__main__":
raise SystemExit(main())