Git 工作流程模式 是做什麼的?
Git 版本控制、分支策略與協作開發的最佳實務。
啟動時機
- 為新專案設定 Git 工作流程
- 決定分支策略(GitFlow、Trunk-Based、GitHub Flow)
- 撰寫提交訊息與 PR 描述
- 解決合併衝突
- 管理版本發布與標籤
- 帶領新團隊成員熟悉 Git 實務
分支策略
GitHub Flow(簡單,推薦大多數團隊使用)
最適合持續部署與中小型團隊。
main (受保護,隨時可部署)
│
├── feature/user-auth → PR → 合併至 main
├── feature/payment-flow → PR → 合併至 main
└── fix/login-bug → PR → 合併至 main
規則:
main隨時可部署- 從
main建立功能分支 - 準備好審查時開啟 Pull Request
- 審查通過且 CI 通過後,合併至
main - 合併後立即部署
Trunk-Based Development(高速團隊)
最適合具備強大 CI/CD 與功能旗標的團隊。
main (主幹)
│
├── 短期功能分支 (最多 1-2 天)
├── 短期功能分支
└── 短期功能分支
規則:
- 所有人直接提交至
main或極短期的分支 - 使用功能旗標隱藏未完成的工作
- 合併前必須通過 CI
- 每天可部署多次
GitFlow(複雜,以發布週期為導向)
最適合排程發布與企業級專案。
main (正式環境發布)
│
└── develop (整合分支)
│
├── feature/user-auth
├── feature/payment
│
├── release/1.0.0 → 合併至 main 與 develop
│
└── hotfix/critical → 合併至 main 與 develop
規則:
main僅包含可上線的程式碼develop是整合分支- 功能分支從
develop分支出去,合併回develop - 發布分支從
develop分支出去,合併至main與develop - 熱修分支從
main分支出去,合併至main與develop
何時使用哪種策略
| 策略 | 團隊規模 | 發布頻率 | 最適合 |
|---|---|---|---|
| GitHub Flow | 任何規模 | 持續 | SaaS、網頁應用、新創 |
| Trunk-Based | 5 人以上有經驗團隊 | 每天多次 | 高速迭代團隊、功能旗標 |
| GitFlow | 10 人以上 | 排程 | 企業、受監管產業 |
提交訊息
Conventional Commits 格式
<type>(<scope>): <subject>
[optional body]
[optional footer(s)]
類型
| 類型 | 用途 | 範例 |
|---|---|---|
feat | 新功能 | feat(auth): add OAuth2 login |
fix | 錯誤修正 | fix(api): handle null response in user endpoint |
docs | 文件 | docs(readme): update installation instructions |
style | 格式調整,無程式碼變更 | style: fix indentation in login component |
refactor | 程式碼重構 | refactor(db): extract connection pool to module |
test | 新增/更新測試 | test(auth): add unit tests for token validation |
chore | 維護任務 | chore(deps): update dependencies |
perf | 效能改善 | perf(query): add index to users table |
ci | CI/CD 變更 | ci: add PostgreSQL service to test workflow |
revert | 還原先前的提交 | revert: revert "feat(auth): add OAuth2 login" |
好與壞的範例
# 不好:模糊、缺乏上下文
git commit -m "fixed stuff"
git commit -m "updates"
git commit -m "WIP"
# 好:清楚、具體、說明原因
git commit -m "fix(api): retry requests on 503 Service Unavailable
外部 API 在尖峰時段偶爾會回傳 503 錯誤。
加入指數退避重試邏輯,最多嘗試 3 次。
Closes #123"
提交訊息模板
在專案根目錄建立 .gitmessage:
# <type>(<scope>): <subject>
# # 類型: feat, fix, docs, style, refactor, test, chore, perf, ci, revert
# 範圍: api, ui, db, auth, 等
# 主旨: 祈使語氣、無句號、最多 50 字元
#
# [選用主體] - 說明原因,而非內容
# [選用頁尾] - Breaking changes、Closes #issue
啟用指令:git config commit.template .gitmessage
合併與重定基底
合併(保留歷史)
# 建立一個合併提交
git checkout main
git merge feature/user-auth
# 結果:
# * merge commit
# |\
# | * feature commits
# |/
# * main commits
使用時機:
- 將功能分支合併進
main - 希望保留精確的歷史記錄
- 多人共同開發該分支
- 分支已推送且其他人可能基於此分支工作
重定基底(線性歷史)
# 將功能分支的提交重新應用到目標分支之上
git checkout feature/user-auth
git rebase main
# 結果:
# * feature commits (經過改寫)
# * main commits
使用時機:
- 更新本地功能分支至最新
main - 希望得到線性、整潔的歷史
- 分支僅在本地(尚未推送)
- 僅有你一人處理該分支
重定基底工作流程
# 在發 PR 前,用最新 main 更新功能分支
git checkout feature/user-auth
git fetch origin
git rebase origin/main
# 解決任何衝突
# 測試仍應通過
# 強制推送(僅限於你是唯一的貢獻者)
git push --force-with-lease origin feature/user-auth
何時不該重定基底
# 永不重定基底的狀況:
- 已推送至共享儲存庫的分支
- 其他人已基於此分支進行開發
- 受保護的分支(main、develop)
- 已經合併過的分支
# 原因:重定基底會改寫歷史,破壞其他人的工作
Pull Request 工作流程
PR 標題格式
<type>(<scope>): <description>
範例:
feat(auth): add SSO support for enterprise users
fix(api): resolve race condition in order processing
docs(api): add OpenAPI specification for v2 endpoints
PR 描述模板
## 做了什麼
簡要說明此 PR 的內容。
## 為什麼
解釋動機與背景。
## 如何達成
值得強調的關鍵實作細節。
## 測試
- [ ] 新增/更新單元測試
- [ ] 新增/更新整合測試
- [ ] 已執行手動測試
## 截圖(如適用)
UI 變更的前後截圖。
## 檢查清單
- [ ] 程式碼符合專案風格指南
- [ ] 已完成自我審查
- [ ] 複雜邏輯已加入註解
- [ ] 文件已更新
- [ ] 未引入新的警告
- [ ] 測試在本地通過
- [ ] 相關 issue 已連結
Closes #123
程式碼審查檢查清單
審查者:
- 程式碼是否解決了所述問題?
- 是否涵蓋邊界情況?
- 程式碼可讀性與可維護性如何?
- 是否有足夠的測試?
- 是否存在安全疑慮?
- 提交歷史是否整潔(必要時已壓縮)?
作者:
- 請求審查前已完成自我審查
- CI 通過(測試、lint、型別檢查)
- PR 大小合理(理想情況下少於 500 行)
- 僅與單一功能/修正相關
- 描述清楚說明變更內容
衝突解決
識別衝突
# 在合併前檢查衝突
git checkout main
git merge feature/user-auth --no-commit --no-ff
# 若有衝突,Git 會顯示:
# CONFLICT (content): Merge conflict in src/auth/login.ts
# Automatic merge failed; fix conflicts and then commit the result.
解決衝突
# 查看衝突檔案
git status
# 在檔案中檢視衝突標記
# <<<<<<< HEAD
# content from main
# =======
# content from feature branch
# >>>>>>> feature/user-auth
# 選項一:手動解決
# 編輯檔案、移除標記、保留正確內容
# 選項二:使用合併工具
git mergetool
# 選項三:接受其中一方
git checkout --ours src/auth/login.ts # 保留 main 版本
git checkout --theirs src/auth/login.ts # 保留功能分支版本
# 解決後,暫存並提交
git add src/auth/login.ts
git commit
衝突預防策略
# 1. 保持功能分支短小且生命週期短
# 2. 經常重定基底至 main
git checkout feature/user-auth
git fetch origin
git rebase origin/main
# 3. 與團隊溝通共同修改的檔案
# 4. 使用功能旗標取代長期分支
# 5. 迅速審查並合併 PR
分支管理
命名慣例
# 功能分支
feature/user-authentication
feature/JIRA-123-payment-integration
# 錯誤修正
fix/login-redirect-loop
fix/456-null-pointer-exception
# 熱修(線上問題)
hotfix/critical-security-patch
hotfix/database-connection-leak
# 發布
release/1.2.0
release/2024-01-hotfix
# 實驗/PoC
experiment/new-caching-strategy
poc/graphql-migration
分支清理
# 刪除已合併的本地分支
git branch --merged main | grep -v "^\*\|main" | xargs -n 1 git branch -d
# 清除已刪除遠端分支的追蹤參考
git fetch -p
# 刪除本地分支
git branch -d feature/user-auth # 安全刪除(僅限已合併)
git branch -D feature/user-auth # 強制刪除
# 刪除遠端分支
git push origin --delete feature/user-auth
暫存工作流程
# 儲存進行中的工作
git stash push -m "WIP: user authentication"
# 列出暫存
git stash list
# 套用最近的暫存
git stash pop
# 套用特定暫存
git stash apply stash@{2}
# 刪除暫存
git stash drop stash@{0}
版本發布管理
語意化版本
MAJOR.MINOR.PATCH
MAJOR:不相容的變更
MINOR:新功能,向後相容
PATCH:錯誤修正,向後相容
範例:
1.0.0 → 1.0.1 (patch: bug fix)
1.0.1 → 1.1.0 (minor: new feature)
1.1.0 → 2.0.0 (major: breaking change)
建立發布
# 建立附註標籤
git tag -a v1.2.0 -m "Release v1.2.0
功能:
- 新增用戶認證
- 實作密碼重設
修正:
- 解決登入重新導向問題
重大變更:
- 無"
# 推送標籤至遠端
git push origin v1.2.0
# 列出標籤
git tag -l
# 刪除標籤
git tag -d v1.2.0
git push origin --delete v1.2.0
變更日誌產生
# 從提交記錄產生變更日誌
git log v1.1.0..v1.2.0 --oneline --no-merges
# 或使用 conventional-changelog
npx conventional-changelog -i CHANGELOG.md -s
Git 設定
必要設定
# 使用者身分
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
# 預設分支名稱
git config --global init.defaultBranch main
# 拉取行為(使用 rebase 而非 merge)
git config --global pull.rebase true
# 推送行為(僅推送目前分支)
git config --global push.default current
# 自動修正輸入錯誤
git config --global help.autocorrect 1
# 更好的差異演算法
git config --global diff.algorithm histogram
# 彩色輸出
git config --global color.ui auto
實用別名
# 加入 ~/.gitconfig
[alias]
co = checkout
br = branch
ci = commit
st = status
unstage = reset HEAD --
last = log -1 HEAD
visual = log --oneline --graph --all
amend = commit --amend --no-edit
wip = commit -m "WIP"
undo = reset --soft HEAD~1
contributors = shortlog -sn
Gitignore 模式
# 相依套件
node_modules/
vendor/
# 建置輸出
dist/
build/
*.o
*.exe
# 環境檔案
.env
.env.local
.env.*.local
# IDE
.idea/
.vscode/
*.swp
*.swo
# 作業系統檔案
.DS_Store
Thumbs.db
# 日誌
*.log
logs/
# 測試覆蓋率
coverage/
# 快取
.cache/
*.tsbuildinfo
常見工作流程
開始一個新功能
# 1. 更新 main 分支
git checkout main
git pull origin main
# 2. 建立功能分支
git checkout -b feature/user-auth
# 3. 撰寫變更並提交
git add .
git commit -m "feat(auth): implement OAuth2 login"
# 4. 推送至遠端
git push -u origin feature/user-auth
# 5. 在 GitHub/GitLab 上建立 Pull Request
更新 PR 內容
# 1. 新增額外變更
git add .
git commit -m "feat(auth): add error handling"
# 2. 推送更新
git push origin feature/user-auth
同步 Fork 與上游
# 1. 加入上游 remote(僅一次)
git remote add upstream https://github.com/original/repo.git
# 2. 取回上游
git fetch upstream
# 3. 將 upstream/main 合併至你的 main
git checkout main
git merge upstream/main
# 4. 推送至你的 fork
git push origin main
還原錯誤
# 還原上一次提交(保留變更)
git reset --soft HEAD~1
# 還原上一次提交(捨棄變更)
git reset --hard HEAD~1
# 還原已推送至遠端的上一次提交
git revert HEAD
git push origin main
# 還原特定檔案的變更
git checkout HEAD -- path/to/file
# 修正上一次提交的訊息
git commit --amend -m "新訊息"
# 將遺漏的檔案加入上一次提交
git add forgotten-file
git commit --amend --no-edit
Git Hooks
Pre-Commit Hook
#!/bin/bash
# .git/hooks/pre-commit
# 執行 lint
npm run lint || exit 1
# 執行測試
npm test || exit 1
# 檢查機密資料
if git diff --cached | grep -E '(password|api_key|secret)'; then
echo "偵測到可能的機密資訊。提交已中止。"
exit 1
fi
Pre-Push Hook
#!/bin/bash
# .git/hooks/pre-push
# 執行完整測試套件
npm run test:all || exit 1
# 檢查 console.log 陳述式
if git diff origin/main | grep -E 'console\.log'; then
echo "請先移除 console.log 陳述式再推送。"
exit 1
fi
反模式
# 不好:直接提交至 main
git checkout main
git commit -m "fix bug"
# 好:使用功能分支與 PR
# 不好:提交機密資訊
git add .env # 包含 API 金鑰
# 好:加入 .gitignore,使用環境變數
# 不好:巨大的 PR(超過 1000 行)
# 好:拆分成較小、聚焦的 PR
# 不好:「Update」提交訊息
git commit -m "update"
git commit -m "fix"
# 好:描述性訊息
git commit -m "fix(auth): resolve redirect loop after login"
# 不好:改寫公開歷史
git push --force origin main
# 好:使用 revert 處理公開分支
git revert HEAD
# 不好:長期存在的功能分支(數週/數月)
# 好:保持分支短暫(數天),經常重定基底
# 不好:…
[略…]