如何只用两个提交和一个提交压缩合并到另一个分支?

时间:2017-08-09 23:00:56

标签: git merge git-merge git-squash

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

编辑: 对不起,如果不清楚,那么让我试着让它更清楚。让我们说我在开发分支中有5个提交。我想将dev分支中完成的所有更改合并到origin / master分支。问题是我想将提交#1-4压缩成一个提交并合并提交并将#5提交到origin / master分支。

2 个答案:

答案 0 :(得分:4)

根据该分支上的提交数量,特别是那些你想要摆脱的“无用”提交,你可以做一个交互式的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之上干净地完成这两项提交,然后您可以使用软重置或交互式rebase来压缩它们。

  

问题是我想将提交#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个更改。

最后,您可以将分支合并为主分区,然后就完成了。

答案 1 :(得分:0)

如果您不想将临时分支中的所有更改合并到母版中,则可以使用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