Work out the next version from commit messages, as release tools do.
What to build
A program that computes the next semantic version from the commits since the last release.
Requirements
- Read the subjects as conventional commits (ignore ones that do not match). A breaking change is a subject with
!before the colon, or any commit whose body line starts withBREAKING CHANGE:. - Print
next version: vX.Y.Zand the reason (breaking change,new featureorbug fix), orno release needed.
Input
Line 1: the current version (vX.Y.Z). Line 2: n. Then n lines, each a subject or a body line starting with BREAKING CHANGE:.
Output
One or two lines.
Constraints
n ≤ 200.
Example
Input:
v1.4.2
3
fix: handle empty query
feat(search): add filters
docs: update readme
Output:
next version: v1.5.0
new feature
Why it works
Semantic versions promise users what kind of change to expect, and the commit types record exactly that, so the biggest kind of change decides the bump.
Examples
v1.4.2 3 fix: handle empty query feat(search): add filters docs: update readme
next version: v1.5.0 new feature
v1.4.2 2 docs: update readme chore: tidy files
no release needed
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Scan all subjects first: is there any breaking change, any feat, any fix or perf?
Hint 2
Breaking → MAJOR+1.0.0; else feat → MAJOR.MINOR+1.0; else fix or perf → MAJOR.MINOR.PATCH+1; else no release.
Solution
Show one correct solution (try it yourself first)
import re
PATTERN = re.compile(r"^(\w+)(?:\(([a-z0-9-]+)\))?(!)?: (.+)$")
major, minor, patch = map(int, input().strip().lstrip("v").split("."))
breaking = feature = fix = False
for _ in range(int(input())):
line = input()
if line.startswith("BREAKING CHANGE:"):
breaking = True
continue
m = PATTERN.match(line)
if not m:
continue
kind, bang = m.group(1), m.group(3)
breaking = breaking or bool(bang)
feature = feature or kind == "feat"
fix = fix or kind in ("fix", "perf")
if breaking:
print(f"next version: v{major + 1}.0.0")
print("breaking change")
elif feature:
print(f"next version: v{major}.{minor + 1}.0")
print("new feature")
elif fix:
print(f"next version: v{major}.{minor}.{patch + 1}")
print("bug fix")
else:
print("no release needed")