[Git 筆記] merge、squash、rebase 三種方式的比較
GitHub 上的三個 merge
選項到底差在哪?讓我們實際來演練一下
合併前的情況
需要檔案請 戳這裡
合併前的 Repo 有兩個 branch,分別是 master
和 alexleo
注意:這裡的 alexleo
分支是處於落後 master
的狀態,這是為了呈現出各個方式在 merge
之後的總 commit
數量差異
使用 merge
合併
-
在
master
分支上執行:12git merge alexleo -
解決衝突
12vim file.txt -
將合併結果
commit
起來,成為一個新的修改12git commit -m "merge"
可以看到多出了一個 commit
叫做 merge
:
如果沒有 commit 3
的話,會是一直線(Fast-forward):
使用 squash
合併
-
在
master
分支上執行:12git merge --squash alexleo -
解決衝突
12vim file.txt -
將合併結果
commit
起來,成為一個新的修改12git commit -m "squash"
可以看到多出了一個 commit
叫做 squash
:
如果沒有 commit 3
的話,也還是需要把 alexleo commit 1
和 alexleo commit 2
變成一個 squash
:
使用 rebase
合併
-
在
alexleo
分支上執行:12git rebase master -
解決衝突(
alexleo commit 1
)之後下--continue
繼續:12git rebase --continue -
解決衝突(
alexleo commit 2
)之後再下--continue
繼續:12git rebase --continue -
切換回
master
執行合併:12git merge alexleo
因為 rebase
的原理是重放(Replay)一次所處的分支(alexleo
)的修改在目標(master
)上,所以合併完成之後當然是一條直線:
注:其實也可以換個方式理解,把 rebase
想成是把 alexleo
這個分支直接 拔起來 然後 接 在 master
頭上
Extra: 使用 git log
檢視修改紀錄
使用指令:
1 2 |
git log --all --graph |
--all
包含所有分支--graph
畫成圖
▲ 合併之前
▲ 使用 merge
合併之後
▲ 使用 squash
合併之後
▲ 使用 rebase
合併之後
參考資料
-
git log – Pretty git branch graphs – Stack Overflow
- 感謝回答2(@Patoshi パトシ)梗圖支援,不然我每次都記不住
git log
怎麼印出graph
- 感謝回答2(@Patoshi パトシ)梗圖支援,不然我每次都記不住
-
什麼是分支?【分支 (branch)】 | 連猴子都能懂的Git入門指南 | 貝格樂(Backlog)
- 真的很有善的教學,每次忘記指令都靠它