xcode
xcode

Reputation: 1717

How to merge or insert certain commit to other branch?

Let say I have following git structure

1--2--3--11--12 (master-branch)
       \
        4--5--6--7--8--9--10--13--14 (custom-branch)

How can I get into the following git structure?

1--2--3--4--11--12 (master-branch)
          \
           5--6--7--8--9--10--13--14 (custom-branch)

Upvotes: 2

Views: 501

Answers (2)

user232548
user232548

Reputation: 487

If these commits have been pushed to remote already, I would just rather merge commit 4 to master.

git checkout master
git merge <4-commit-id-here>

But that is not what you asked for, so what you could do is to cherry-pick the commit you want on master:

git checkout master
git cherry-pick <4-commit-id-here>

Then if these are only local branches or you are perfectly sure you want to be rewriting history also on remote, you can reorder the commits with git rebase interactive:

git rebase -i HEAD~4

Rebase interactive shows you a list of commits which you can reorder.

After reordering the master you have new commit ID for the commit 4. So you need to rebase custom-branch on top of that:

git checkout custom-branch
git rebase <new-commit4-id-here>

Rebase should by default ignore the old commit 4 from custom branch as it does not introduce any new changes on top of new commit 4. So that is it.

If your changes were already on the remote, you need to do force push (assuming here you have tracking for both branches in place).

First push the custom-branch: git push -f

And then push the master branch:

git checkout master
git push -f

But generally rewriting history on remote should be avoided. More on this e.g. in here: How do I properly force a Git push?

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521569

Just rebase master on the custom-branch up to the 4 commit:

git checkout master
git rebase custom-branch~8

By inspection, all you want to do here is to make 1--2--3--4 the new common base of both branches.

Upvotes: 4

Related Questions