DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Hector Leiva
Hector Leiva

Posted on

Github Actions and creating a short SHA hash

This will be a quick post as a sort of reminder for myself (and anyone else) on how to actually generate a short git commit SHA hash in Github actions for a particular build.

git commit hashes are important for various reasons

git commit SHA hashes are useful in tagging releases and to know what was the state of the code at a certain point in time.

git commit SHA hashes are also really long: 9c1e1a7f8f3827b11fb9eb34ab0a21afde30e19c (for example). Sometimes as an engineer you just need to know the first say 6 characters and that's more than enough to know which point in time the code is in.


Github provided short commit SHA hashes for some time, but not anymore

Github depreciated the Short SHA environment variable in January, 2021

This makes sense because if you're going to shorten a git commit SHA, which one are your planning on shortening? You might need the github.event.pull_request_head.sha for certain workflows OR you might need the github.sha which depends on which event triggered that specific run.


My solution to generating a short git commit SHA hash

- name: Set short git commit SHA
  id: vars
  run: |
    calculatedSha=$(git rev-parse --short ${{ github.sha }})
    echo "::set-output name=short_sha::$calculatedSha"

- name: Confirm git commit SHA output
  run: echo ${{ steps.vars.outputs.short_sha }}
Enter fullscreen mode Exit fullscreen mode

How is this different from what's in Stackoverflow

What's annoying about this particular Stackoverflow post is that none of the solutions stated are quite correct as-of the writing of this post.

run: echo "::set-output name=sha_short::$(git rev-parse --short HEAD)"
Enter fullscreen mode Exit fullscreen mode

Doesn't work since you don't know exactly which HEAD is being declared in the context of a Github Action runner.

echo "::set-output name=sha_short::$(git rev-parse --short ${{ github.event.pull_request.head.sha }})"
Enter fullscreen mode Exit fullscreen mode

Doesn't work because you can't use "" double-quotes when referencing ${{ }} tags. But even if you used the '' single-quotes to wrap this expression, what ends up happening is that sha_short doesn't equal the string of the git commit SHA, but it's the expression:

$(git rev-parse --short ${{ github.event.pull_request.head.sha }})
Enter fullscreen mode Exit fullscreen mode

So any time you use sha_short later on in your run, it'll have to re-run that entire expression again (which will return what you want, but there's no need to re-run an expression and instead it's better to store the value).

I hope that this might help anyone else who is trying to find a simple way to shorten a git commit SHA hash. At least for now!

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.