Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git: I accidentally merged feature branch into master instead of develop

I'm using git and working with master/develop/feature branches.

The master only had the README file. And, unfortunately, I accidentally merged the feature branch I was working into the master instead the develop branch. And also removed the feature branch.

I know little about git and I'm confused about what to do. But I think the right thing is to merge the changes on the feature branch (already removed) into develop and revert the merge into the master. But how to do that if I already removed the feature branch?

like image 492
Rafael P. Miranda Avatar asked Nov 06 '17 14:11

Rafael P. Miranda


People also ask

How do I undo a merge master into a branch?

You can undo a Git merge using the git reset –merge command. This command changes all files that are different between your current repository and a particular commit. There is no “git undo merge” command but the git reset command works well to undo a merge.

How do I revert a merge in git?

You can use the Git reset command to undo a merge. Firstly, you need to check for the commit hash (or id) so you can use it to go back to the previous commit. To check for the hash, run git log or git reflog . git reflog is a better option because things are more readable with it.

Should you merge master back into develop?

Once you merge develop to master then both are already in sync with each other so there is no need to merge again master into develop.


1 Answers

Note that I'm assuming here that you haven't pushed the results of the merge. If you have, this still can work, but would require a "force push" which in turn impacts everyone else using the repo (see "recovering from upstream rebase" in the git rebase docs; as that's essentially the situation it would create). But if you haven't, you don't need to worry about any of that. So:

First thing is to recreate the feature branch. I'm assuming it only ever existed locally. (If it had been pushed before the merge, you might be able to recover it from the remote; but either way the approach below will work.) So

git checkout master
git checkout -b feature
git reset --hard HEAD^2

Now the feature branch is restored to the merge commit's "second parent" - which should be where it was before the merge.

Next you need to remove the merge from master.

git checkout master
git reset --hard HEAD^

And that's it; you're ready to merge the feature into the development branch.

like image 152
Mark Adelsberger Avatar answered Oct 06 '22 09:10

Mark Adelsberger