In Git, how can I write the current commit hash to a file in the same commit
I would recommend doing something similar to what you have in mind: placing the SHA1 in an untracked file, generated as part of the build/installation/deployment process. It's obviously easy to do (git rev-parse HEAD > filename
or perhaps git describe [--tags] > filename
), and it avoids doing anything crazy like ending up with a file that's different from what git's tracking.
Your code can then reference this file when it needs the version number, or a build process could incorporate the information into the final product. The latter is actually how git itself gets its version numbers - the build process grabs the version number out of the repo, then builds it into the executable.
It's impossible to write the current commit hash: if you manage to pre-calculate the future commit hash — it will change as soon as you modify any file.
However, there're three options:
- Use a script to increment 'commit id' and include it somewhere. Ugly
- .gitignore the file you're going to store the hash into. Not very handy
- In
pre-commit
, store the previous commit hash :) You don't modify/insert commits in 99.99% cases, so, this WILL work. In the worst case you still can identify the source revision.
I'm working on a hook script, will post it here 'when it's done', but still — earlier than Duke Nukem Forever is released :))
Update: code for .git/hooks/pre-commit
:
#!/usr/bin/env bash
set -e
#=== 'prev-commit' solution by o_O Tync
#commit_hash=$(git rev-parse --verify HEAD)
commit=$(git log -1 --pretty="%H%n%ci") # hash \n date
commit_hash=$(echo "$commit" | head -1)
commit_date=$(echo "$commit" | head -2 | tail -1) # 2010-12-28 05:16:23 +0300
branch_name=$(git symbolic-ref -q HEAD) # http://stackoverflow.com/questions/1593051/#1593487
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD} # 'HEAD' indicates detached HEAD situation
# Write it
echo -e "prev_commit='$commit_hash'\ndate='$commit_date'\nbranch='$branch'\n" > gitcommit.py
Now the only thing we need is a tool that converts prev_commit,branch
pair to a real commit hash :)
I don't know whether this approach can tell merging commits apart. Will check it out soon
This can be achieved by using the filter
attribute in gitattributes. You'd need to provide a smudge
command that inserts the commit id, and a clean
command that removes it, such that the file it's inserted in wouldn't change just because of the commit id.
Thus, the commit id is never stored in the blob of the file; it's just expanded in your working copy. (Actually inserting the commit id into the blob would become an infinitely recursive task. ☺) Anyone who clones this tree would need to set up the attributes for herself.