我在git中常犯的错误是
- 不检查我在哪个分支
- 将更改提交到错误的分支(在分支 B 上,以为我在 A 上,提交对功能 A 的更改)
我如何返回并将编辑提交到正确的分支?
最佳答案
rebase --onto
在这里可以提供帮助,尤其是当您有一系列提交要移回时。
不要忘记 git stash
来保存与“wrongBranch
”(正确应用提交的那个)相关的任何当前未提交的更改,以便 pop 他们在流程结束时返回。
基本上,您需要应用一个提交或一系列提交 to another branch (此处称为“rightBranch
”):
# Checkout the right branch where the commit should have been applied
git checkout rightBranch
# Checkout a new temporary branch at the current location
git checkout -b tmp
# Move the rightBranch branch to the head of patchset which should have been on rightBranch
git branch -f rightBranch last_SHA-1_of_commits_for_rightBranch
# Rebase the patchset onto tmp, the old location of rightBranch
git rebase --onto tmp first_SHA-1_of_commits_for_rightBranch~1 rightBranch
(first_SHA-1_of_commits_for_rightBranch~1
是 first_SHA-1_of_commits_for_rightBranch
的父提交,即其上所有 rightBranch 提交都被错误应用的提交)
rightBranch
将再次位于顶部:
- 右分支的所有旧提交(由
tmp
分支指向) - 加上所有相关的提交范围从
wrongBranch
,它们刚刚在tmp
之上重播(tmp
是之前的rightBranch HEAD
).
然后您可以将 wrongBranch
重置为之前的一些提交。
git checkout wrongBranch
git reset --hard some_older_commit
# if needed, re-apply what you were working on vefore this all proccess
git stash pop
警告:
- 择优或 rebase --onto 会产生后果(参见 this question)
- 如果
wrongBranch
已经发布(推送到公共(public)仓库),对于 pull 该仓库的人来说可能会很尴尬(必须将他们所有的更改重新设置在那个"new"分支之上)
关于git - 如何撤消提交并将更改提交到 Git 中的另一个分支?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2100851/