githashgit-revert

Will a git commit have the same hash after reverting previous commit?


Will a commit in the git history have the same hash after getting into the same state? For example after revert?

It is possible that there are more commits for one hash?

Let us suppose history

commit number 1: hash 1111
commit number 2; hash 2222
commit number 3(revert of 2), hash 3333 or 1111?

I know that there is quite similar question Can you get a duplicate hash in Git in any way and what are the implications, but it does not answer my question.


Solution

  • No, if you create a new revert commit (while ending up at same state), it will have a new hash.

    This is because the commit hash is not only dependent on the file state and commit metadata (like date), but also on any commit that is an ancestor, i.e., any commit that can be reached by continuously following the parent commit(s). Since commit 3 and commit 1 have different ancestors (one has 2 as an ancestor, the other doesn't), it gets a new hash.


    On a related note, every object in git gets a hash; commits, trees (directories), blobs (files) and tags. The tree you create by reverting commit 3 will have the same hash as the tree commit 1 points to because trees only depend on their contents. They don't track their history. This is only done by the commits that point to the trees. You can find out the tree hash for a particular commit via

    $ git cat-file -p <commit-hash>