git rebase 合並多個commit 方法
在開發過程中,有時一個任務會分幾次commit提交,這樣可能對於有些分支要cherry pick時會比較麻煩,這是我們可以通過git rebase 將幾個commit合並為一個commit,再推送到遠端
git rebase -i
這里指的是通過交互的手段執行git rebase, 也是合並commits 的好方法
例子
假設當前git日志文件內容是這樣
➜ test git:(master) git log --oneline
bb44232 (HEAD -> master) 增加第f行
5d2e760 增加第b行,增加第c行
f443e25 增加第a行,增加第行
48d5c58 增加第6行,增加第7行,增加第8行
c4b45e6 增加第五行
0469b01 增加第四行,修改commit
cd80e8f 22222
295e1a6 11111
a772b51 1. 增加testgit文件
我想合並這幾個commit
bb44232 (HEAD -> master) 增加第f行
5d2e760 增加第b行,增加第c行
f443e25 增加第a行,增加第行
48d5c58 增加第6行,增加第7行,增加第8行
1. 要先找出48d5c58 增加第6行,增加第7行,增加第8行之前的commit-id c4b45e6
執行以下命令
git rebase -i c4b45e6
會進入vim 並顯示以下內容
pick 48d5c58 增加第6行,增加第7行,增加第8行
pick f443e25 增加第a行,增加第行
pick 5d2e760 增加第b行,增加第c行
pick bb44232 增加第f行
# Rebase c4b45e6..bb44232 onto c4b45e6 (4 commands)
#
# 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:保留該commit(縮寫:p)
reword:保留該commit,但我需要修改該commit的注釋(縮寫:r)
edit:保留該commit, 但我要停下來修改該提交(不僅僅修改注釋)(縮寫:e)
squash:將該commit和前一個commit合並(縮寫:s)
fixup:將該commit和前一個commit合並,但我不要保留該提交的注釋信息(縮寫:f)
exec:執行shell命令(縮寫:x)
drop:我要丟棄該commit(縮寫:d)
將下面幾行的pick 換成s 即可,代表將下面幾個合並到最近的(即pick 48d5c58)commit上,並生成一個新的commit(包括48d5c58就都沒有了)
pick 48d5c58 增加第6行,增加第7行,增加第8行
s f443e25 增加第a行,增加第行
s 5d2e760 增加第b行,增加第c行
s bb44232 增加第f行
# Rebase c4b45e6..bb44232 onto c4b45e6 (4 commands)
# ...
之后可能沖突(跨commit rebase時可能會沖突),就解決沖突
然后執行git add 和 git rebase --continue
最后會彈出vim,讓你填寫這個最后合並的commit的注釋信息
填寫完 wq,就ok了
執行成功信息
➜ test git:(master) git rebase -i c4b45e6
[detached HEAD 7d9155b] 增加第6行,增加第7行,增加第8行;增加第a行,增加第行;增加第b行,增加第c行
Date: Tue Aug 13 17:46:37 2019 +0800
2 files changed, 17278 insertions(+)
create mode 100644 package-lock.json
Successfully rebased and updated refs/heads/master.
查看git 日志
7d9155b (HEAD -> master) 增加第6行,增加第7行,增加第8行;增加第a行,增加第行;增加第b行,增加第c行
c4b45e6 增加第五行
0469b01 增加第四行,修改commit
cd80e8f 22222
295e1a6 11111
a772b51 1. 增加testgit文件
42c86e2 Initial commit from Create React App
可以看到c4b45e6之上的commit都合成了一個commit了(即7d9155b,一個新的commitid)