Auto versioning your app with a simple bash script

Author: Bjørnar Hagen

Date published: 2024-01-05T13:03:00Z

Auto versioning your app with a simple bash script

To automatically version your app can be pretty complicated and a lot of solutions require complex dependencies and configurations. In this post I will show you how to do it with just a simple Bash script and Git.

Preqrequisites

Bash, Git

The script

 1#!/bin/bash
 2
 3echo "🚀 Starting auto-version script"
 4
 5# Get the latest tag from git and use it to get the version number
 6VERSION=$(git describe --abbrev=0 --tags)
 7VERSION_NUMBER=$(echo $VERSION | sed 's/v//g')
 8OLD_VERSION_NUMBER=$(echo $VERSION | sed 's/v//g')
 9
10# Get the number of commits since the last tag
11COMMITS_SINCE_TAG=$(git rev-list --count $VERSION..HEAD)
12
13MAJOR=$(echo $VERSION_NUMBER | cut -d'.' -f1)
14MINOR=$(echo $VERSION_NUMBER | cut -d'.' -f2)
15PATCH=$(echo $VERSION_NUMBER | cut -d'.' -f3)
16
17INCREASE_MAJOR=false
18INCREASE_MINOR=false
19INCREASE_PATCH=false
20
21# Loop through the commits and check the prefix of each commit message
22for COMMIT in $(git log --pretty=format:"%H" $VERSION..HEAD); do
23  MESSAGE=$(git log --pretty=format:"%s" -n 1 $COMMIT)
24  echo "🔍 Checking commit message: \"$MESSAGE\""
25  case $MESSAGE in
26  breaking:*)
27    INCREASE_MAJOR=true
28    INCREASE_MINOR=true
29    INCREASE_PATCH=true
30    echo "   💥 Breaking change detected 💥"
31    ;;
32  feat:*)
33    INCREASE_MINOR=true
34    INCREASE_PATCH=true
35    echo "   ✨ Minor change detected ✨"
36    ;;
37  refactor:* | fix:* | build:* | ci:* | docs:* | perf:* | style:* | test:* | chore:*)
38    INCREASE_PATCH=true
39    echo "   🛠️ Patch change detected 🛠️"
40    ;;
41  *)
42    echo "   🤷 No change detected, make sure to follow the commit message format! 🤷"
43    ;;
44  esac
45done
46
47if [ "$INCREASE_MAJOR" = true ]; then
48  MAJOR=$((MAJOR + 1))
49  MINOR=0
50  PATCH=0
51elif [ "$INCREASE_MINOR" = true ]; then
52  MINOR=$((MINOR + 1))
53  PATCH=0
54elif [ "$INCREASE_PATCH" = true ]; then
55  PATCH=$((PATCH + 1))
56fi
57
58VERSION_NUMBER="$((MAJOR)).$((MINOR)).$((PATCH))"
59echo "Old version: $OLD_VERSION_NUMBER"
60echo "New version: $VERSION_NUMBER"
61
62echo "optional-prefix-v$VERSION_NUMBER" >public/version.txt