Gitワークフローパターン
Gitバージョン管理、ブランチ戦略、協調開発のベストプラクティス。
アクティベートすべきタイミング
- 新しいプロジェクトでGitワークフローを設定するとき
- ブランチ戦略(GitFlow、トランクベース、GitHub Flow)を決めるとき
- コミットメッセージやプルリクエストの説明を書くとき
- マージコンフリクトを解決するとき
- リリースとバージョンタグを管理するとき
- 新しいチームメンバーにGitプラクティスをオンボーディングするとき
ブランチ戦略
GitHub Flow(シンプル、ほとんどのチームにおすすめ)
継続的デプロイと小〜中規模チームに最適。
main (保護、常にデプロイ可能)
│
├── feature/user-auth → PR → mainにマージ
├── feature/payment-flow → PR → mainにマージ
└── fix/login-bug → PR → mainにマージ
ルール:
mainは常にデプロイ可能mainからフィーチャーブランチを作成- レビュー準備ができたらプルリクエストを開く
- 承認後、CIが通ったら
mainにマージ - マージ後すぐにデプロイ
トランクベース開発(高速度チーム向け)
強力なCI/CDとフィーチャーフラグを持つチームに最適。
main (トランク)
│
├── 短命なフィーチャーブランチ(最大1-2日)
├── 短命なフィーチャーブランチ
└── 短命なフィーチャーブランチ
ルール:
- 全員が
mainまたは非常に短命なブランチにコミット - フィーチャーフラグで未完成の作業を隠す
- マージ前にCIがパスすること
- 1日に複数回デプロイ
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、Webアプリ、スタートアップ |
| トランクベース | 5人以上の経験者 | 1日複数回 | 高速度チーム、フィーチャーフラグ |
| 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
The external API occasionally returns 503 errors during peak hours.
Added exponential backoff retry logic with max 3 attempts.
Closes #123"
コミットメッセージテンプレート
リポジトリルートに .gitmessage を作成:
# <type>(<scope>): <subject>
# # Types: feat, fix, docs, style, refactor, test, chore, perf, ci, revert
# Scope: api, ui, db, auth, etc.
# Subject: imperative mood, no period, max 50 chars
#
# [optional body] - explain why, not what
# [optional footer] - Breaking changes, closes #issue
有効化: git config commit.template .gitmessage
マージ vs リベース
マージ(履歴を保持)
# マージコミットを作成
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 (rewritten)
# * 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)
- すでにマージされたブランチ
# 理由: リベースは履歴を書き換え、他の人の作業を壊す
プルリクエストワークフロー
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変更の前/後のスクリーンショット。
## チェックリスト
- [ ] コードがプロジェクトのスタイルガイドラインに従っている
- [ ] 自己レビュー完了
- [ ] 複雑なロジックにコメントを追加
- [ ] ドキュメント更新
- [ ] 新しい警告が追加されていない
- [ ] テストがローカルでパス
- [ ] 関連するイシューがリンクされている
Closes #123
コードレビューチェックリスト
レビュアー向け:
- コードは問題を解決しているか?
- 処理されていないエッジケースはないか?
- コードは読みやすく、保守しやすいか?
- 十分なテストがあるか?
- セキュリティ上の懸念はないか?
- コミット履歴はクリーンか?(必要に応じてスカッシュ済みか)
作成者向け:
- レビュー依頼前に自己レビュー完了
- CIがパス(テスト、リント、型チェック)
- 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
# オプション1: 手動解決
# ファイルを編集し、マーカーを削除し、正しい内容を保持
# オプション2: マージツールを使用
git mergetool
# オプション3: 一方を受け入れる
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: バグ修正)
1.0.1 → 1.1.0 (minor: 新機能)
1.1.0 → 2.0.0 (major: 互換性のない変更)
リリースの作成
# 注釈付きタグを作成
git tag -a v1.2.0 -m "Release v1.2.0
Features:
- Add user authentication
- Implement password reset
Fixes:
- Resolve login redirect issue
Breaking Changes:
- None"
# タグをリモートにプッシュ
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設定
必須設定
# ユーザーID
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
# デフォルトのブランチ名
git config --global init.defaultBranch main
# pull動作(マージの代わりにリベース)
git config --global pull.rebase true
# push動作(現在のブランチのみをプッシュ)
git config --global push.default current
# タイプミスの自動修正
git config --global help.autocorrect 1
# より良いdiffアルゴリズム
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
# OSファイル
.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でプルリクエストを作成
新しい変更でPRを更新
# 1. 追加の変更を加える
git add .
git commit -m "feat(auth): add error handling"
# 2. 更新をプッシュ
git push origin feature/user-auth
フォークを上流と同期
# 1. 上流リモートを追加(一度だけ)
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. 自分のフォークにプッシュ
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 "New message"
# 最後のコミットにファイルを追加し忘れた場合
git add forgotten-file
git commit --amend --no-edit
Gitフック
Pre-Commitフック
#!/bin/bash
# .git/hooks/pre-commit
# リントを実行
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フック
#!/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
# 悪い例: 長命なフィーチャーブランチ(数週間/数ヶ月)
# 良い例: ブランチを短期間(数日)に保ち、頻繁にリベース
# 悪い例: コンフリクトを無視する(すべてoursを受け入れる)
git merge -X theirs feature/branch
# 良い例: コンフリクトを適切に解決する
# 悪い例: タグのみのリリース、チェンジログなし
# 良い例: 変更を文書化する
# 悪い例: レビューなしでPRをマージ
# 良い例: 常にコードレビューを必須にする