Bump Semantic Version Git Tag in Python
Automatically find the latest Git tag and compute the next patch release using semantic versioning (semver) in Python.
Python code
27 linesfrom re import match
from subprocess import run
SEMVER_PATTERN = r"^v(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+(?P<buildmetadata>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$"
def get_latest_tag() -> str:
result = run(["git", "describe", "--tags", "--abbrev=0"], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError("No git tags found in this repository")
return result.stdout.strip()
def bump_patch(tag: str) -> str:
if not match(SEMVER_PATTERN, tag):
raise ValueError(f"Invalid semver tag: {tag}")
prefix = "v" if tag.startswith("v") else ""
parts = tag.lstrip("v").split("-")[0].split(".")
parts[2] = str(int(parts[2]) + 1)
return f"{prefix}{'.'.join(parts)}"
if __name__ == "__main__":
current = get_latest_tag()
next_version = bump_patch(current)
print(f"Current tag: {current}")
print(f"Next release tag: {next_version}")
Output
Current tag: v1.2.3
Next release tag: v1.2.4
How it works
The script uses git describe --tags --abbrev=0 to fetch the most recent tag and validates it against a strict semver regex before bumping. The bump_patch function splits the version string, increments the patch number, and reconstructs the tag while preserving the optional v prefix. Using subprocess.run with capture_output=True keeps the output clean and avoids shell injection. The regex follows the official SemVer 2.0.0 spec, covering prerelease and build metadata. This approach is deterministic and works across platforms as long as Git is installed.
Common mistakes
- Not stripping newline from `git describe` output with `.strip()`
- Forgetting to handle missing tags (nonzero return code)
- Assuming tags always have a 'v' prefix when validating semver
Variations
- Use `git tag --sort=-v:refname | head -1` to fetch the latest tag by version order
- Enhance `bump_patch` to also bump minor/major based on a flag or argument
Real-world use cases
- In a CI/CD pipeline, automatically generating the next release version before tagging a new build.
- A release script that suggests the next patch version to a human reviewer before creating a tag.
- Automating version bumps for library releases based on the latest Git tag in a monorepo.
Sponsored
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
- Detect Merge Conflict Markers in a File with Python easy
Keep learning
Related tutorials and quizzes for this topic.