merge
git merge
將已提交的commit(自歷史記錄與當前分支分開以來的提交)合併到當前分支中。
原始分支
A---B---C topic
/
D---E---F---G master
checkout
至master
分支,使用命令git merge topic
A---B---C topic
/ \
D---E---F---G---H master
git merge --abort
將中止合併過程,並嘗試重建合併前的狀態。但是,如果在合併開始時有未提交的更改(尤其是在合併開始後進一步修改了這些更改),則git merge --abort
在某些情況下將無法重建原始更改。因此警告:不建議運行git merge
合併重要的未提交更改
rebase
git rebase
的使用場景
- 合併多次
commit
爲單次commit
- 分支合併
變基的原理
- 找到這兩個分支(即當前分支 topic、變基操作的目標基底分支 master)的最近共同祖先 D
- 對比當前分支相對於該祖先的歷次提交,提取相應的修改並存爲臨時文件(A+B+C=C’)
- 然後將當前分支指向目標基底 C’, 最後以此將之前另存爲臨時文件的修改依序應用。
原始分支
A---B---C topic
/
D---E---F---G master
在topic
分支使用git rebase master
C' topic
/
D---E---F---G maste
checkout
至master
分支,使用命令git merge topic
D---E---F---G---C' master
注意:rebase 會改寫歷史記錄,若該分支的提交已被其他使用者修改時,不建議使用
可選操作
- p,
pick
保留該commit- r,
reword
保留該commit,但修改註釋- e,
edit
保留該commit,但修改提交- s,
squash
保留該commit,將其前一個commit合併- f,
fixup
操作與squash
相同,但丟棄註釋- x,
exec
執行shell命令- d,
drop
丟棄該commit
cherry-pick
git-cherry-pick
能應用(合併)已經存在的commit,即選擇合併某個特定commit
原始分支
A---B---C topic
/
D---E---F---G master
假設commit C的版本號爲7289a5
,在master
分支使用git cherry-pick 7289a5
A---B---C topic
/
D---E---F---G---C master
參考資料: