代码之家  ›  专栏  ›  技术社区  ›  culebrón

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

  •  4
  • culebrón  · 技术社区  · 16 年前

    我在Git犯的常见错误是

    1. 不查我在哪家分店
    2. 将更改提交到错误的分支(在分支B上,认为我在A上,提交对功能A的更改)

    如何返回并将编辑提交到正确的分支?

    3 回复  |  直到 15 年前
        1
  •  4
  •   Community Mohan Dere    9 年前

    rebase --onto 可以在这里提供帮助,特别是当您有一系列的承诺要移回时。

    别忘了 git stash 保存与“相关的任何当前未提交的更改” wrongBranch “(适当地应用了承诺的情况),以便在流程结束时将其弹出。

    基本上,您需要应用一个提交或一系列提交 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的提交都被错误应用的提交)

    右分支 将再次出现在:

    • 所有右分支的旧承诺(由 tmp 分支机构)
    • 加上所有相关的承诺 错误分支 ,在 川芎嗪 ( TMP公司 是上一个 rightBranch HEAD )

    然后你可以重置 错误分支 以前的一些承诺。

    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
    

    Caveat:

    • 樱桃采摘或再烘焙——产生后果(见 this question )
    • 如果 错误分支 已经发布(推送至公开回购),这对拉动回购的人来说可能很难(必须在“新”分支的基础上重新平衡其所有更改)
        2
  •  0
  •   Kzqai    15 年前

    简单的答案?

    git checkout branch_with_wrong_tip
    git reset HEAD~1 (or whatever number of commits you want to go back)
    git checkout correct_branch
    git commit ...etc
    

    注意重要的部分,即软重置(保留更改),而不是任何硬重置,这可能会让您失去更改的位置。

    这还将把您重置的所有提交都转换回更改,然后您必须单独或作为一个组重新提交这些更改。例如,如果您重新设置头10,则必须对10个提交中提交的所有文件进行提交,否则将它们合并为一个全新的提交。当然,如果你使用这种方法的话。

        3
  •  0
  •   dseminara    15 年前

    签出提交所在的错误分支

    git checkout wrong_branch
    

    在错误的分支中,重置为上一个提交:

    git reset --hard HEAD^
    

    注意:指示上一次提交的^运算符,若要删除多个提交,请使用~n,其中n是提交数。

    签出到提交应该位于的分支

    git checkout right_branch
    

    使用cherry pick重新应用提交

    git cherry-pick wrong_branch@{1}
    

    注意:错误分支@1是错误分支的最后一次提交 之前 执行了git reset命令,例如,head@2在这种情况下也可以使用

    要移动多个提交,可以使用对Git Cherry Pick的多个调用或仅执行一次Git Rebase:

    git rebase --onto right_branch wrong_branch@{1}~N wrong_branch@{1}
    

    (在这种情况下,要重置的相应参数为head~n)