背景

对于不连续但是作用相同的间隔的commit,此时我们想将他们合并成一个commit。

实践

可以看到,下面是5个commit,其中4个commit都是和readme文件有关,我们想将这几个和readme文件相关的不连续的commit给合并成一个。

1
2
3
4
5
6
7
 G:\mygitea\GitLearn\learn03   master 
$ git log --oneline --graph master
* 7fd2c5d (HEAD -> master) add test info to readme
* 30636df add test file
* ac94160 add Third commit info to readme
* e232742 add The Second commit info to readme
* 342ea2f add First commit info to readme

我们继续使用git rebase -i 342ea2f命令:

1
2
 G:\mygitea\GitLearn\learn03   master 
$ git rebase -i 342ea2f

最终页面呈现的只有4个commit的信息,这个是不够的,我们需要把父commit也给写进来,越老的commit的写在越上面,修改如下:

可以不用写commit message,我们的目的是将8653890b\c18b52fc\cca417a0\44ac8522这4个不连续的commit合并。我们需要把要合并的commit放到一起,使得四个commit连续,并删除重复项,同时修改命令为s(参考文章:合并连续commit),保持融合的头commit命令为pick

保存退出后:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
interactive rebase in progress; onto 342ea2f
Last command done (1 command done):
pick 342ea2f
Next commands to do (4 remaining commands):
squash e232742 add The Second commit info to readme
squash ac94160 add Third commit info to readme
(use "git rebase --edit-todo" to view and edit)
You are currently rebasing branch 'master' on '342ea2f'.
(all conflicts fixed: run "git rebase --continue")

nothing to commit, working tree clean
The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

git commit --allow-empty

Otherwise, please use 'git rebase --skip'
Could not apply 342ea2f...

G:\mygitea\GitLearn\learn03   HEAD detached at 342ea2f 
$ git status
interactive rebase in progress; onto 342ea2f
Last command done (1 command done):
pick 342ea2f
Next commands to do (4 remaining commands):
squash e232742 add The Second commit info to readme
squash ac94160 add Third commit info to readme
(use "git rebase --edit-todo" to view and edit)
You are currently rebasing branch 'master' on '342ea2f'.
(all conflicts fixed: run "git rebase --continue")

nothing to commit, working tree clean

这里提示不连续,我们继续输入git rebase --continue继续rebase:

这里我们添加一行message,对这几个message进行概括,提交:

1
2
3
4
5
6
7
 G:\mygitea\GitLearn\learn03 
$ git rebase --continue
[detached HEAD 16ce92b] add info to readme
Date: Wed May 11 09:02:40 2022 +0800
1 file changed, 4 insertions(+)
create mode 100644 readme
Successfully rebased and updated refs/heads/master.

看到出现上面的信息,我们的变基就已经结束了,此时分支的commit的情况如下:

1
2
3
4
5
6
7
 G:\mygitea\GitLearn\learn03   master 
$ git log --oneline --graph master
* 7a7836e (HEAD -> master) add test file
* 16ce92b add info to readme

G:\mygitea\GitLearn\learn03   master 
$ gitk --all

出现了两颗树是没有祖先节点的,因为原先的根commit加了新的信息进来,已经不是原来的初始commit了,所以会产生新的初始commit,生成了两颗树。

master所在的分支是重要的分支,此时如果我们把下面的分支或tag删除,git就会将下面的树清理掉。

总结与补充

Q1:操作完第一步以后,后悔了不想continue了该如何操作?

git rebase —abort