Git 合并提交

Git 在执行 rebase 操作时,有时候会需要把当前分支中的若干次提交合并在一起,作为一次提交合并到主分支当中,这时候就要用到 squash 。顾名思义,squash 的用途是合并多次提交。

流程

初始状态

开始 Rebase

在 Rebase 操作的同时进行 Squash。

完成 Rebase

操作

如图一所示,要合并 C5C6C7 三次提交,先切换到 C5C6C7 所在的分支,然后执行

git rebase -i HEAD~3  

之后会出现如下提示信息

pick 708fa0a commit message A  
pick 8baaa26 commit message B  
pick dba177a commit message C

# Rebase 2d2fb07..bfa62a9 onto 2d2fb07 (3 command(s))
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

这个时候把它改成如下形式

pick 708fa0a commit message A  
squash 8baaa26 commit message B  
squash dba177a commit message C

# ...

之后保存退出,出现

# This is a combination of 3 commits.
# The first commit's message is:
commit message A

# This is the 2nd commit message:
commit message B

# This is the 3rd commit message:
commit message C  

再保存,就会显示合并成功的提示信息。

[detached HEAD bfa62a9] commit message A
 Date: Fri Jun 17 16:32:31 2016 +0800
 2 files changed, 3 insertions(+)
Successfully rebased and updated refs/heads/dev.  

这时候,Rebase 合并成功,并且 C5C6C7 三次提交也合并在一起了。

补充


对于合并提示信息

pick 708fa0a commit message A  
squash 8baaa26 commit message B  
squash dba177a commit message C  

squash 也可以改为 fixup

pick 708fa0a commit message A  
squash 8baaa26 commit message B  
fixup dba177a commit message C  

它们二者的区别就在于 fixup 后面的提交信息会被忽略。

最后,合并提示信息也可以简写成这样

p 708fa0a commit message A  
s 8baaa26 commit message B  
f dba177a commit message C  
Show Comments