Show your software version from GIT hash
Just a few words. Git doesn’t assign a ‘version number’ for your codes. It generates hashes (SHA1) for different commits in different branches. When you release a new version of your code, that code is pointed by a SHA1 code. You can use a portion of that code to programatically show the version of your software.
All the Git information is on the .git directory, inside your project. Git generates a hash for each object (files, trees, commits, etc.) it generates and those hashes are written in plain text in well known files.
You always have a HEAD ‘pointer’ in the .git/HEAD file. If you inspect that file, it will reveal a path to a tag. A tag is just a name that you give to a specific hash, because it is a lot easier to remember and to understand. For example, maybe you have just corrected the last batch of issues on your software and you want to deploy it on our customer system. You have been working on different branches and it ends with a merge of all changes. These changes are, maybe, in the ‘allCorrected’ branch.
‘allCorrected’ is just a tag for a ugly hash of 40 characters. If your last deploy was from the code in ‘allCorrected’, then your HEAD file must have something like:
That is the path for the file which contains the SHA1 code. If you open that path, you will have something like:
The probability of a ‘collision’ (same hash for two different objects) is so small that you don’t need all the bytes. I think that, for the Linux kernel, 8 bytes is the usual identifier. This means that Git just need the first N bytes to identify a code version in your project. So everything is done.
Programatic version text
You just have to:
- Create a library function/class called getGitVersion() or something like that.
- That function has no input parameters and it returns a text. Maybe you can add an optional parameter for the N bytes you want to retrieve, giving a default value of, maybe, 8.
- This function opens the .git/HEAD file and catches the path to the current code version.
- Then it opens that path to retrieve the hash.
- Then, it returns the N first bytes as a string.
- You can show that N bytes string as the ‘version code’ for your software.
You don’t have to do this by hand, which is a ‘coarse’ method for versioning, and you can retrieve anywhere and anytime, any customer version of the code just by asking him to open the “about”, as long as you have the repository on your laptop or workstation.