3

I have a couple of branches, and I want the changes from the second branch to appear in the first branch.

It's probably best described with a diagram:

          X - Y - Z    (branch-2)
         /         \
A - B - C - D - E - F  (master)
 \     
  G - H - I            (branch-1)

I want to merge X, Y, Z into branch-1 without bringing B and C.

I tried to cherry-pick merge-commit F, and although I specify the correct parent (I think), the cherry-pick fails with: The previous cherry-pick is now empty, possibly due to conflict resolution.

Should I cherry-pick the X^..Z range? Or is there a better way to do it?

aidan
  • 9,310
  • 8
  • 68
  • 82
  • 1
    Yes I think you're right. You can cherry-pick the three `X`, `Y` and `Z` commits in the right order, and then you can optionally reduce those 3 commits into a single one with a `git rebase -i ~1` command. – jbaptperez Jun 29 '18 at 07:20
  • 1
    I would cherry-pick one by one. Also have a look at this [SO answers](https://stackoverflow.com/questions/7072013/git-cherry-pick-not-working) to understand your error message. – YesThatIsMyName Jun 29 '18 at 07:22
  • 1
    The graph drawing doesn't show which parent is which, but probably you would need `-m 2` rather than the more typical `-m 1`. Your proposed solution (pick `X^..Z`) is probably the best way anyway though. Note that you can use `-n` to combine them in the index as you go, and make one commit at the end, although I'd probably do the interactive rebase squash as well since that means I get to resolve any conflicts as I go, and make sure I did not break anything before squashing. – torek Jun 29 '18 at 08:09

1 Answers1

4

cherrypicking one by one might be a solution if that branch-2 is small.

For larger branches to move I'd do this:

git checkout branch-2
git branch   moving/branch-2 # new branch to work with
git rebase --onto  branch-1 [sha_of_c] moving/branch-2 # move commits of branch ontop of the other 
git checkout branch-1 
git reset --hard  moving/branch-2 # set branch lable to new HEAD
git branch -d  moving/branch-2 # clean up

As suggested by @quetzalcoatl in the comments you might use the -i swithch with rebase so you can check that the right commits are being copied before actually doing that.

On the other Hand if something went wrong you can simply revert moving/branch-2 to branch-2 and start over again.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
  • 3
    just one note - for all people "not feeling safe with rebase", add `-i` to `rebase`. This will display you a list of commits that will be taken, and you can edit (i.e. remove, reorder, etc) the plan beforewards. This is super-handy. I actually rarely use rebase without -i, because I tend to mistake the order of branches for --onto/etc parameters and it's better to check the plan first. – quetzalcoatl Jun 29 '18 at 07:49