How to move commits in a branch to another new branch in GIT?

廉价感情. 提交于 2019-12-12 11:35:49

问题


I have develop git branch for my work, I created a new branch called feature1 and made commit 1,2,3, and 4.

I need to move commit 3,4 from feature1 branch to a new created branch feature2.

The commits 3,4 should be deleted from feature1 and added to a new branch feature2, so the end result should be something like feature1 with 1, and 2 branches and feature2 with 3 and 4.

Please note that at the moment I have develop and feature1 branches. feature2 not added yet.

What is the best way to achieve that? I tried git cherry-pick but wanna make sure the best way to do that.


回答1:


If I understand your description correctly, your repo currently looks like this,

... -- o [develop]
        \ 
         1 -- 2 -- 3 -- 4 [feature1]

and you want it to look like that

         3'-- 4'[feature2]
        /
... -- o [develop]
        \
         1 -- 2 [feature1]

Correct? If so, do the following.

First, make sure you're in a clean working state. Then, create and check out a branch called feature2 that points at the same commit as develop:

git checkout -b feature2 develop

Your repo will look as follows.

... -- o [HEAD=feature2,develop]
        \ 
         1 -- 2 -- 3 -- 4 [feature1]

Cherry-pick the two commits of interest (3 and 4):

git cherry-pick <commit-ID-of-3> <commit-ID-of-4>

After that, Your repo will look as follows.

         3'-- 4'[HEAD=feature2]
        /
... -- o [develop]
        \ 
         1 -- 2 -- 3 -- 4 [feature1]

Finally, check out your feature1 branch and reset it two commits back:

git checkout feature1
git reset --hard HEAD~2

Your repo will end up as desired,

         3'-- 4'[feature2]
        /
... -- o [develop]
        \
         1 -- 2 [HEAD=feature1]

and you'll be in a clean working state.



来源:https://stackoverflow.com/questions/26023761/how-to-move-commits-in-a-branch-to-another-new-branch-in-git

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!