29 July 2014

Including the hash for the current git-commit in a C program

Say you wrote the following simple C program:
It includes a file "githash.h" that would contain the hash for the current commit in Git:

#include <stdio.h>
#include "githash.h"
int main(int argc,char** argv)
{
return fputs("Git-Version:" GIT_HASH "\n",stdout)==0;
}
view raw test.c hosted with ❤ by GitHub


Because you're working with a Makefile, the file "githash.h" is generated by invoking 'git rev-parse HEAD ':

a.out: test.c githash.h
gcc $<
githash.h:
echo -n '#ifndef GIT_HASH\n#define GIT_HASH "' > $@ && \
git rev-parse HEAD | tr -d "\n" >> $@ && \
echo '"\n#endif' >> $@
view raw Makefile hosted with ❤ by GitHub


the file "githash.h" loooks like this:


#ifndef GIT_HASH
#define GIT_HASH "f2607d7e246549d9ea54922a87001459c0235486"
#endif
view raw githash.h hosted with ❤ by GitHub


But WAIT that is not so simple, once the file 'githash.h' has been created it won't be updated by Make as it already exists. This file should be removed each time 'git commit' is invoked. We can do this by creating POST COMMIT git hook: we create a bash script named ".git/hooks/post-commit" removing 'githash.h:

#!/bin/sh
rm -f githash.h
view raw post-commit hosted with ❤ by GitHub


don't forget make it executable: `chmod +x .git/hooks/post-commit`

Now, each time 'git commit' is called, the file githash.h for the previous git-commit will be deleted !


That's it,

Pierre








2 comments:

István Albert said...

The risk seems to be that if someone commits a second time without running make they could end up removing githash.h from the repository.

Perhaps a better solution would be to have a third file that githash.h depends on, a file that is touched by the post commit hook so that on the next make the file is recreated.

Jamie Bullock said...

Why?