Automated semantic versioning based on commits.

I wondered if there was a way to automatically update the patch version of SemVer when a commit is made. I tried to make it using the commit hook in python.

  1. Create a version.py file with a variable to store the version:
1
2
# version.py
__version__ = '0.1.0'
  1. Add a pre-commit hook script that updates the version in the version.py file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# .git/hooks/pre-commit
#!/bin/bash

# Get the current version from version.py
VERSION=$(sed -nE 's/^__version__ = (\x27|\")(.*)\1$/\2/p' version.py)

# Increment the patch number
PATCH=$(echo $VERSION | awk -F. '{print $3}')
NEW_PATCH=$(expr $PATCH + 1)
NEW_VERSION=$(echo $VERSION | awk -F. -v new_patch="$NEW_PATCH" '{$3=new_patch; OFS="."; print $1,$2,$3}')

# Update the version in version.py
sed -i '' -E "s/^__version__ = (\x27|\").*(\x27|\")/__version__ = \'$NEW_VERSION\'/" version.py

# Stage the updated version.py file for commit
git add version.py

This script gets the current version number from the version.py file, increments the patch number, updates the version in version.py, and stages the file for commit.

  1. Make the pre-commit hook script executable:
1
chmod +x .git/hooks/pre-commit

Now, when you make a commit, the pre-commit hook script will automatically update the version in version.py. You can use the __version__ variable in your Python code to refer to the current version number. For example:

1
2
3
4
# main.py
import version

print('MyApp version {}'.format(version.__version__))

This will output MyApp version 0.1.1 if the latest commit incremented the patch number.

Share