Page cover

合併多個 Commit , 編輯

我們深入探討每位開發人員都應該掌握的基本 Git 技巧。包括:合併多個提交、編輯提交和 Interactive rebase 等。逐步了解如何優化您的 Git 工作流程,有效地結合多個提交、精煉提交消息以及利用 Interactive rebase 的強大功能。

Commit Merge 模式


  • Merge commit: 保留 Branch commit 歷程,又稱為 no fast-forward merge。(預設的 Merge 模式)

  • Squash merge: 忽略並壓縮 Branch commit 歷程。

  • Rebase merge (基底合併): 將 Branch commit 歷程加入到 Main branch commit,又稱為 fast-forward merge 。(從 Branch 取得最新內容,並重新定位 Commit 基準)

  • Cherry-Pick (揀選): 從一個 Branch 中獲取單個 Commit 並將其 Merge 於另一個 Branch。

Merge commit
Squash merge
Rebase commit
Cherry-Pick

將 Merge commit (Branch merge) 到當前 Branch。

SHELL
git merge <要合併的 Branch>

執行 Rebase merge 到當前 Branch。。

SHELL
git rebase <Branch 名稱>

執行 Cherry-pick 到當前 Branch。。

SHELL
git cherry-pick <Git SHA-1 ID>

同一 Repository 的 Git SHA-1 ID 不會重複。

Interactive rebase


Interactive rebase 允許以互動的方式(interactive)修改、刪除、合併和拆分同一 Branch 的 Commit。

Interactive rebase 是一個強大的工具,但應該小心使用它,因為它可以改變 Branch 的歷史,這可能會給在同一 Branch 上工作的其他開發人員帶來問題。通常建議只在本地 Branch 或尚未 Push branch 上使用 Interactive rebase。

  1. 執行 Interactive rebase ,顯示編輯介面。 (使用預設編輯器開啟)

SHELL
git rebase -i HEAD~7
git rebase -i HEAD~<顯示 Commit 數量>
Interactive rebase 編輯說明

<Commands> <Git SHA-1 ID> <Commit 摘要> , 常用的 <Commands>:

pick: Commit 維持不變

squash: 將此條 Commit 併入前一條 Commit。

drop: 刪除 Commit。

reword: 編輯 Commit。

label: 使用標籤標記 Commit。

編輯介面
使用 squash 後,壓縮的訊息
使用 squash 後,log 訊息

跳過 Conflict commit。

SHELL
git rebase --skip

繼續因Conflict 而暫停的 Interactive rebase。

SHELL
git rebase --continue

製作 Remote repository 副本


  1. 建立空白的 Remote repository 副本。

可以 clone URL建立空白副本

導入 Repository
建立空白 Repository
  1. Push 所有 Tags、本地 Branchs。

SHELL
git push --mirror <Github網址>.git

參考資料


Windows 上的 Git:如何設置合併工具? - 堆棧溢出

git - merge --squash 和 rebase 有什麼區別? - 堆棧溢出

Git Rebase VS Merge VS Squash:如何選擇合適的? - 開發社區

合併策略和壓縮合併 - Azure Repos | Microsoft Learn

About pull request merges - GitHub Docs

Git fast-forward VS no fast-forward merge - Stack Overflow

Last updated

Was this helpful?