如何使用Git将我最后的X提交压缩成一个提交?
如何使用Git将我最后的X提交压缩成一个提交?
使用 git rebase -i <after-this-commit>
并使用“squash”或“fixup”替换第二次和后续提交中的“pick”,如中所述 手册。
在这个例子中, <after-this-commit>
是SHA1哈希值或当前分支的HEAD的相对位置,从中为rebase命令分析提交。例如,如果用户希望在过去查看当前HEAD的5次提交,则命令为 git rebase -i HEAD~5
。
你可以相当容易地做到这一点 git rebase
要么 git merge --squash
。在这个例子中,我们将压缩最后3次提交。
如果要从头开始编写新的提交消息,这就足够了:
git reset --soft HEAD~3 &&
git commit
如果你想用现有提交消息的串联开始编辑新的提交消息(即类似于pick / squash / squash / ... / squash) git rebase -i
指令列表会启动你,然后你需要提取这些消息并将它们传递给 git commit
:
git reset --soft HEAD~3 &&
git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"
这两种方法都以相同的方式将最后三次提交压缩成一个新的提交。软复位只是将HEAD重新指向您不想压缩的最后一次提交。软复位不会触及索引和工作树,使索引处于新提交所需的状态(即,它已经具有您即将“扔掉”的提交的所有更改)。
您可以使用 git merge --squash
为此,这比稍微优雅一点 git rebase -i
。假设您是主人,并且您希望将最后12次提交压缩为一次。
警告:首先确保您提交工作检查 git status
很干净(因为 git reset --hard
将抛弃分阶段和未分阶段的变化)
然后:
# 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
选项更详细。
更新: 这种方法唯一真正的优点就是更简单 git reset --soft HEAD~12 && git commit
克里斯约翰森在 他的回答 是你获得提交消息预填充每个提交消息,你正在挤压。
我建议避免 git reset
在可能的情况下 - 特别是对于Git-novices。除非你真的需要基于a自动化流程 数 提交,有一种不那么奇特的方式......
git merge --squash (working branch name)
git commit
提交消息将根据壁球预先填充。
基于 克里斯约翰森的回答,
从bash添加全局“squash”别名:(或Windows上的Git Bash)
git config --global alias.squash '!f(){ git reset --soft HEAD~${1} && git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"; };f'
...或使用Windows的命令提示符:
git config --global alias.squash "!f(){ git reset --soft HEAD~${1} && git commit --edit -m\"$(git log --format=%B --reverse HEAD..HEAD@{1})\"; };f"
你的 ~/.gitconfig
现在应该包含这个别名:
[alias]
squash = "!f(){ git reset --soft HEAD~${1} && git commit --edit -m\"$(git log --format=%B --reverse HEAD..HEAD@{1})\"; };f"
用法:
git squash N
...它自动挤压最后一个 N
承诺,包容性。
注意:结果提交消息是所有压缩提交的组合,按顺序。如果你对此不满意,你可以随时 git commit --amend
手动修改它。 (或者,编辑别名以符合您的口味。)
如果您使用TortoiseGit,您可以使用该功能 Combine to one commit
:
Show Log
Combine to one commit
从上下文菜单中此函数自动执行所有必需的单个git步骤。 不幸的是只适用于Windows。
谢谢 这个方便的博客文章 我发现你可以使用这个命令来压缩最后3次提交:
git rebase -i HEAD~3
即使您在没有跟踪信息/远程仓库的本地分支上,它也很方便。
该命令将打开交互式rebase编辑器,然后允许您按照正常情况重新排序,压缩,重写等。