5个提交到错误的分支并推送到远程/原点

时间:2017-08-25 04:23:49

标签: git github

所以我不小心做了5次提交分支" A",但我打算将它分支到" B"。我还将所有提交推送到远程/原点。我意识到我已将所有提交到错误的分支。有什么方法可以将所有这5个提交转移到分支" B"并使我的分支" A"因为它是5次提交之前?

1 个答案:

答案 0 :(得分:7)

结帐至A。将5个提交哈希值按顺序复制并粘贴到任何地方。

e.g。 5(最老的) - > 4 - > 3 - > 2 - > 1(最新),假设1是git log命令的最高提交。

$ git checkout A
$ git log
# copy the 5 commit hashes

结帐到B并将( cherry-pick )5次提交到B分支。

$ git checkout B

$ git cherry-pick <commit-hash>
# repeat 5 times with new commit hash each time (old to new)

# Or, you can cherry-pick a range of commits by 'git cherry-pick <from-commit>^..<to-commit>', note '^' sign
$ git cherry-pick <commit-5>^..<commit-1>  

现在,撤消(hard reset)来自A的最新5次提交。注意,硬重置会改变你的A的git历史记录(如果有其他人已经在本地拉了一个分支,那么你可以使用revert代替hard reset)。因此,需要强制推送分支A

$ git checkout A
$ git branch A.bac           # backup branch 'A' for safety 

$ git reset --hard HEAD~5    # undo last 5 commits from branch A
$ git push -f origin HEAD    # need force push since history is changed

注意:采摘一系列提交的基本形式是:

$ git cherry-pick abc1234..def5678

abc1234是最早的提交,def5678是最新的提交。 abc1234未包含在提交中,但包含def5678。如果您想要包含abc1234,请在abc1234之后^之后设置abc1234的上一次提交范围:

$ git cherry-pick abc1234^..def5678
相关问题