morpheus
morpheus

Reputation: 20350

How can a program know its own git SHA?

I understand there may be no solution for this but we are building a system which does some data processing and in the logs we want to store the version of the program which is used to generate the data. We are using Java in case it matters. The program version is nothing but the git SHA. Using the SHA we can track which build / commit was used to generate the data. How can our program determine its git SHA? Is it even possible? Appreciate your thoughts.

One possible thought is to have a script which upon committing the code, extracts the git SHA from the commit message and then writes it to a resources file. This file obviously would not be tracked by git (i.e., file needs to be added to .gitignore). At runtime the program would read the SHA from this file. Any better alternatives?

One thing we really want to avoid is a developer accidentally committing code by running git commit directly instead of running the script. If that happens the SHA in the resources file will not get updated and this would introduce a serious bug. How to handle this?

Another issue is that when we do git commit -m "commit message", git does not spit out the complete SHA but instead truncates it. How can we get git to print out the full SHA?

Upvotes: 0

Views: 519

Answers (3)

danglingpointer
danglingpointer

Reputation: 4920

Git SHA isnt truncated. Truncate means cutting it off.

SHA is just 64bit hascode key in non-human readable format.

What is sha?

sha is a simple program that hashes files. It uses the National Institute of Standards and Technology's Secure Hash Algorithm. It can use SHA-1, SHA-256, SHA-384, or SHA-512, which generate respectively, hashes of 160, 256, 384, or 512 bits. sha can be used in scripts to do, for example, file integrity checking. The C implementations of the algorithms might be useful in other projects as well.

There are several techniques to extract the version of software, usually how we use it is using git tag and suffix Major, Minor and Patch at git pre commit hooks, it will autogenrate the release notes and easy to know what feature is running in the different versions.

Upvotes: 0

Steve Harris
Steve Harris

Reputation: 306

Bash variable for your SHA in the repo:

$(git rev-parse HEAD)

You can use that in your build. If you are using something like Jenkins for your builds, then there are other questions with answers for that.

Upvotes: 0

Nick Caballero
Nick Caballero

Reputation: 944

You can store the Git SHA as part of your packaging process. Obviously the implementation depends on your build system but in general, you can write the SHA to a property file and load it at runtime.

Upvotes: 1

Related Questions