Search code examples
gitversionsha

Can git SHA be displayed as part of a software version for an electronic device


I would like to use and display a fairly standard semantic versioning MM.mm.bb = (M)ajor.(m)inor.(b)uild, but ideally I would like something computer generated, because I don't want to auto-increment the build number due to a peculiarity with this device.

I was thinking of trying to include the git SHA, but of course the SHA is not output until you form a commit.

Is it possible/reasonable to include the SHA in a software build version (for example: MM.mm.bb-f9a8e8)?

Given that I don't want to auto-increment build number and don't particularly want to add an additional SHA calculation other than the git one, Is there a better way to do this?


Solution

  • As I pointed out in the comments, Linux kernel does the trick. The main part there is the setlocalversion script, the core part of which is (detailed explanations are given inside the original script, below are only crucial parts)

        if test -z "$(git rev-parse --show-cdup 2>/dev/null)" &&
           head=$(git rev-parse --verify --short HEAD 2>/dev/null); then
                if [ -z "$(git describe --exact-match 2>/dev/null)" ]; then
                        printf '%s%s' -g $head
                fi
    
                if {
                        git --no-optional-locks status -uno --porcelain 2>/dev/null ||
                        git diff-index --name-only HEAD
                } | grep -qvE '^(.. )?scripts/package'; then
                        printf '%s' -dirty
                fi
        fi
    

    Now our C file module.c:

    #include <stdio.h>
    
    #include "version.h"
    
    int main(int argc, char *argv[])
    {
        printf("Our version is: %s\n", VERSION);
        return 0;
    }
    

    and Makefile

    VERSION = 0.1
    
    version.h: FORCE
        @echo "$(VERSION)$(shell $(PWD)/setlocalversion $(PWD))"
        @echo "#define VERSION \"$(VERSION)$(shell $(PWD)/setlocalversion $(PWD))\"" > version.h
    
    
    module.o: version.h
    
    all: module
        @$(PWD)/module
    
    clean:
        @rm module module.o version.h
    
    FORCE:
    
    .PHONY: FORCE
    

    Show time:

    $ make all
    0.1-gb6d5c80
    cc    -c -o module.o module.c
    cc   module.o   -o module
    Our version is: 0.1-gb6d5c80