将Git/SourceTree中分支B的特定提交移动到分支A

4

在开发过程中我遇到了一个问题。我有两个提交需要放到分支A中,但是我却把它们推送到了分支B中。现在,我想把这些提交移动到分支A,并从分支B中删除它们。详细请见图片:

enter image description here

1个回答

6

首先,进入branchAcherry-pick你想要选择的两个提交。

$ git checkout branchA
$ git cherry-pick <commit1>       # commit1 = 0a18e0f   
$ git cherry-pick <commit2>       # commit2 = e604ce4

$ git push origin HEAD            # push to remote

现在通过使用 revertrebasebranchB 中移除两个提交。优先考虑使用 revert,因为它不会改变 Git 历史记录。

Revert:

$ git checkout branchB
$ git revert <commit1>
$ git revert <commit2>
$ git push origin HEAD

Rebase:

$ git checkout branchB
$ git rebase -i efb2443         # go back to the commit before the two commmits you want to remove

Now comment out (adding `#` before the commit hash) the two commits you want to remove.

$ git push -f origin HEAD       # you need to force(-f) push as history is changed here by rebasing

在 cherry-pick<commit>(将代码提交)之后,我需要做其他的事情来推送代码到服务器吗? - lee
1
@lee,与其使用交互式变基(rebase -i)将那两个提交从分支B中删除,不如还原它们。如果有人(或多人)已经拉取了你之前推送到分支B的更改,当你(强制)推送更新后的分支时,你将会改写他们的历史记录。这会给他们带来麻烦,并且违反了git的礼仪准则。 - mattliu
非常感谢您的帮助。 - lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接