代码之家  ›  专栏  ›  技术社区  ›  YSC

将一个分支的顶部提交移动到另一个分支

git
  •  0
  • YSC  · 技术社区  · 7 年前

    假设我想离开

                        branch1 <- HEAD
                        ↓
    A -- B -- C -- D -- E
         ↑
         branch2
    

              branch1
              ↓
    A -- B -- C
          \-- D' -- E'
                    ↑
                    branch2 <- HED
    

    当我在一个分支中提交而我本应提交给另一个分支时,可能会发生这种情况。我还没推那两个树枝,所以我可以把它们移走 D E 从提交 branch1 branch2 .

    如何将提交从一个分支移动到另一个分支?

    一种可能是摘樱桃然后用力移动 branche1 后面,但这很难看:

    git checkout branch2
    git cherry-pick D E
    git branch -f branch1 C
    

    应该有一个回扣可能。

    3 回复  |  直到 7 年前
        1
  •  1
  •   bimlas    7 年前

    这正是 rebase --onto :您可以在任何提交的基础上重新设置分支。基本语法是:

    git rebase --onto new_base old_base branch
    

    在你的情况下你必须搬家 branch2 第一到 branch1 :

    git checkout branch2
    git reset --hard branch1
    

    然后移动 鳃2 到顶端 B :

    git rebase --onto B C branch2
    

    在这之后,你有行动 小精灵 回到 C :

    git checkout branch1
    git reset --hard C
    

    详细示例:

    命令行参数 --onto 可以传递给git rebase。在Git中 重碱 --上 命令扩展到的模式:

    git rebase --onto  
    

    这个 --上 命令启用更强大的窗体或rebase,允许 传递特定的ref作为rebase的提示。

    假设我们有一个带有如下分支的示例repo:

    o---o---o---o---o master
                     \
                      o---o---o---o---o featureA
                       \
                        o---o---o featureB
    

    featureB 基于 featureA 但是,我们意识到 小精灵 不是 依赖于羽毛尿素的任何变化 master .

    git rebase --onto master featureA featureB
    

    特技 <oldbase> . 主人 成为 <newbase> 特技B 是什么的参考 HEAD <纽伯特公司; 将指向。结果是 然后:

                      o---o---o featureB
                     /
    o---o---o---o---o master
                     \
                      o---o---o---o---o featureA
    

    (从 Atlassian Git Tutorial 寻找 --上 )

        2
  •  0
  •   Sergio Lema    7 年前

    您可以使用Rebase Interactive: git checkout branch1 git rebase branch2 -i HEAD~2

    来源: https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History

    然后,提交按您所需的顺序进行。如果你想把树枝移到你的目标上,你必须强迫它们( git branch -f {branch-name} {postition} )

        3
  •  0
  •   axiac    7 年前

    首先,确保没有未提交的更改。要么把他们放在其他事情之前。

    然后创建一个临时分支或一个指向提交的标记 E . 如果出了什么问题,你可以用它来恢复位置 branch1 重新开始。达到所需结果后,可以移除分支或标记。

    您可以通过以下方式实现所需的结构:

    # Make branch `branch2` point to commit `E`
    git checkout branch2
    git rebase branch1
    # Move `branch1` onto its desired destination (2 commits behind its current position)
    git checkout branch1
    git reset --hard HEAD~2
    # Get back to branch2
    git checkout branch2
    # Rebase its most recent 2 commits (D and E) on top of B
    git rebase --onto HEAD~3 HEAD~2
    

    或者,您可以将最后一个命令改写为 git rebase --onto branch1~1 branch1 .

    它移动可从当前分支访问的提交( branch2 那就是承诺 e )但无法从分支访问 小精灵 在承诺之上 branch1~1 (父母 鳃1 )这样,历史线从 鳃1 (除外) 小精灵 )作为兄弟姐妹被感动 鳃1 (或在任何地方 --onto 说)

    阅读 documentation of git rebase 有关如何 GIT重碱 作品。