Know git hash before committing?

If you are only interesting in predictable references to commits and do not care about the complete hash, you could customize the short hash (first 4 to 8 characters) after making a commit to whatever you like using lucky-commit. This also works on GPG signed commits.

Caveats:

  • The more characters you fix at the beginning, the longer it takes, exponentially longer.
  • It has to be run after each and every commit
  • It will make a duplicate commit for every commit in the local repository. See below example:
% git log --oneline --graph         
* 0000003 (HEAD -> master) Third commit
* 0000002 Second commit
* 0000001 First commit
% git log --oneline --graph --reflog
* 4ef3899 Third commit
| * 0000003 (HEAD -> master) Third commit
|/  
* 0000002 Second commit
| * d756f59 Second commit
|/  
* 0000001 First commit
* a1e6be7 First commit

Finding commit hash before making a commit is possible in theory, but requires in-depth knowledge of git's inner workings and then engineering a solution around it. For a brief overview you can read Git Magic Chapter 8 Secrets Revealed, sections on Blobs, Trees, and Commits.


What possible reason do you have for needing this? If you were thinking of putting the hash of the commit into its own commit message, I'm sorry to tell you but that's impossible (or at least, impossible without breaking SHA1). The commit message is one of the pieces that are used when generating the hash, so any attempt to modify the message would change the hash.

In any case, finding out the hash of the commit before committing is nearly indistinguishable from actually committing, writing down the hash, and then throwing away the commit (as Carl Norum suggested in his comment). The reason is that the hash is generated by making the commit object and passing it through SHA1. So in order to find the hash without committing, you'd have to basically walk through the commit process manually and SHA1 the results, without actually writing the object to disk. And not only is that rather impractical, but it's also completely pointless.


The commit hash is dependent of commit time.

If you make 2 commits with same changes, same parent, same author and commit message within the same second, you will get the same hash. Otherwise, the hash should be different.

Tags:

Hash

Git