【问题标题】:Git replace inbetween commits with another branch commitsGit用另一个分支提交替换中间提交
【发布时间】:2024-01-11 00:25:01
【问题描述】:

想搬东西:

A--B--C--D--E--F--G--H   (master)
      \
       \
        L--M--N--O--P    (feature)

想要删除 D-E-F 提交并替换为 L-M-N-O-P。最终的回购应该是

A--B--C--L--M--N--O--P--G--H  (master)

很遗憾,我的 Git 还不够强大,有什么帮助吗?

【问题讨论】:

    标签: git git-branch git-merge branching-and-merging


    【解决方案1】:

    应该这样做:git rebase F master --onto feature

    这告诉 Git 将 F..master 之间的提交移动到 feature。现在你的仓库看起来像

    A--B--C--D--E--F
           \
            \
             L--M--N--O--P          (feature)
                          \
                           \
                            G--H    (master)
    

    然后只需git branch -d feature 清理旧的feature 分支,Git 的垃圾收集将处理D--E--F

    如需更多详细信息和一些很好的示例图,请通读rebase docs

    【讨论】:

      【解决方案2】:

      您的历史记录如下所示:

      $ git log --oneline  --graph --all
      * 3e680f3 H
      * afd87a5 G
      * 2583117 F
      * 6f44661 E
      * 37ba1cd D
      | * 7c8d70f P
      | * b953a6f O
      | * 7e2f28e N
      | * 95fc381 M
      | * 7ca7fe9 L
      |/
      * c30b405 C
      * 70fad86 B
      * 18aedd7 A
      * c32e786 Initial commit
      

      合并feature 分支

      $ git me feature
      Merge made by the 'recursive' strategy.
       l | 0
       m | 0
       n | 0
       o | 0
       p | 0
       5 files changed, 0 insertions(+), 0 deletions(-)
       create mode 100644 l
       create mode 100644 m
       create mode 100644 n
       create mode 100644 o
       create mode 100644 p
      

      Interactively rebase 你的主人,对我来说c32e786 是初始提交的哈希:

      $ git rebase -i  c32e786
      

      您将看到一个包含提交列表的文本编辑器。删除不需要的提交并重新排序其余的或您想要的:

      $ git log --oneline
      ff6a364 H
      4a9d73c G
      7c8d70f P
      b953a6f O
      7e2f28e N
      95fc381 M
      7ca7fe9 L
      c30b405 C
      70fad86 B
      18aedd7 A
      c32e786 Initial commit
      

      【讨论】: