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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "githash.h" | |
int main(int argc,char** argv) | |
{ | |
return fputs("Git-Version:" GIT_HASH "\n",stdout)==0; | |
} |
Because you're working with a Makefile, the file "githash.h" is generated by invoking '
git rev-parse HEAD
':
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' >> $@ |
the file "githash.h" loooks like this:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef GIT_HASH | |
#define GIT_HASH "f2607d7e246549d9ea54922a87001459c0235486" | |
#endif |
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
rm -f githash.h |
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:
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.
Why?
Post a Comment