53

I want to do something similar to git rebase but without collapsing parallel commits.

Let's say I have the following commits:

  B (bar)
 /
A-C-D (foo)

Now I want to take the changes that D introduced to C in branch foo, and apply them to B in branch bar. so that I end up with the following:

  B-E (bar)
 /
A-C-D (foo)

Where the difference between commits B and E is equal to difference between commits C and D. Is this possible? Is there a way to do it without creating a patch?

t0r0X
  • 4,212
  • 1
  • 38
  • 34
juniper-
  • 6,262
  • 10
  • 37
  • 65

3 Answers3

63

Yes:

git checkout -b mergebranch B
git cherry-pick D
cforbish
  • 8,567
  • 3
  • 28
  • 32
  • 4
    To ellaborate on the answer above: `git checkout -b mergebranch B` creates a new branch called `mergebranch` using branch `B` as the starting point. `git cherry-pick D` applies the changes introduced by the commit at the tip of the branch `D`. – Patrick Apr 17 '19 at 11:57
  • 6
    Cherry-pick without commit command: `git cherry-pick -n ` – Emre Tapcı Jan 13 '22 at 08:52
  • A small clarification to the meaning of `B` above. It refers to a commit hash, in this case the one at the tip of the branch called `bar`, it is not a branch name as it may come across from reading the comment by @Patrick above. This is still the best answer in my humble opinion. – Pablo Adames Mar 13 '23 at 23:06
  • @EmreTapcı That's what I was searching for, as a normal cherry-pick threw an error despite no affected paths being modified in my worktree. It worked with `-n` and I didn't need a commit anyway. – Dennis98 Mar 21 '23 at 16:04
7

In my case I needed to apply the changes of specific commits of another branch. I did that by cherry picking them like so: git cherry-pick COMMIT-HASH.

t0r0X
  • 4,212
  • 1
  • 38
  • 34
Patrick
  • 1,728
  • 2
  • 17
  • 30
2

If the last commit on the branch that you want to cherry-pick out of (foo in the example) is a merge commit, you can point at the specific commit to cherry pick by using git cherry-pick branchname~1 to get the commit which was the parent of the merge.

aaaarrgh
  • 984
  • 1
  • 10
  • 22