利用git rebase合并commit

现有git库如下:

初始git log

$ git log
commit 697dabcf4407e44382a298d798dc7608ab90fb92 (HEAD -> master)
Author: Your Name <you@example.com>
Date: Thu Sep 1 15:41:28 2022 +0800

add3

commit fc65840dfb217b6cb3c14d0d8c7343e448357935
Author: Your Name <you@example.com>
Date: Thu Sep 1 15:41:19 2022 +0800

add2

commit f5f6f71466af2271906c119acd48c51e1f8d2576
Author: Your Name <you@example.com>
Date: Thu Sep 1 15:41:08 2022 +0800

add1

commit a88c1fd9e627e5dcf032995e9d1396e31130f5a0
Author: Your Name <you@example.com>
Date: Thu Sep 1 15:38:33 2022 +0800

add0

 

用图形表示:

 

现在rebase 最新的3个commit:
git rebase -i HEAD~3
此时最上面的3个commit弹出:

 

HEAD变为这3个commit前的最新commit:

假设最新三个commit分别为(从旧到新):

  • add 1
  • add 2
  • add 3

输入rebase命令后会显示:

pick f5f6f71 add1
pick fc65840 add2
pick 697dabc add3

 

修改为:

pick f5f6f71 add1
pick fc65840 add2
squash 697dabc add3

表示pick两个commit:add 1 和 add 2
squash一个commit: add 3

保存退出后显示合并后commit的message(#为注释):

# This is a combination of 2 commits.
# This is the 1st commit message:

add2

# This is the commit message #2:

add3

这里可以修改合并后的commit的message,也可以不修改(默认为被合并的两次commit的message放一起),直接保存退出
git之后所做的事:

  1. add 1这个commit盖到HEAD上面,成为新HEAD
  2. add 3这个commit被squash到add 2这个commit,然后一起盖到新HEAD上面,成为新HEAD,达到合并commit的目的

最终状态:

 

之后显示rebase成功:

$ git rebase -i HEAD~3
[detached HEAD 7dc038a] add2
Date: Thu Sep 1 15:41:19 2022 +0800
1 file changed, 2 insertions(+)
Successfully rebased and updated refs/heads/master.

rebase后git log

$ git log
commit 7dc038a9e11fcf62c46eadf78fa665809efa2585 (HEAD -> master)
Author: Your Name <you@example.com>
Date: Thu Sep 1 15:41:19 2022 +0800

add2

add3

commit f5f6f71466af2271906c119acd48c51e1f8d2576
Author: Your Name <you@example.com>
Date: Thu Sep 1 15:41:08 2022 +0800

add1

commit a88c1fd9e627e5dcf032995e9d1396e31130f5a0
Author: Your Name <you@example.com>
Date: Thu Sep 1 15:38:33 2022 +0800

add0

 

如果要把3个commit都合并到一起,则可以修改为:

pick 0151429 add 1
squash f23dcc2 add 2
squash e3983bf add 3

注意add 1这个commit不能用squash,因为squash是将当前commit合并到之前的commit上,而我们并未获取add 1这个commit之前commit的修改权限

 

参考文档

https://backlog.com/git-tutorial/tw/stepup/stepup7_5.html

封面链接

https://www.pixiv.net/artworks/74855837

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注