How can I populate the Git commit ID into a file when I commit?

The solution I have used for a similar situation is this:

  1. Put the string $Id$ somewhere in the file you want to have identified (e.g. test.html), probably within a comment or other non-functional section of the file where it won’t cause issues.
  2. In your .gitattributes, flag the file in question with the ident keyword (e.g. *.html ident).

The result of this is that when git checkout copies the file out of the object database into your working directory, it expands the $Id$ string to read $Id: <sha-1 of file>$, and git add reverses that transformation when you want to check it in, so the versions of that file in your object database only ever contain $Id$, not the expanded forms.

That’s a start, but unfortunately, finding the commit that contains a file with a specific hash is not so easy, and not necessarily one-to-one either. So, in addition, I also tag those files with the export-subst attribute (e.g. *.html ident export-subst in .gitattributes), and add an additional string, like $Format:%ci$ ($Format:%h$) somewhere in the file as well.

git checkout and git add don’t affect these tags, though, so the versions in my repository always have exactly that string. In order to get those tags expanded, you have to use git archive to create a tar-ball (or .zip) of a specific version of your project, which you then use to deploy that version – you won’t be able to just copy the files, or make install or whatever, since git archive is the only thing that will expand those tags.

The two tags I gave as an example expand to YYYY-MM-DD HH:MM:SS +TZOFFSET (HASH), where the HASH in this case is the actual commit hash, so it’s more useful.

You can find other potentially usefull $Format:$ specifiers in the git log help page under the --pretty-format specifiers.

Leave a Comment