Add Git commit ID to application log

Context

In most software projects, multiple developers tend to push code into the repo, in parallel.  In some projects, the nature of the application forces each tester to deploy the app into a separate server (assigned to that tester) for testing each functionality.  


Challenge

I'm in a such a project and we often run into issues where the tester has not deployed the correct version of the binary which has the needed Git commit.  We haven't started to version our binaries because we are at an early stage of the development.

Life would be easier for everyone involved if there was a way to map each binary to the latest Git commit, from which it was built.  I recently learned from my colleague that this is indeed possible, assuming the following:

  1. The project uses some kind of a basic Continuous Integration set-up to build the binary automatically.
  2. The programming language that you are using, has the ability to inject variables into the executables at build-time.

Continuous Integration

A typical CI set-up will automatically trigger a build as soon as a commit is pushed into the common branch.  This trigger usually invokes a script file (eg. Makefile), that contains the command needed to build the binary.  This script is usually executed in a server which has Git installed (to pull the latest code).

Git + Makefile + GoLang

Let me show how this is done in the context of Git, Makefile & GoLang.  But this should be applicable with other set-ups and languages as well.  

First, we need to extract the latest commit ID from Git.  This can be achieved by using the command 
git rev-parse --short HEAD
Now, add this command to the build command in the Makefile, like so
go build -ldflags "-X main.GitCommit=$(shell git rev-parse --short HEAD)"
 The command essentially says "pull the Git commit ID and assign it to the variable GitCommit inside the main package".

Now, simply create a variable named GitCommit in the main package and print it on the console or log, during app start-up.


Attributions - Icons for the illustration were sourced from http://thenounproject.com/

Comments