git如何合并多个commits
使用场景
在分支开发的时候,我们经常会在分支上有多个commit,然而在最后开发完成合并到主干(或者发布分支)的时候,我们希望能把这些commit合并成一个,这样在主干看来只做了一次commit,因为在开发分支上有些时候只有一点点改动就产生了一个commit,合并到主干后会显得commit过多过于零散。
第0步切换到你的分支
$ git checkout <branchname>
第一步找出你的commits
$ git log --oneline
1959093 [BUG-4668] Add rollback script
f41c79b [BUG-4668] Let backup configure time once
d8b3f48 Merge pull request #128 in <project/repo> from BUG-4668 to develop
30b5d3d BUG-4668 use local copy of images instead of remote format
...
现在我们需要把前两个commit合并成一个。
第二步 合并commit
$ git rebase -i d8b3f48
注意这里这个hash(d8b3f48),不是你要merge的任何一个commit,而是你改动的基础commit,这就是rebase的参照commit。
也可以使用另外一种写法:
$ git rebase -i HEAD~2
数字2表示合并最近的两个commit:git rebase -i HEAD~[NUMBER OF COMMITS]
参数i表示interactive的方式,这样会弹出一个窗口让你进行编辑:
pick f41c79b [BUG-4668] Let backup configure time once
pick 1959093 [BUG-4668] Add rollback script
# Rebase d8b3f48..1959093 onto d8b3f48
#
# 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
#
# 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
然后我们编辑新的commit的内容:
pick f41c79b [BUG-4668] Add rollback scripts and fix several backup script minors
fixup 1959093 [BUG-4668] Add rollback script
...
关于pick和fixup的含义,窗口里面有详细介绍;通常我们把第一个作为提交的内容,选择pick,并且把message修改为一个综合的描述信息,然后把所有的其他commits都选为fixup,这样合并后只有个commit历史,包含之前所有的commits改动和第一个修正过的commit的message。
编辑完之后按:wq退出:
$ git rebase -i d8b3f48
[detached HEAD 1660c81] [BUG-4668] Let backup configure time once
5 files changed, 235 insertions(+), 18 deletions(-)
Successfully rebased and updated refs/heads/develop-BUG-4668.
再次确认改动结果:
$ git log --oneline
1660c81 [BUG-4668] Let backup configure time once
d8b3f48 Merge pull request #128 in <project/repo> from BUG-4668 to develop
这个地方要注意一下log message是不是想要的,我经常就碰到不是我想要的内容,不知道是不是git的一个bug还是我操作的错误;如果不一致就行--amend命令修复一下:
$ git commit --amend
注意:--amend只能修复最后commit的log message。
可见被合并成了一个commit了:
1959093
+ f41c79b
= 1660c81
第三步:push
如何之前做个push代码到远端了,那么需要强制再push一次:
$ git push origin <branchname> --force