【问题标题】:How to merge to another branch with only two commits and with one commit squashed?如何合并到另一个只有两个提交并且一个提交被压缩的分支?
【发布时间】:2017-08-09 23:00:56
【问题描述】:

我创建了一个开发分支,它有一些无用的提交。现在我想将提交合并到主线分支。我想要在 origin/master 分支中的唯一提交是最新提交和另一个将第一个提交压缩到第二个最新提交的提交。

编辑: 对不起,如果这不清楚,所以让我试着让它更清楚。假设我在 dev 分支中有 5 个提交。我想将 dev 分支中所做的所有更改合并到 origin/master 分支。问题是我想将提交 #1-4 压缩为一个提交并将该提交和提交 #5 合并到 origin/master 分支。

【问题讨论】:

    标签: git merge git-merge git-squash


    【解决方案1】:

    根据该分支上的提交数量,尤其是那些您想要摆脱的“无用”提交,您可以执行交互式 rebase 以摆脱那些您不想要的提交,或者您可以简单地挑选你真正想要保留的两个:

    # check out master and update it first
    git checkout master
    git merge origin/master
    
    # cherry-pick the latest commit from the development branch
    git cherry-pick dev-branch
    
    # cherry-pick the other commit (use the hash from the log)
    git cherry-pick theothercommitshash
    

    之后,您将这两个提交干净地放在 master 之上,您可以使用软重置或交互式变基来压缩它们。

    问题是我想将提交 #1-4 压缩为一个提交并将该提交和提交 #5 合并到 origin/master 分支。

    这实际上是交互式变基的完美用例。

    从 dev 分支开始并运行 git rebase -i dev~5 以启动编辑器,其中包含最近 5 次提交的交互式变基计划。它应该是这样的:

    pick <hash1> Commit 1
    pick <hash2> Commit 2
    pick <hash3> Commit 3
    pick <hash4> Commit 4
    pick <hash5> Commit 5
    

    把里面的三个pick改成squash这样看起来像这样:

    pick <hash1> Commit 1
    squash <hash2> Commit 2
    squash <hash3> Commit 3
    squash <hash4> Commit 4
    pick <hash5> Commit 5
    

    squash 基本上意味着“接受提交,但将其融合到前一个中”。所以在这种情况下,提交 1 被按原样选择,然后提交 2、3 和 4 都被一个接一个地压入其中。因此,您最终会得到一个包含所有 4 个提交的更改的提交。

    保存计划并退出编辑器以启动交互式变基,并在 Git 提示您执行此操作时调整压缩提交的提交消息。最终,您将在分支上只得到两个提交:压扁的提交,以及在此基础上重新构建的提交 5。

    最后,你可以将分支合并到 master 中,你就完成了。

    【讨论】:

    • 在我签出 master 并更新它之后,我是否能够压缩前 4 个提交(在我添加的示例中提到)?如果是这样,你能告诉我我会怎么做吗?抱歉,我对 git 还很陌生。
    • @lezzago 更新了关于您的更新的答案。
    【解决方案2】:

    如果您不想将临时分支中的所有更改合并到 master 中,您可以使用 git cherry-pick:

    git checkout master
    # Create a new commit in branch master which is equal to the latest
    # commit in my_dev_branch
    git cherry-pick my_dev_branch
    

    如果您想从my_dev_branch 中挑选两个提交并将它们压缩为master 中的单个提交,那么您需要--no-commit

    git checkout master
    git cherry-pick --no-commit <some-commit>
    git cherry-pick --no-commit <another-commit>
    # Now that all changes are in index, create a new commit
    git commit
    

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 2011-07-15
      • 2018-03-12
      • 2021-11-14
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 2012-09-13
      相关资源
      最近更新 更多