Moving selected git commits to other branches in Visual Studio

2.8k views Asked by At

I develop many project which are very similar - using the same base features. My scenario assume, that I have the basic branch e.g. 'master', then I create from 'master' new branches e.g. 'project1-dev', 'project2-dev' - Created branches are developed seperately, but sometimes I would like to add new feature for project1-dev, then moving this feature to 'master', and then merge with 'project2-dev'. In Visual Studio 2015 I can use 'Rebase', but it also moving changes added before add new feature. enter image description here

Is there any way to moving selected commit from 'project1-dev' to 'master', and then merge with 'project2-dev' ?

2

There are 2 answers

0
ivan.sim On

You can easily merge your new feature from project1-dev to both master and project2-dev by keeping that work in a new branch created from the best common ancestors of all three branches. This is where git-merge-base will come in handy.

Using this command (notice the usage of the back-ticks):

$ git checkout -b new_feature_branch `git merge-base master project1-dev project2-dev`

you will end up with a new branch named new_feature_branch, whose HEAD is set to the common ancestor of master, project1-dev and project2-dev.

(If you run just $ git merge-base master project1-dev project2-dev, you will get the commit SHA of the common ancestor of those three branches.)

This new branch is where you will do your new feature work. When completed, you can merge it back to all the three branches without merging other unwanted works into master and project2-dev.

$ cd new_feature_branch
$ # do some work and commit 
$ git checkout master
$ git merge --no-ff <new_feature_branch> # merge new feature into master
$ git checkout project1-dev
$ git merge --no-ff <new_feature_branch> # merge new feature into project1-dev
$ git checkout project2-dev
$ git merge --no-ff <new_feature_branch> # merge new feature into project2-dev
0
David Deutsch On

First off, since you are using rebase in the first place I am assuming that you have not pushed any of the changes you are going to move yet, or that you are the only one on the project and will do a git push -f, etc.

Anyway, let's say you want to move just a few commits from project1-dev to master, but only as far back as commit A, but as far forward as the head of project1-dev. Do the following:

git checkout project1-dev -b new_master   #create branch new_master at project1-dev
git rebase --onto master A^ new_master    #"Moves" A through new_master onto master
git checkout project1-dev
git reset --hard A^                       #moves project1-dev backwards to A's parent
git checkout master
git merge new_master                      #moves master forwards to where it should be
git branch -d new_master                  #deletes temp branch