Setting Release Version Via Branch Name Using GitHub Actions

If you are tired of creating git tags, forgetting to use git push --tags, or are otherwise annoyed by having to think about versioning rather than code, this one’s for you.

Trunk-based development (the only git branching strategy I’m aware of with research backing it’s efficacy) encourages release branches. Those release branches are often named releases/v1.5.4 or the like.

Why duplicate effort? If the version name is all right there in the release branch, why not get it from there and use it rather than relying on cumbersome tags in git?

Why indeed. Here’s a GitHub action sample that scrapes the version from the release branch name:

name: Build and release on push to releases

on:
  push:
    branches: [ releases/* ]
permissions:
  contents: write
  
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3 #1 (Explanation)
      with:
        fetch-depth: 0
    - name: Compute Tag Name
      id: compute-tag
      run: |
        BRANCH_NAME=$(git branch --show-current) #2 (Explanation)
        VERSION_NAME=$(basename $BRANCH_NAME) #3 (Explanation)
        echo "tagname=${VERSION_NAME}" >> $GITHUB_OUTPUT #4 (Explanation)

    - name: Build
      run: echo ${{ steps.compute-tag.outputs.tagname }} >> ./release_file.txt #5 (Explanation)
      
    - name: Create release
      uses: ncipollo/release-action@v1
      with:
        token: ${{ secrets.GITHUB_TOKEN }}
        tag: ${{ steps.compute-tag.outputs.tagname }} #6 (Explanation)
        commit: main
        artifacts: './release_file.txt'

Explanation

  1. uses: actions/checkout is required to be able to access your git branch from GitHub actions
  2. BRANCH_NAME=$(git branch --show-current) gets the latest branch name (e.g. releases/v1.5.4
  3. VERSION_NAME=$(basename $BRANCH_NAME) gets the last part of the path of the branch name (e.g. v.1.5.4). If you had a branch name of releases/hotfix/v.1.5.5 it would still return the last part (e.g. v.1.5.5)
  4. echo "tagname=${VERSION_NAME}" >> $GITHUB_OUTPUT sets the tag name for the current branch to version name
  5. echo ${{ steps.compute-tag.outputs.tagname }} >> ./release_file.txt writes the version number to a file (simulating a build step)
  6. tag: ${{ steps.compute-tag.outputs.tagname}} uses ncipollo’s release action to actually create a release using the set tag

Source Code

To see the source code, the releases, and the Action in, well, action – here’s the source code on GitHub.

↓ I'll get a dopamine hit if you share this post