christophmegusta
christophmegusta

Reputation: 53

how to get git hash of current / aka next commit (not head)

i would like to save the current git hash into a file of my repo like this:

echo `git rev-parse HEAD` > VERSION
git add VERSION
git commit -m 'updated version'
git push

the problem, the HEAD is not the hash of the to be commited revision but that of the working revision (which is one revision previous). so if i do like above i always have the hash of the prev commit and not the latest.

can i get before commiting the revision of the hash number the commit will have?

Upvotes: 3

Views: 2240

Answers (1)

mmlr
mmlr

Reputation: 2165

The commit hash is a hash of the commit object, which contains various fields like the commit author, committer, dates, parent commit hashes and the tree hash. The tree hash is a hash of all the content in that tree, i.e. across all hashes of all files and their metadata like mode and name.

Modifying a file (VERSION in the given example), will therefore modify the tree hash and, because the tree hash is part of the hashed content of the commit object, also the commit hash.

Precalculating a hash so that it will produce a matching commit hash after that hash is recorded to a file and changes the tree/commit hashes is theoretically possible, but in practice not feasible. It would basically mean to produce hash collisions for every commit.

That being said, if it is enough to only record a short hash, i.e. a reasonably unique prefix like the 7 character hashes many git commands and user interfaces will show, this can be made to work. There are projects like git-vanity that will brute force a small modification to the commit object to produce a desired prefix of a certain length.

In short, it isn't possible to get the "next" commit hash, because there is no "next" commit hash, it is generated based on all the information contained and referenced by that commit.

Upvotes: 6

Related Questions