乐闻世界logo
搜索文章和话题

How do i squash my last n commits together in git?

7 个月前提问
3 个月前修改
浏览次数69

5个答案

1
2
3
4
5

git rebase无需或 即可相当轻松地完成此操作 git merge --squash。在此示例中,我们将压缩最后 3 个提交。

如果您想从头开始编写新的提交消息,这就足够了:

shell
git reset --soft HEAD~3 git commit

如果您想开始编辑新的提交消息与现有提交消息的串联(即类似于 pick/squash/squash/…/squash git rebase -i指令列表将开始您的操作),那么您需要提取这些消息并通过他们 git commit

shell
git reset --soft HEAD~3 && git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"

这两种方法都以相同的方式将最后三个提交压缩为一个新的提交。软重置只是将 HEAD 重新指向您不想压缩的最后一次提交。

软重置不会触及索引和工作树,从而使索引处于新提交所需的状态(即,它已经具有您要“丢弃”的提交的所有更改)。

2024年6月29日 12:07 回复

在第二次及后续提交中使用git rebase -i <after-this-commit>“pick”并将其替换为“squash”或“fixup”,如手册中所述。

在此示例中,<after-this-commit>是 SHA1 哈希值或当前分支 HEAD 的相对位置,从中分析提交以进行 rebase 命令。例如,如果用户希望查看过去来自当前 HEAD 的 5 次提交,则命令为git rebase -i HEAD~5

2024年6月29日 12:07 回复

您可以使用 git merge --squash它,这比 git rebase -i. 假设您在 master 上,并且想要将最后 12 次提交压缩为一次。

警告:首先确保您提交了您的工作 - 检查是否 git status干净(因为 git reset --hard将丢弃分阶段和未分阶段的更改)

然后:

shell
# Reset the current branch to the commit just before the last 12: git reset --hard HEAD~12 # HEAD@{1} is where the branch was just before the previous command. # This command sets the state of the index to be as it would just # after a merge from that commit: git merge --squash HEAD@{1} # Commit those squashed changes. The commit message will be helpfully # prepopulated with the commit messages of all the squashed commits: git commit

文档 git merge --squash更详细地描述了该选项。

2024年6月29日 12:07 回复

无需 rebase 的简单解决方案:

shell
git reset --soft HEAD~2 git commit -m "new commit message" git push -f

其中 2 意味着最后两次提交将被压缩,您可以将其替换为任意数字

2024年6月29日 12:07 回复

我建议git reset尽可能避免——尤其是对于 Git 新手。除非您确实需要基于_多次_提交来自动化流程,否则有一种不太奇特的方法......

  1. 将要压缩的提交放在工作分支上(如果还没有)——为此使用 gitk
  2. 查看目标分支(例如“master”)
  3. git merge --squash (working branch name)
  4. git commit

提交消息将根据挤压进行预填充。

2024年6月29日 12:07 回复

你的答案