Git Rebase有兩種使用場景:
一、對本地分支代碼多次commit進行合并
二、對本地分支代碼進行變基操作,將其他分支commit合入到當前分支
一、合并commit記錄:
在工作中,有些同學的習慣是將每天編寫的代碼進行提交,這樣本地就會有多次commit記錄,如果提交到主庫上就對它的commit記錄造成了污染。
步驟:
(1)獲取提交記錄,確認需要合并最近3條記錄
$ git log --pretty=oneline -4
auiregfq8234g0923h09fdadfoiasdfhoiasdhf03f2oia Req:333
asdfasdaqw3f212543512345231234123gwrgwreg Req:222
34trgw354t2gdfwegq34t234t23gwegrwergwetg234 Req:111
234t23ggeegr34trgw35rgwetg23dfwegq34tw4t2w4 BUG:fix xxx
(2)合并最近三次提交
$ git rebase -i HEAD~3
提交后會進入編輯模式,注意下,這里的順序會跟git log查出來相反。
pick 34trgw Req:111
pick asdfas Req:222
pick auireg Req:333
# Rebase 5f2452b2..8f33126c onto 5f2452b2 (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.
#
(3)將后面兩個pick改為s(這樣做的效果就是222和333的代碼合并到111這次commit中)
pick 34trgw Req:111
s asdfas Req:222
s auireg Req:333
(4)然后保存退出,會進入另外一個編輯器中,這時可以對commit信息進行修改(把Req:111改為Req:new info),再保存退出
# This is a combination of 3 commits.
# The first commit's message is:
Req:111
# This is the 2nd commit message:
Req:222
# This is the 3rd commit message:
Req:333
(5)rebase完成,再用$ git log --pretty=oneline -2
查看得到:
34trgw354t2gdfwegq34t234t23gwegrwergwetg234 Req:new info
234t23ggeegr34trgw35rgwetg23dfwegq34tw4t2w4 BUG:fix xxx
二、分支變基:
1.先從master上chckout出一個分支;
2.master和feature各自演進;
3.feature準備合入master。
以前我是用git reset --soft退回master記錄,再本地stash,pull完代碼后,再進行unstash。
現在就可以直接在feature上執行rebase操作來代替上述操作:
1.git checkout master
2.git pull origin master
3.git checkout feature
4.git rebase master
第四步rebase干了哪些事呢?
先將master分支的代碼checkout,存到工作目錄下,然后將feature分支的commit依次合并。
如果合并的過程沒問題,也就是沒有沖突,那rebase到這里就算完成。
如果發生了沖突的情況,就會報錯error:Failed to merge in the changes.
自行解決沖突完畢后,使用git add .
命令添加修改文件,然后使用git rebase –continue
完成整個rebase過程。
如果你不想處理沖突,有兩種方式恢復:
一、使用git rebase –abort
放棄此次操作,分支會回到 rebase 開始前的狀態。
二、使用git rebase –skip
,用master分支的取代當前feature分支。
注:git rebase會導致其他開發的feature分支和你的feature出現不一樣的歷史,因此在多人協同開發同個分支的情況下需要謹慎使用