Search code examples
gitgit-rebasegit-cherry-pick

Is there sort of a reverse cherry-pick in Git?


tl;dr: How can I keep the current last couple of commits on a branch, and replace the history before that with that of another branch?


I have a branch where I want to keep the existing last 3 commits but replace the history with that of another branch.

So I have:

        E-F-G   :: my-branch
       /
A-B-C-D   :: main
  \
   B'-C'-D'     :: new-past

and I want

A-B-C-D         :: main
 \
  B'-C'-D'      :: new-past
         \
          E-F-G :: my-branch

Currently I am doing this manually

git checkout new-past
git pull
git checkout -b my-branch-temp
git checkout cherry-pick E
git checkout cherry-pick F
git checkout cherry-pick G
git branch -D my-branch
git branch -m my-branch

So is there some opposite of cherry-pick where you can insert the past commit or something or some flag on merge or rebase that would make this more elegant?


PS- The case here is I am on a child branch of another branch that is getting regularly rebased and I'm trying to avoid having merge commits.

PPS- I'd just as soon script the existing process were there not frequent conflicts that need to be resolved


Solution

  • Thanks to @Hasturkun for pointing me towards rebase --onto which led me to Git rebase --onto an overview & How change parent branch in git?

    So for the example in the question the answer is:

    git rebase --onto D' D my-branch