Skip to content

Instantly share code, notes, and snippets.

@fcangialosi
Last active August 21, 2017 16:34
Show Gist options
  • Save fcangialosi/da730254e38b6dfc3f71319c8d2be98c to your computer and use it in GitHub Desktop.
Save fcangialosi/da730254e38b6dfc3f71319c8d2be98c to your computer and use it in GitHub Desktop.
git simple automatic per-commit version numbers

This gist shows how to automatically increment and add version numbers to your commit messages and source code.

The major and minor version numbers are managed manually using git tag, while the per-commit numbers are managed automatically with git hooks.

This example uses the following version numbering scheme:

v{MAJOR}.{MINOR}-c{COMMIT#}

Start out by running git tag -a v1.0 for the initial release

Internally, this will be referred to as "v1.0-c1"

The next commit made will automatically be incremented to "v1.0-c2", and so on...

If you need to increment the major or minor version number, add a new tag:

git tag -a v1.1

The commit counter will then be reset and the next commit will internally be referred to as "v1.1-c1"

These hooks prepend this internal version number to your commit messages and also optionally update it in the source code.

Thus, if you run git commit -m 'bugfix', the actual commit message will become [version] bugfix

Edit the pre-commit file as necessary to change the proper place in your code. For simplicity's sake, it assumes the initial version number "v1.0-c1" already exists in the code and uses this to figure out where the version number should be replaced.

#!/bin/sh
new_version=$(.git/hooks/get-next-version)
echo "[$new_version] "$(cat "$1") > "$1"
#!/bin/sh
last_version=$(git log --oneline -1 | cut -d "[" -f2 | cut -d "]" -f1)
last_version_tag=$(echo $last_version | cut -d "-" -f1)
last_manual_tag=$(git describe --abbrev=0)
new_version=$last_manual_tag
if [ "$last_manual_tag" == "$last_version_tag" ]
then
last_commit=$(echo $last_version | cut -d "c" -f2)
new_version="$new_version-c$((last_commit + 1))"
else
new_version="$new_version-c1"
fi
echo $new_version
#!/bin/sh
last_version=$(git log --oneline -1 | cut -d "[" -f2 | cut -d "]" -f1)
new_version=$(.git/hooks/get-next-version)
# TODO: EDIT THIS
source_file=TODO
sed -i'.tmp' "s/$last_version/$new_version/g" $source_file
rm $source_file.tmp
git add $source_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment