@Borealid's answer is correct, but suppose that you don't care about preserving the exact merging history of a branch and just want to cherry-pick a linearized version of it. Here's an easy and safe way to do that:
Starting state: you are on branch X
, and you want to cherry-pick the commits Y..Z
.
git checkout -b tempZ Z
git rebase Y
git checkout -b newX X
git cherry-pick Y..tempZ
git branch -D tempZ
What this does is to create a branch tempZ
based on Z
, but with the history from Y
onward linearized, and then cherry-pick that onto a copy of X
called newX
. (It's safer to do this on a new branch rather than to mutate X
.) Of course there might be conflicts in step 4, which you'll have to resolve in the usual way (cherry-pick
works very much like rebase
in that respect). Finally it deletes the temporary tempZ
branch.
If step 2 gives the message "Current branch tempZ is up to date", then Y..Z
was already linear, so just ignore that message and proceed with steps 3 onward.
Then review newX
and see whether that did what you wanted.
(Note: this is not the same as a simple git rebase X
when on branch Z
, because it doesn't depend in any way on the relationship between X
and Y
; there may be commits between the common ancestor and Y
that you didn't want.)