Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...