Skip to content

Instantly share code, notes, and snippets.

@MichaelCurrin
Last active February 23, 2023 12:41
Show Gist options
  • Save MichaelCurrin/83373c6dae8c6f8d147b5b3cc82fdc7b to your computer and use it in GitHub Desktop.
Save MichaelCurrin/83373c6dae8c6f8d147b5b3cc82fdc7b to your computer and use it in GitHub Desktop.
Increment and create a Git tag based on whether [MAJOR] or [MINOR] appears in the current commit message

Setup

If you make the script executable and in your bin directory, you can run it from anywhere.

$ chmod +x commit_msg_tag.sh
$ sudo mv commit_msg_tag.sh /usr/local/bin/commit_msg_tag

Then run as:

$ commit_msg_tag

Usage

$ git commit -m "[MAJOR] new feature"
$ commit_msg_tag
$ # OR run directory if in current directory.
$ bash commit_msg_tag.sh
#!/bin/bash
# Increment and create a Git tag based on commit message.
# If it contains "[MAJOR]" or "[MINOR]" then increment appropriately, otherwise increment patch version.
# Do nothing if already tagged.
#
# Using format like "1.2.3".
if git describe --exact-match --tags HEAD > /dev/null 2>&1; then
echo "Current commit is already tagged."
exit 0
fi
MOST_RECENT_TAG=$(git describe --tags --abbrev=0)
MAJOR_VERSION=$(echo $MOST_RECENT_TAG | cut -d '.' -f 1)
MINOR_VERSION=$(echo $MOST_RECENT_TAG | cut -d '.' -f 2)
PATCH_VERSION=$(echo $MOST_RECENT_TAG | cut -d '.' -f 3)
COMMIT_MESSAGE=$(git log -1 --pretty=%B)
if echo $COMMIT_MESSAGE | grep -iq "\[MAJOR\]"; then
NEW_VERSION="$((MAJOR_VERSION + 1)).0.0"
elif echo $COMMIT_MESSAGE | grep -iq "\[MINOR\]"; then
NEW_VERSION="$MAJOR_VERSION.$((MINOR_VERSION + 1)).0"
else
NEW_VERSION="$MAJOR_VERSION.$MINOR_VERSION.$((PATCH_VERSION + 1))"
fi
git tag $NEW_VERSION
echo "Tagged current commit with version $NEW_VERSION."
#!/bin/bash
# Increment and create a Git tag based on commit message.
# If it contains "[MAJOR]" or "[MINOR]" then increment appropriately, otherwise increment patch version.
# Do nothing if already tagged.
#
# Using format like "v1.2.3".
if git describe --exact-match --tags HEAD > /dev/null 2>&1; then
echo "Current commit is already tagged."
exit 0
fi
MOST_RECENT_TAG=$(git describe --tags --abbrev=0 | sed 's/^v//')
MAJOR_VERSION=$(echo $MOST_RECENT_TAG | cut -d '.' -f 1)
MINOR_VERSION=$(echo $MOST_RECENT_TAG | cut -d '.' -f 2)
PATCH_VERSION=$(echo $MOST_RECENT_TAG | cut -d '.' -f 3)
COMMIT_MESSAGE=$(git log -1 --pretty=%B)
if echo $COMMIT_MESSAGE | grep -iq "\[MAJOR\]"; then
NEW_VERSION="v$((MAJOR_VERSION + 1)).0.0"
elif echo $COMMIT_MESSAGE | grep -iq "\[MINOR\]"; then
NEW_VERSION="v$MAJOR_VERSION.$((MINOR_VERSION + 1)).0"
else
NEW_VERSION="v$MAJOR_VERSION.$MINOR_VERSION.$((PATCH_VERSION + 1))"
fi
# Tag the commit with the new version number
git tag $NEW_VERSION
echo "Tagged current commit with version $NEW_VERSION."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment