git:如何将一些提交移动到新分支

tak*_*hin 42 git version-control

我一直在直线工作:

A---B---C---D---E---F (master:HEAD)
Run Code Online (Sandbox Code Playgroud)

现在我想向后移动:

git checkout C
Run Code Online (Sandbox Code Playgroud)

并将最后一次提交移至新分支:

选项1:

          D---E---F (new:HEAD)
         /
A---B---C (master)
Run Code Online (Sandbox Code Playgroud)

选项2:

          F (new:HEAD)
         /
A---B---C (master)
Run Code Online (Sandbox Code Playgroud)

如何重新定义选项1以及如何选择2?

Phi*_*ler 70

要从第一个图表(master = HEAD = F)到选项1:

git branch new        # Make a 'new' branch pointing at HEAD, which is F
git reset --hard C    # Move master back to point at C
git checkout new      # Make HEAD follow new, and get F in the working tree
Run Code Online (Sandbox Code Playgroud)

从选项1到选项2(选择上面的位置离开),

git rebase -i master  # Start the process of re-jiggering this branch
# edit the commit list that opens up to only include F
# save and exit
# resolve potential conflicts from missing changes in D and E
Run Code Online (Sandbox Code Playgroud)

直接从您的起点转到选项2:

git checkout -b new C  # Start the 'new' branch at C
git cherry-pick F      # Include F on it
git checkout master    # Switch back to master
git reset --hard C     # Rewind master to the earlier commit
Run Code Online (Sandbox Code Playgroud)

  • 如果您在尝试推送master时遇到错误"更新被拒绝,因为当前分支的提示落后于其远程对应",则需要使用--force选项:`git push --force origin master` (3认同)
  • 谢谢你这个详细的答案. (2认同)