Home > Enterprise >  How do I revert a commit that I forgot to squash in git?
How do I revert a commit that I forgot to squash in git?

Time:10-21

I accidentally merged a Pull Request when what I really meant to do was a squash and merge. As a result, my commit history now contains the ~20 individual commits from that PR.

My goal is twofold:

  1. Revert back to the last "good" commit
  2. Clear the "bad" commits from my commit history

Most of these "bad" commits appear AFTER the last "good" commit, but a handful of them appear BEFORE the last "good" commit (I'm guessing this is due to their commit dates), which I'm afraid complicates things for me.

Fortunately, there haven't been any additional commits since this mistake was made.

Based on my research thus far, I can revert back to the last "good" commit by doing the following:

git reset --hard <commit-before-the-merge>

But given that the "bad" commits appear both before AND after the last "good" commit, I'm uncertain this will resolve the issue, and I don't want to try it without being reasonably confident it will work.

Will the command noted above do the trick, or should I be using a different set of commands to get myself out of this mess?

CodePudding user response:

Before or after time-wise shouldn't matter. What matters to Git is the ancestry of commits, which is purely defined through the parent: line in each commit object.

Use git log to check if any invalid commits would be reset:

git log $last_good_commit..$bad_commit

But even if it contains commits which you want to keep, you can always use git cherry-pick to create a new commit with the same patch.

  • Related