Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

git 如何合并中间的 commit?

git 记录:

- a1
- a2
- a3
- a4
- a5

请问如何合并 a2、a3、a4 并把 commit message 改为 a24

也就是改成:

- a1
- a24 // a2、a3、a4 合并后的
- a5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

可以使用git rebase合并commit,用法为

git rebase -i  [startpoint]  [endpoint]

其中-i--interactive,即通过交互界面完成合并操作。[startpoint][endpoint]为需要合并的起止版本号,其中[startpoint]不会被进入合并流程,而[endpoint]则会(当然可以选择不合并)。

需要确保该分支只有你自己在使用时才使用rebase进行合并!

示例

通过git log查看commit的版本号,假设a5~a1依次如下:

70b1648 (HEAD -> master) a5
cef63d7 a4
2373978 a3
2413975 a2
98be6d0 a1

需要合并a2、a3、a4,则使用命令([endpoint]省略时默认为HEAD):

git rebase -i 98be6d0

然后会出现一个文件编辑的界面

pick 2413975 a2
pick 2373978 a3
pick cef63d7 a4
pick 70b1648 a5
...

注意这里需要留头留尾,即首尾都需要pick,否则会出现head detached等情况。这也是为什么我们在这里的[endpoint]要设置为HEAD
我们修改上方的指令即可,下方主要为命令具体说明,其中s即为squash,可以将几个commit合并,将文件修改为:

pick 2413975 a2
s 2373978 a3
s cef63d7 a4
pick 70b1648 a5

这样就将a3,a4的提交都折叠了。输入:wq保存后会进入新的编辑界面:

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

a2

# This is the commit message #2:

a3

# This is the commit message #3:

a4

可以将其删除,输入自己想要的合并信息如:

# This is a combination of 3 commits.
a24

然后输入:wq保存即可。
此时git log --oneline查看提交记录则变成了

c7b2cce (HEAD -> master) a5
478b208 a24
98be6d0 a1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...