2

I have a master branch, and a develop branch. My production environment uses the master branch, and the develop branch is usually several commits ahead.

I needed to add a quick patch to production. What I would normally do is:

  • git checkout master
  • git checkout -b my-hot-fix
  • (make my hotfix changes, and commit them)
  • git checkout develop
  • git merge my-hot-fix
  • git checkout master
  • git merge my-hot-fix

In this case, I accidentally forget step 1, which means that I was on the develop branch when I created my-hot-fix. I didn't realise this until I got to the last step, and merged the hot fix into master. Instead of getting one small change, I received a number of prior commits from the develop branch.

How do I reverse this? Note that I have not pushed the changes upstream yet.

Note: there are other SO questions about accidental merging. My problem is more than that - it came about because the branch I am merging was created from the wrong branch.

DatsunBing
  • 8,684
  • 17
  • 87
  • 172
  • Refer to this : https://stackoverflow.com/questions/2389361/undo-a-git-merge-that-hasnt-been-pushed-yet – AlexK Nov 21 '18 at 10:22
  • 2
    Possible duplicate of [Undo a Git merge that hasn't been pushed yet](https://stackoverflow.com/questions/2389361/undo-a-git-merge-that-hasnt-been-pushed-yet) – sleske Nov 21 '18 at 10:22
  • Duplicate indeed, we can vote on it – AlexK Nov 21 '18 at 10:25

3 Answers3

2

To get your commit on the right branch :

# in the output of next command, spot the commit you know is good and store its hash ID, let's call it <commit_hash_OK>
git log -10 --oneline master

# in the output of next command, spot the NEW hotfix commit and store its hash ID, let's call it <commit_hash_NEW>
git log -10 --oneline my-hot-fix

# we need to reset master to its previous state
git checkout master
git reset --hard <commit_hash_OK>

# finally, put onto master only the commit you needed
git cherry-pick <commit_hash_NEW>

Then you'll be set on local, just push as usual.

Romain Valeri
  • 19,645
  • 3
  • 36
  • 61
2

Your best bet is to simply reset your changes on both the master and develop to be in sync with the remote. So presuming your remote is called origin:

git checkout master && git reset --hard origin/master

git checkout develop && git reset --hard origin/develop

Then you can create a new hotfix branch from master this time and git cherry-pick the commit you want like so:

Find the commit hash:

git log my-hot-fix

Then:

git cherry-pick MY_COMMIT_HASH

Then you can continue from step 4 (git checkout develop) onwards.

You're fortunate in that you haven't pushed yet. You might want to look at the git reflog command also if you're ever stuck and want to revert local changes. It's really powerful! https://git-scm.com/docs/git-reflog

1

If changes are not pushed, you can cancel the commit with git reset command

veben
  • 19,637
  • 14
  • 60
  • 80