Autosquash 提交你希望在 rebase 期间压缩的代码

鉴于以下历史记录,假设你要进行更改,以便压缩到提交 bbb2222 A second commit

$ git log --oneline --decorate
ccc3333 (HEAD -> master) A third commit
bbb2222 A second commit
aaa1111 A first commit
9999999 Initial commit

完成更改后,可以像往常一样将它们添加到索引中,然后使用 --fixup 参数提交它们,并引用要压缩的提交:

$ git add .
$ git commit --fixup bbb2222
[my-feature-branch ddd4444] fixup! A second commit

这将创建一个新的提交,其中包含 Git 在交互式 rebase 期间可以识别的提交消息:

$ git log --oneline --decorate
ddd4444 (HEAD -> master) fixup! A second commit
ccc3333 A third commit
bbb2222 A second commit
aaa1111 A first commit
9999999 Initial commit

接下来,使用 --autosquash 参数进行交互式 rebase:

$ git rebase --autosquash --interactive HEAD~4

Git 会建议你将使用 commit --fixup 做出的提交压缩到正确的位置:

pick aaa1111 A first commit
pick bbb2222 A second commit
fixup ddd4444 fixup! A second commit
pick ccc3333 A third commit

为避免必须在每个 rebase 上键入 --autosquash,你可以默认启用此选项:

$ git config --global rebase.autosquash true