有时候我们会因为一个需求多次提交,但是多次提交的内容并无实际意义,只是这次需求代码的完善和补充,我们不希望在提交记录时间轴上看到这些提交信息,我们应该合并多次的commit message为一次,这里我们使用rebase。

假如我们为这次测试需求提交了4次,其实只需要一个commit message,如下:

commit 8fecb60f1fb048d3faa11cdb35cebcd48a203244 (HEAD -> master) Author: shuaijin2 66118181@qq.com Date: Mon May 31 17:06:54 2021 +0800

fix: 增加测试内容2次

commit d7f94a78119fdc1996c1a698d845c7f45b84328d Author: shuaijin2 66118181@qq.com Date: Mon May 31 17:06:03 2021 +0800

fix: 增加测试内容1次

commit 56737dd949703bf8daeea53e8cfdb0e6ba2ae774 Author: shuaijin2 66118181@qq.com Date: Mon May 31 17:04:16 2021 +0800

fix: 增加测试内容

commit fe4776bfa03941e7a6b9e2582a4387a9a493e11b Author: shuaijin2 66118181@qq.com Date: Mon May 31 17:03:14 2021 +0800

fix: 测试

commit e9796de2a6e8a6731fba28e4aef6980aac0bb326 Author: shuaijin2 66118181@qq.com Date: Mon May 31 16:45:05 2021 +0800

feat: 增加chrome调试摄像头

我们可以用git rebase -i fe4776 进入交互模式

其中,-i 的参数是不需要合并的 commit 的 hash 值,这里指的是第一条 commit, 接着我们就进入到 vi 的编辑模式

pick fe4776b fix: 测试 pick 56737dd fix: 增加测试内容 pick d7f94a7 fix: 增加测试内容1次 pick 8fecb60 fix: 增加测试内容2次

Rebase fe4776b..8fecb60 onto fe4776b (3 commands)


我们把测试后面的3个commit前面的pick改成s (squash),然后输入:wq保存退出,squash 的意思是这个 commit 会被合并到前一个commit,

This is a combination of 4 commits.

This is the 1st commit message:

fix: 测试

This is the commit message #2:

#fix: 增加测试内容

This is the commit message #3:

#fix: 增加测试内容1次

This is the commit message #4:

#fix: 增加测试内容2次

接着进入commit message界面,用#注释掉 测试 以外其他3个message

然后输入:wq保存退出,我们可以看到4条信息合并成一条信息“测试”

commit 8288dd869e1d9bf22915e5cf2d81cf0c98763767 (HEAD -> master) Author: shuaijin2 66118181@qq.com Date: Mon May 31 17:03:14 2021 +0800

fix: 测试

commit e9796de2a6e8a6731fba28e4aef6980aac0bb326 Author: shuaijin2 66118181@qq.com Date: Mon May 31 16:45:05 2021 +0800

feat: 增加chrome调试摄像头

如果以上4条信息已经在远程了,那么我们需要用git push -f 强制推送到远程分支,此步骤一定注意备份好远程分支代码,另外git可以设置哪些角色可以使用git push -f 强制推送,在Settings - Repository - Protected Branches。