Release Engineering Exercises
Each exercise is a small piece of release logic written as a pure function, with the calls already in place. Run the starter first: it prints placeholder answers, which shows what the calls expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real Git session with a bug to fix.
Exercise 1: Sort versions by SemVer precedence
Topics: Semantic Versioning & Precedence, Pre-releases & Build Metadata
Write key(version) so that sorted(versions, key=key) orders versions by SemVer precedence: numeric core, a release after its pre-releases, numeric identifiers before text, a shorter pre-release list first when all earlier identifiers are equal, and build metadata ignored.
versions = ["1.0.0", "1.0.0-rc.1", "1.0.0-alpha", "1.10.0", "1.9.0", "1.0.0-alpha.1",
"1.0.0-beta.11", "1.0.0-beta.2", "1.0.0+build.7", "0.9.9"]
def key(version):
# TODO: drop "+metadata", split core and pre-release, build a sortable tuple
return version
print(sorted(versions, key=key))['0.9.9', '1.0.0', '1.0.0+build.7', '1.0.0-alpha', '1.0.0-alpha.1', '1.0.0-beta.11', '1.0.0-beta.2', '1.0.0-rc.1', '1.10.0', '1.9.0']
Expected output:
['0.9.9', '1.0.0-alpha', '1.0.0-alpha.1', '1.0.0-beta.2', '1.0.0-beta.11', '1.0.0-rc.1', '1.0.0', '1.0.0+build.7', '1.9.0', '1.10.0']Show solution
def key(version):
core, _, pre = version.split("+")[0].partition("-")
nums = tuple(int(p) for p in core.split("."))
if not pre:
return (nums, 1, ()) # a release sorts after all its pre-releases
ids = tuple((0, int(i), "") if i.isdigit() else (1, 0, i) for i in pre.split("."))
return (nums, 0, ids)Python's sorted is stable, so 1.0.0 and 1.0.0+build.7 (equal precedence) keep their input order.
Exercise 2: The next version from commits
Topics: Conventional Commits, semantic-release
Given the last version and the commit subjects since it, return the next version, or None if nothing is releasable. feat → minor, fix/perf/revert → patch, ! before the colon or a BREAKING CHANGE: line → major; everything else releases nothing.
import re
def next_version(last, messages):
# TODO: find the highest bump among the messages and apply it to `last`
return last
print(next_version("1.4.2", ["fix: a", "docs: b"]))
print(next_version("1.4.2", ["fix: a", "feat(cli): b"]))
print(next_version("1.4.2", ["chore: a", "refactor(api)!: rename"]))
print(next_version("1.4.2", ["refactor: x\n\nBREAKING CHANGE: Client is gone"]))
print(next_version("1.4.2", ["docs: only docs", "ci: only ci"]))1.4.2
1.4.2
1.4.2
1.4.2
1.4.2
Expected output:
1.4.3
1.5.0
2.0.0
2.0.0
NoneShow solution
def next_version(last, messages):
order = {None: 0, "patch": 1, "minor": 2, "major": 3}
bump = None
for msg in messages:
header = msg.split("\n")[0]
m = re.match(r"^(\w+)(\([^)]*\))?(!)?: ", header)
if not m:
continue
if m.group(3) or re.search(r"^BREAKING[ -]CHANGE: ", msg, re.M):
kind = "major"
else:
kind = {"feat": "minor", "fix": "patch", "perf": "patch", "revert": "patch"}.get(m.group(1))
if order[kind] > order[bump]:
bump = kind
if bump is None:
return None
major, minor, patch = map(int, last.split("."))
return {"major": f"{major + 1}.0.0", "minor": f"{major}.{minor + 1}.0",
"patch": f"{major}.{minor}.{patch + 1}"}[bump]Exercise 3: Group a changelog
Topics: Changelogs for Humans, Configuring git-cliff
Turn commit subjects into Keep a Changelog sections, in the order Added (feat), Fixed (fix), Changed (perf, refactor with !). Skip every other type. Scopes become a bold prefix, and the first letter of the description is capitalised.
commits = [
"feat(cli): add --json output",
"fix: crash on empty input",
"chore(deps): bump serde",
"perf(cache): reuse parsed files",
"refactor(api)!: rename Client to Session",
"refactor: tidy imports",
"fix(io): close files on error",
]
def changelog(version, date, subjects):
# TODO: build "## [version] - date", then "### Section" blocks with "- " lines
return f"## [{version}] - {date}"
print(changelog("1.5.0", "2026-01-15", commits))## [1.5.0] - 2026-01-15
Expected output:
## [1.5.0] - 2026-01-15
### Added
- **cli:** Add --json output
### Fixed
- Crash on empty input
- **io:** Close files on error
### Changed
- **cache:** Reuse parsed files
- **api:** Rename Client to SessionShow solution
import re
def changelog(version, date, subjects):
sections = {"Added": [], "Fixed": [], "Changed": []}
for s in subjects:
m = re.match(r"^(\w+)(?:\(([^)]*)\))?(!)?: (.+)quot;, s)
if not m:
continue
kind, scope, bang, desc = m.groups()
if kind == "feat":
section = "Added"
elif kind == "fix":
section = "Fixed"
elif kind == "perf" or (kind == "refactor" and bang):
section = "Changed"
else:
continue
prefix = f"**{scope}:** " if scope else ""
sections[section].append(f"- {prefix}{desc[0].upper()}{desc[1:]}")
out = [f"## [{version}] - {date}"]
for title, lines in sections.items():
if lines:
out += ["", f"### {title}", *lines]
return "\n".join(out)Exercise 4: Name the artifacts
Topics: Artifact Naming & Checksums, Matrix Builds
From a tag and a build matrix, produce the artifact file names (tad-<version>-<os>-<arch>.<ext>, zip for Windows and macOS, tar.gz otherwise) and decide whether the release is a pre-release. Reject tags that aren't v + SemVer.
import re
matrix = [("linux", "x86_64"), ("linux", "aarch64"), ("macos", "arm64"), ("windows", "x86_64")]
def plan(tag):
# TODO: validate the tag, strip the "v", build the names; return (names, prerelease)
return ([], False)
for tag in ["v1.4.2", "v2.0.0-rc.1", "1.4.2", "v1.4"]:
try:
names, pre = plan(tag)
print(tag, "prerelease" if pre else "release", names)
except ValueError as e:
print(tag, "rejected:", e)v1.4.2 release []
v2.0.0-rc.1 release []
1.4.2 release []
v1.4 release []
Expected output:
v1.4.2 release ['tad-1.4.2-linux-x86_64.tar.gz', 'tad-1.4.2-linux-aarch64.tar.gz', 'tad-1.4.2-macos-arm64.zip', 'tad-1.4.2-windows-x86_64.zip']
v2.0.0-rc.1 prerelease ['tad-2.0.0-rc.1-linux-x86_64.tar.gz', 'tad-2.0.0-rc.1-linux-aarch64.tar.gz', 'tad-2.0.0-rc.1-macos-arm64.zip', 'tad-2.0.0-rc.1-windows-x86_64.zip']
1.4.2 rejected: not a release tag: 1.4.2
v1.4 rejected: not a release tag: v1.4Show solution
TAG = re.compile(r"^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?quot;)
def plan(tag):
m = TAG.match(tag)
if not m:
raise ValueError(f"not a release tag: {tag}")
version = tag[1:]
names = [f"tad-{version}-{os}-{arch}.{'zip' if os in ('windows', 'macos') else 'tar.gz'}"
for os, arch in matrix]
return names, m.group(4) is not NoneExercise 5: Which fixes still need a backport?
Topics: Backport Flows
main_log lists commits on main since the release branch was cut; branch_log lists commits on the release branch, including cherry-picks with their (cherry picked from commit …) trailer. Return the fix commits from main that have not been picked yet.
main_log = [
("a1f3", "feat: new export dialog", ""),
("b2e4", "fix: crash on empty input", ""),
("c3d5", "fix(io): close files on error", ""),
("d4c6", "docs: update README", ""),
("e5b7", "fix(sec): reject path traversal", ""),
]
branch_log = [
("9f01", "fix: crash on empty input", "(cherry picked from commit b2e4)"),
("8e02", "fix: release-only build fix", ""),
]
def missing_backports(main_log, branch_log):
# TODO: collect the picked ids from the trailers, then filter main's fix commits
return []
print(missing_backports(main_log, branch_log))[]
Expected output:
['c3d5 fix(io): close files on error', 'e5b7 fix(sec): reject path traversal']Show solution
import re
def missing_backports(main_log, branch_log):
picked = {m.group(1) for _, _, body in branch_log
for m in [re.search(r"cherry picked from commit (\w+)", body)] if m}
return [f"{sha} {subject}" for sha, subject, _ in main_log
if re.match(r"^fix(\(|!|:)", subject) and sha not in picked]Exercise 6: Fix the release script
Topics: Annotated vs Lightweight Tags, git describe & Version Strings
This release script computes the version with git describe, then pushes the tag with --follow-tags. It runs without errors, but the version is wrong and the remote never gets the release tag. Find the two problems (they have the same cause) and fix the script.
git init -q --bare remote.git
git clone -q remote.git app 2>/dev/null && cd app
git commit -q --allow-empty -m "feat: first release"
git tag -a v1.0.0 -m "v1.0.0"
git commit -q --allow-empty -m "feat: second release"
# --- the release script ---
git tag v1.1.0
echo "building version $(git describe --always)"
git push -q --follow-tags origin main
echo "tags on the remote: $(git ls-remote --tags origin | grep -v '\^{}' | cut -f2 | tr '\n' ' ')"building version v1.0.0-1-gaf0d893
tags on the remote: refs/tags/v1.0.0
Expected output after the fix:
building version v1.1.0
tags on the remote: refs/tags/v1.0.0 refs/tags/v1.1.0Show solution
git tag v1.1.0 creates a lightweight tag. git describe ignores lightweight tags by default (so it describes from v1.0.0) and --follow-tags only pushes annotated tags. Create an annotated tag:
git tag -a v1.1.0 -m "v1.1.0"(git describe --tags and pushing the tag by name would also work around each symptom, but release tags should be annotated.)