Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GIT: how do i do a partial merge from one branch to another one?

Tags:

git

I have commits A-B-C-D on one branch and want to merge A-B-C to another one.

I know that you could do git cherry-pick one by one, and my question is whether I could group these commits together and hopefully do a squash.

like image 512
Vicky Avatar asked Mar 17 '11 18:03

Vicky


People also ask

Can you do a partial merge git?

If only there were a way to do a partial merge instead of a cherry-pick, the problems could have been avoided. It turns out that git does support partial merges.

How do I merge specific branches?

To merge branches locally, use git checkout to switch to the branch you want to merge into. This branch is typically the main branch. Next, use git merge and specify the name of the other branch to bring into this branch. This example merges the jeff/feature1 branch into the main branch.

How do I merge two branches without conflict?

You can do the merge by checking out branch B and having no working changes, then run the following command git merge A . The result will likely require a manual editing of the files to resolve conflicts before doing the final commit.


2 Answers

Like Autocracy said, git rebase is probably what you want.

An example:

Let's say you have A-B-C-D and want to merge A-B-C to Y. Creates a clone of C and rebase the clone onto Y:

git checkout -b C_copy C
git rebase --onto Y A~1 C_copy  # <= --onto [target] [source] [what]

Check if everything went well and resolve conflicts on your way if necessary.

Now you've got C_copy on top of Y, like this: Y-[A_copy]-[B-copy]-C_copy

You could edit that with an interactive rebase e.g. to squash it (assuming you're still on C_copy):

git rebase -i HEAD~3

If something goes awry, you can just throw away C_copy as it does not affect C.

Now you can either fast-forward Y to C_copy or merge it using git merge --no-ff (specify --no-commit to edit your commit if you wish):

git checkout Y
git merge --no-ff [--no-commit] C_copy
like image 174
Arc Avatar answered Oct 30 '22 21:10

Arc


Shouldn't git checkout branch-to-merge-on; git merge tag-or-sha1-of-commit-c work?

The following does as I expect:

git init
touch init; git add init; git commit -m 'init'
git checkout -b abcd
touch a; git add a; git commit -m 'a'
touch b; git add b; git commit -m 'b'
touch c; git add c; git commit -m 'c'; git tag commit-c
touch d; git add d; git commit -m 'd'
git checkout master
touch e; git add e; git commit -m 'e'
git merge commit-c

resulting in

init -- e -- merged   <- (master)
 \           /   
  a -- b -- c -- d    <- (abcd)

This merges everything (up until a common ancestor (init) in this case) before c, but it looks like this is what you want to do. If not, then git rebaseing a-b-c-d elsewhere might be appropriate.

like image 31
wnoise Avatar answered Oct 30 '22 19:10

wnoise