Search code examples
gitgit-mergegit-rebasegit-cherry-pick

Merge features in Git in another branch?


We use branches for features which we then merge into master. We also use branches for versions. However, I have a particular feature (merged into master) that needs to go into the version branch. Previously, I had been using cherry-pick for this (manually plucking commits one at a time), but this feature has too many commits to do one at a time. Is there a better way?

This feature has already been merged into master. The branch does not exist locally anymore. However, I do have the commit which resulted from merging it into master.

I am able to restore feature-branch (since we use GitHub). However, from the version branch, when I run git merge feature-branch, I get all sorts of conflicts unrelated to the feature. Same thing happens if I do git rebase feature-branch (from the version-branch).


Solution

  • Your history might look something like this:

    *--*--X--Y---------------* [master]
        \     \             /
         \     *--*--*--*--A [formerly feature-branch]
          \
           *--*--* [version-branch]
    

    The easy part is getting feature-branch back; just figure out the commit hash A and do:

    git checkout -b feature-branch A
    

    However, if version-branch branched off of master before feature-branch did (as shown above), you don't want to do a straight git merge or git rebase, because that will also bring in commits X and Y. Instead, do an --onto rebase:

    git rebase --onto version-branch Y feature-branch
    

    To make it easier to find Y, you can do:

    git merge-base master feature-branch
    

    Or all in one command:

    git rebase --onto version-branch $(git merge-base master feature-branch) feature-branch
    

    After the rebase is complete, you can merge into version-branch as usual.


    If you get any merge conflicts during the rebase (or if version-branch branched off master at or after feature-branch did and you are still getting conflicts), then you will have to deal with them, because that means the conflicts are between the commits in feature-branch and the commits in version-branch.