Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current branch and commit hash in GitHub action

I want to build a docker image using a GitHub action, migrating from TeamCity.

In the build script, I want to tag the image with a combination of branch and commit, e.g. master.ad959de. Testing that locally, I get that information like this:

git_branch=`git symbolic-ref --short HEAD` git_hash=`git rev-parse --short HEAD` docker_version=${git_branch}.${git_hash} 

This is the relevant part of the GitHub action:

name: CI on: [push] jobs:   build:     runs-on: ubuntu-latest     steps:     - uses: actions/checkout@v1      - name: Create docker image       run: ./docker-build.sh    

Running that script in that GitHub action results in this error:

fatal: ref HEAD is not a symbolic ref 

How can I generate a tag like that inside a GitHub action?

like image 608
Rüdiger Schulz Avatar asked Nov 16 '19 00:11

Rüdiger Schulz


People also ask

How do you find the hash of a commit on GitHub?

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master ), or the "Issues" tab to see pull requests containing the commit.

How do I get the latest commit hash?

# open the git config editor $ git config --global --edit # in the alias section, add ... [alias] lastcommit = rev-parse HEAD ... From here on, use git lastcommit to show the last commit's hash.

Where can I find the commit hash?

If you have the hash for a commit, you can use the git show command to display the changes for that single commit. The output is identical to each individual commit when using git log -p .

How does git determine commit hash?

In Git, get the tree hash with: git cat-file commit HEAD | head -n1. The commit hash by hashing the data you see with cat-file . This includes the tree object hash and commit information like author, time, commit message, and the parent commit hash if it's not the first commit.


1 Answers

from Using environment variables

github provides two variables that are useful here, you'll need to process them a bit to get the values you desire:

GITHUB_SHA: The commit SHA that triggered the workflow. For example, ffac537e6cbbf934b08745a378932722df287a53.

GITHUB_REF: The branch or tag ref that triggered the workflow. For example, refs/heads/feature-branch-1. If neither a branch or tag is available for the event type, the variable will not exist.

The short values can be extracted like this:

git_hash=$(git rev-parse --short "$GITHUB_SHA") git_branch=${GITHUB_REF#refs/heads/} 
like image 59
Anthony Sottile Avatar answered Sep 16 '22 12:09

Anthony Sottile