git - 如何撤消提交并将更改提交到 Git 中的另一个分支?

标签 git version-control branch

我在git中常犯的错误是

  1. 不检查我在哪个分支
  2. 将更改提交到错误的分支(在分支 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~1first_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/

相关文章:

git - 以不同的名称获取 Git 分支

git - 在不更改工作区文件的情况下切换到另一个分支

git - 集中式 GIT 工作流/部署 - 发布分支

git - 是否有一个简单的解决方案可以将软件的不同分支导入到新的 git 存储库中?

git - 如果只有受信任的用户具有 SSH 访问权限,远程 git 客户端是否容易受到 CVE-2014-9390 的攻击?

git - 我可以在不先从原点调用 fetch 的情况下 rebase 吗?

git - 是否有可能获得 diff3 merge 冲突或 libgit2 中的复合 diff 的行的起源?

git - 为什么 `git checkout -` 在 Makefile 中的工作方式不同?

version-control - 您可以为您在 P4V 中创建的自定义工具分配快捷方式吗

version-control - 来自 MPLAB 的 Mercurial : what are the very first steps?