有时,您可能不想使用交互式 Rebase
如果 A 到 X 之间的中间提交数量相对较小,那么您可以使用交互式变基:
git rebase -i origin/master
然而,根据我个人的经验,在大量提交上使用交互式变基是很慢的。我一次对大约一百个提交运行了交互式变基(在使用 Git Bash 的 Windows 机器上),msysgit 花了很长时间才生成交互式变基提交编辑器,该编辑器允许您选择要运行的操作在哪个提交上,因为,嗯,列表最终变得非常大。
在这种情况下,您有几种解决方法。
替代方案#1:git reset
混合重置和软重置可用于(分别)修改工作树或暂存区域,以聚合/收集两个提交 A 和 Y 之间的所有更改,之后您可以将所有修改作为单个提交一次提交。
我只会给出一个软重置的示例,因为它已经为您保留了所有内容,而如果您使用混合重置,则无论如何都必须进行修改:
# You don't need to create the temp branch A if you
# copy the commit sha A down somewhere so that you can remember it.
git branch temp A
git reset --soft Y
git commit -m "Squash commits A through X"
# Verify that this new commit is equivalent to the final state at A
git diff A
替代方案#2:使用补丁
另一种选择是简单地使用补丁。只需生成 A 到 Y 之间差异的 diff 补丁,然后将该补丁应用为 Y 之上的新提交:
git diff y a > squash.patch
git checkout -b squash-branch y
git apply squash.patch
git commit -m "Squash commits A through X"
# Verify that this new commit is equivalent to the final state at A
git diff A
正如所指出的评论里@A-B-B,如果涉及二进制文件,这将不太有效。git diff --binary除了文本文件之外,还可以用于输出二进制文件的差异,但我不确定这些差异是否也可以用作补丁。