Question

I have the following situation in my git repository at the moment.

HEAD -- 0 -- 1 -- ... -- 3 -- 5 master
         \-- 2 -- ... -- 4 --/  branch-1

The branch "branch-1" has been forked from the master some time ago (see commit 5).

At commit 0 I wanted to merge it back to master but all changes that had happened in master between commits 1 and 3 were overwritten. Effectively creating

0 -- 2 -- ... -- 4 -- 5 master

Since my colleagues could not continue their work on this state I have reverted the merge commit. Thus I did set HEAD to be the same as 1. The command used would be "git revert -m 2 0".

But now I would like my changes merged back in again. This time I hope it will be successful. I need to create something like:

-2 -- HEAD -- 0 -- 1 -- ... -- 3 -- 5 master
  \            \-- 2 -- ... -- 4 --/
   \--- -1 ------/

This would be a new commit -1 that avoids the failed merge 0 and goes back in at the clean state I had (the clean state I achieved by reverting) prior to the merge.

However just trying to merge 2 to HEAD does not work. I think this is because they are already merged at 0.

Was it helpful?

Solution

The problem is that you used git revert instead of git reset --HARD. git revert creates a new commit that redoes the changes of the previous commit. git reset does the same, but not by creating a new commit, but by throwing away the faulty commit. Because of that the faulty commit still sits in your history.

Merging 2 to HEAD doesnt work, because you are trying to merge with your own history. It is like trying to merge 4 into 2.

What you need to do is, throw away 0 and make a new one.

First, reset master back to 1 using:

git reset --HARD 1

Then, reach a clean, merge-ready state there (you can do commits if you need to).

After that, make sure branch-1 points to 2:

git checkout branch-1
git reset --HARD 2

Reach a clean, merge-ready state there too. Then, merge them both:

git checkout master
git merge branch-1

Check the result of the merge. If it didnt work as you want, start over by reseting master and branch-1 again. If you can't get merge working, you might also try a rebase. This will flatten your history to a look like that:

2' -- .. -- 4' -- 1 -- .. -- 3 -- 5

After you merged or rebased the two branches together, you may rebase any changes that were introduced after the reverted commit (Replace 2' with the most current commit of the new merge/rebase you created, dont use HEAD as it will change once the command runs):

git rebase 2' -2

After that, your history should look like that:

-2' -- .. -- 2' -- .. -- 4' -- 1 -- .. -- 3 -- 5

Or, if you merged instead of rebase:

-2' -- .. -- 0' -- 1 -- ... -- 3 -- 5
              \ -- 2 -- ... -- 4 --/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top