git commit --squash 选项有什么作用,为什么会有用?

What does the git commit --squash option do and why would it be useful?

我一直在寻找一种替代解决方案来压缩分支中的一系列提交。我过去所做的是使用 git rebase -i HEAD~<#commits> 然后选择要压缩的提交。通常我 pick 编辑了最新的提交,并压缩了两者之间的冗余提交。

这种方法工作得相当好,但我希望有一种更快的方法。我注意到 git commit 有一个 --squash 选项。但我不确定这是如何工作的。它的具体作用是什么,您如何使用它?这能解决我的问题吗?

来自documentation

--squash=<commit>

Construct a commit message for use with rebase --autosquash. The commit message subject line is taken from the specified commit with a prefix of "squash! ". Can be used with additional commit message options (-m/-c/-C/-F). See git-rebase[1] for details.

--squash(也是 --fixup 标志)将提交作为参数,并格式化消息以用于 --autosquash.

可以在您的配置中设置 rebase.autosquash = true 以缩短整个过程。

如果您想压缩最后的 N 提交:

git reset --soft HEAD~N && git commit

这会将头放在 HEAD~N 上,因此索引和工作目录根本不会改变,这意味着您现在可以使用 git commit 并为所有更改创建一个提交.

假设您正在处理功能分支,您已经完成了 15 次提交。现在您已完成任务并希望将其合并为 master。这 15 次提交将使 master 分支的历史变得很长,更好的选择是将它们压缩在单个提交中,给它有意义的评论。硕士历史是干净的,有利于您将来也可以复习。 Git 合并 master --sqash.

现在IDE也对这个选项提供了很好的支持。