Revert Unknown Git Commits

Rewriting the past to subtract from the present.


Here's the deal. You've done a big refactor of a codebase that moved a bunch of files (actually renamed in version control terms), and you find that you want to revert something from the before-times. I did this recently at work and found that if I tried to directly revert the offending commit on HEAD, git would stage an undo of the refactor.

From the git man page:

        git-revert(1) is about making a new commit that reverts the changes made by other commits.
    

This means that git revert will attempt to apply the inverse of any patch wrapped in a commit, regardless of whether it appears on the current branch.

This allows us to do some fun stuff. Lets assume we have the following commits:

  1. Previous changes
  2. Substantial change (to be reverted)
  3. Big refactor
  4. Other changes

My solution was to check out (1), cherry-pick (3) followed by (2) to apply the "substantial" commit on top of "refactor". To my delight this applied cleanly. I then copied the hash of this commit, reset back to origin/master, and reverted that. I have no idea why this worked when directly reverting (2) on the tip of master didn't work, but it did.

—James
16 July 2023