Skip to content

Instantly share code, notes, and snippets.

@CSTDev
Last active October 23, 2024 23:42
Show Gist options
  • Save CSTDev/08c127680e3b5fae38c051da3e489351 to your computer and use it in GitHub Desktop.
Save CSTDev/08c127680e3b5fae38c051da3e489351 to your computer and use it in GitHub Desktop.
Script that will find the last Git Tag and increment it. It will only increment when the latest commit does not already have a tag. By default it increments the patch number, you can tell it to change the major or minor versions by adding #major or #minor to the commit message.
#!/bin/bash
#get highest tag number
VERSION=`git describe --abbrev=0 --tags`
#replace . with space so can split into an array
VERSION_BITS=(${VERSION//./ })
#get number parts and increase last one by 1
VNUM1=${VERSION_BITS[0]}
VNUM2=${VERSION_BITS[1]}
VNUM3=${VERSION_BITS[2]}
VNUM1=`echo $VNUM1 | sed 's/v//'`
# Check for #major or #minor in commit message and increment the relevant version number
MAJOR=`git log --format=%B -n 1 HEAD | grep '#major'`
MINOR=`git log --format=%B -n 1 HEAD | grep '#minor'`
if [ "$MAJOR" ]; then
echo "Update major version"
VNUM1=$((VNUM1+1))
VNUM2=0
VNUM3=0
elif [ "$MINOR" ]; then
echo "Update minor version"
VNUM2=$((VNUM2+1))
VNUM3=0
else
echo "Update patch version"
VNUM3=$((VNUM3+1))
fi
#create new tag
NEW_TAG="v$VNUM1.$VNUM2.$VNUM3"
echo "Updating $VERSION to $NEW_TAG"
#get current hash and see if it already has a tag
GIT_COMMIT=`git rev-parse HEAD`
NEEDS_TAG=`git describe --contains $GIT_COMMIT`
#only tag if no tag already (would be better if the git describe command above could have a silent option)
if [ -z "$NEEDS_TAG" ]; then
echo "Tagged with $NEW_TAG (Ignoring fatal:cannot describe - this means commit is untagged) "
git tag $NEW_TAG
git push --tags
else
echo "Already a tag on this commit"
fi
@chromero
Copy link

I just added --match="v[0-9]*" to the first line.
It allows to filter tags and have only v[n] tags listed

VERSION=`git describe --abbrev=0 --tags --match="v[0-9]*"`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment