I would like to create Git hook(s) that will populate the commit id of the commit I am about to make into a file (basically variable substitution) in my source code. Is this
It's impossible to do what you want: the commit's SHA-1 hash is calculated over the whole repository snapshot including each member file, so there's the chicken and egg problem — to calculate the commit's hash you need to know the contents of all the files which comprise it.
I was looking for an answer to this question. The Commit Id is already written to a file you just have to know where to look. After making a commit on the master branch, you can find the commit hash at
./.git/refs/heads/master
So in our continuous delivery solution (it downloads the .git folder along with the source code) we can simply
cat ./.git/refs/heads/${BRANCH}
in order to associate the current commit hash with our build
The key here is to put your revision ID into some file that Git doesn't care about. Here is a fragment from one of my projects:
. . . AssemblyCS="Properties/AssemblyInfo.cs" rev="$(git log -n 1 --date=short --format=format:"rev.%ad.%h" HEAD)" sed "$AssemblyCS" . . .
This script is run as part of my build process (it could also be a post-commit hook). In this case Properties/AssemblyInfo.cs
is in .gitignore
whereas Properties/AssemblyInfo.cs.in
is under version control. The build uses the .cs
filewhich includes a revision ID that ends up in the deployed executable.