Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

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 possible with Git? Or is the fact that by resolving the variable to the git id, I am going to be changing the sha 1, thereby winding up with a "chicken or the egg" problem.

like image 645
BestPractices Avatar asked May 13 '13 14:05

BestPractices


People also ask

How do you get details of a commit?

`git log` command is used to view the commit history and display the necessary information of the git repository. This command displays the latest git commits information in chronological order, and the last commit will be displayed first.

How do you reference a commit?

To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.


1 Answers

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.

like image 107
twalberg Avatar answered Sep 21 '22 10:09

twalberg