How to tag a Git commit by using semantic versioning?

A Semantic versioning is a simple and popular concept these days. As we all (?) use Git in our daily life, it would be great if we could create Git tags based on Semantic versioning, right?

Well, this little script could help us:

filename=`basename "$0"`

function setVersionNumbers() {
  # Get latest existing tag
  latestTag=$(git describe --tags --abbrev=0 2>/dev/null) || true

  if [[ -z "$latestTag" ]]; then
    # First version
    initialRelease=true
    latestTag='v1.0.0'
  fi

  # Set version numbers
  major=$(echo $latestTag | cut -d. -f1)
  minor=$(echo $latestTag | cut -d. -f2)
  patch=$(echo $latestTag | cut -d. -f3)
}

function printUsage() {
  echo "./$filename {major|minor|patch}"
  echo "For instance: ./$filename minor"
}

function increaseMajorVersion() {
  # Remove "v" prefix
  major="${major/v}"

  major="v$((major + 1))"
  minor=0
  patch=0
}

function increaseMinorVersion() {
    minor=$((minor + 1))
    patch=0
}

function increasePatchVersion() {
    patch=$((patch + 1))
}

function tagVersion() {
  echo "Tagging release with: $latestTag"
  git tag -a $latestTag -m "Releasing version $latestTag"
  git push origin $latestTag
}

# Get action from the command line & convert it to lower case
commandLineActionArgument=$1
action=$(echo "$commandLineActionArgument" | tr '[:upper:]' '[:lower:]')

if [[ -z "$action" ]]; then
  printUsage
  exit 0
fi

setVersionNumbers

# If it's initial release v1.0.0 - simply tag it
if [ "$initialRelease" = "true" ]; then
    tagVersion
    exit 0
fi

case $action in
  major)
    increaseMajorVersion
    ;;
  minor)
    increaseMinorVersion
    ;;
  patch)
    increasePatchVersion
    ;;
  *)
    echo "Unknown action selected, aborting"
    printUsage
    exit 0
    ;;
esac

latestTag="${major}.${minor}.${patch}"

tagVersion

This little script can be used as follows:

# Increases major version: v1.4.0 -> v2.0.0
./script.sh major

# Increases minor version: v1.4.0 -> v1.5.0
./script.sh minor

# Increases patch version: v1.4.0 -> v1.4.1
./script.sh patch

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *