Validate commit subjects against the Conventional Commits format.
What to build
A program that checks commit subjects and extracts their parts.
Requirements
- Format:
type(scope)!: description, where the scope (lower-case letters, digits and hyphens, in brackets) and!are optional, followed by a colon, one space and a non-empty description. Allowed types: build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test. - Print
type=T scope=S breaking=yes|no description=D(S is-without a scope),invalid: wrong formatorinvalid: unknown type T.
Input
Line 1: n. Then n subjects.
Output
n lines.
Constraints
n ≤ 200.
Example
Input:
3
feat(search): add filters
fix: handle empty query
update stuff
Output:
type=feat scope=search breaking=no description=add filters
type=fix scope=- breaking=no description=handle empty query
invalid: wrong format
Why it works
A fixed structure lets both people and programs read what kind of change each commit is.
Examples
Example 1 · Input
3 feat(search): add filters fix: handle empty query update stuff
Expected output
type=feat scope=search breaking=no description=add filters type=fix scope=- breaking=no description=handle empty query invalid: wrong format
Example 2 · Input
2 feat(api)!: remove v1 feature: something
Expected output
type=feat scope=api breaking=yes description=remove v1 invalid: unknown type feature
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A regular expression such as `^(\w+)(?:\(([a-z0-9-]+)\))?(!)?: (.+)$` captures the parts.
Hint 2
Check the type against the allowed list after the format matches.
Solution
Show one correct solution (try it yourself first)
import re
PATTERN = re.compile(r"^(\w+)(?:\(([a-z0-9-]+)\))?(!)?: (.+)$")
TYPES = {"build", "chore", "ci", "docs", "feat", "fix", "perf", "refactor", "revert", "style", "test"}
for _ in range(int(input())):
subject = input()
m = PATTERN.match(subject)
if not m:
print("invalid: wrong format")
elif m.group(1) not in TYPES:
print(f"invalid: unknown type {m.group(1)}")
else:
kind, scope, bang, description = m.groups()
print(f"type={kind} scope={scope or '-'} breaking={'yes' if bang else 'no'} description={description}")