Git 進階操作與工作流程
Git 不僅是版本控制工具——它是現代軟體開發的協作基礎設施。理解 Git 的進階操作能讓你從「會用 Git」進化到「精通 Git」。
🔥 Vibe Prompt
「幫我建立一個 Git 進階教學:包含 Gitflow vs GitHub Flow 比較、互動式 rebase 實戰、cherry-pick 與 stash 的正確使用時機、bisect 除錯、以及團隊協定的 commit message 規範。」
分支策略
GitHub Flow(推薦用於持續部署)
main ──── feat/a ──── merge ──── feat/b ──── merge ────
\ /
└─ commits ─────────────┘
原則:
main永遠是可部署的- 新功能從
main開分支 - 分支命名:
feat/xxx、fix/xxx、chore/xxx - 透過 PR (Pull Request) 合併
- 合併後立即刪除分支
Gitflow(適用於版本發布)
main ──── v1.0 ──── v1.1 ──── v2.0
\ / /
develop ──── feat ──── release ──── hotfix
main:正式發布版本develop:開發主線feature/*:新功能release/*:發布準備hotfix/*:緊急修復
互動式 Rebase
互動式 rebase 讓你可以改寫歷史——在推送前整理 commit:
# 重新整理最近 3 個 commit
git rebase -i HEAD~3
# 你會看到如下編輯器:
pick abc123 feat: add login form
pick def456 fix: correct validation
pick 789ghi feat: add error handling
# 常用指令:
# pick = 保留此 commit
# reword = 修改 commit message
# squash = 合併到前一個 commit
# fixup = 合併並丟棄 message
# drop = 刪除此 commit
# edit = 暫停在這個 commit 進行修改
Rebase 實戰範例
# 將分支 rebase 到最新的 main
git checkout feature/awesome
git rebase main
# 出現衝突時:
# 1. 手動解決衝突
# 2. git add .
# 3. git rebase --continue
# 4. 或 git rebase --abort 放棄
# 合併多個 commit 為一個
# 將第二個和第三個 squash 到第一個
pick abc123 feat: add complete feature
squash def456 wip: intermediate
squash 789ghi fix: typo
# 結果:一個乾淨的 commit「feat: add complete feature」
Cherry-Pick
將特定 commit 應用到當前分支:
# 從其他分支挑選一個 commit
git cherry-pick abc123
# 挑選多個 commit
git cherry-pick abc123 def456
# 挑選一段範圍
git cherry-pick abc123..def456
# 常用場景:
# - 將 hotfix 從 main 套用到 release 分支
# - 只挑選某個功能的 commit,不整個 merge
Stash
暫存未完成的工作:
# 暫存目前變更
git stash
# 暫存並包含未追蹤檔案
git stash -u
# 檢視暫存清單
git stash list
# stash@{0}: WIP on feat/login: abc123 login form
# stash@{1}: WIP on main: def456 fix css
# 套用暫存(保留 stash)
git stash apply stash@{0}
# 套用並刪除
git stash pop
# 刪除特定 stash
git stash drop stash@{0}
Bisect(二元搜尋除錯)
當你發現一個 bug,但不確定是哪個 commit 引入的,git bisect 可以幫你用二分法快速定位:
# 開始 bisect
git bisect start
# 標記當前為壞的
git bisect bad
# 標記某個舊版本為好的
git bisect good v1.0
# Git 會自動跳到中間的 commit
# 測試後標記:
git bisect good # 這個 commit 是好的
git bisect bad # 這個 commit 是壞的
# 重複幾次後,Git 會告訴你第一個壞的 commit
# abc123 is the first bad commit
# 結束 bisect
git bisect reset
Commit Message 規範
好的 commit message 讓團隊協作更順暢:
<type>(<scope>): <subject>
<body>
<footer>
| Type | 用途 |
|------|------|
| feat | 新功能 |
| fix | 錯誤修復 |
| docs | 文件變更 |
| style | 程式碼格式(不影響邏輯) |
| refactor | 重構 |
| test | 測試 |
| chore | 雜項(建置、依賴) |
# 好的範例
feat(auth): add Google OAuth login
Implement Google OAuth 2.0 authentication flow:
- Add Google OAuth configuration
- Create OAuth callback handler
- Add user profile sync after login
- Update database schema for OAuth accounts
Closes #123
# 壞的範例
fix bug
update something
asdf
實戰練習
💡 Vibe Coding 練習:請 AI 幫你:
- 建立一個互動式腳本,引導你建立正確的 Git workflow
- 建立一個 git hook(pre-commit)自動檢查程式碼格式
- 建立一個自動生成 changelog 的工具
- 模擬一個團隊協作情境:分支 → 開發 → rebase → PR → merge