I am writing a script that requires checking whether a particular commit is a Merge/Revert commit or not, and I am wondering if there is a git trick for that.
What I came up with so far (and I definitely don't want to depend on the commit message here) is to check HASH^2
and see if I don't get an error, is there a better way?
Figuring out if something is a merge is easy. That's all commits with more than one parent. To check for that, you can do, for example
$ git cat-file -p $commit_id
If there's more than one `parent' line in the output, you found a merge.
For reverts it's not as easy. Generally reverts are just normal commits that happen to apply the diff of a previous commit in reverse, effectively removing the changes that commit introduced. They're not special otherwise.
If a revert was created with git revert $commit
, then git usually generates a commit message indication the revert and what commit it reverted. However, it's quite possible to do reverts in other ways, or to just change the commit message of a commit generated by git revert
.
Looking for those generated revert commit message might already be a good enough heuristic for what you're trying to achieve. If not, you'd have to actually look through other commits, comparing their diffs against each other, checking if one is the exact reverse operation of another. But even that isn't a good solution. Often enough reverts are slightly different than just the reverse of the commit they're reverting, for example to accommodate for code changes that happened between the commit and the revert.