Git: Gitのベストプラクティスとチームコラボレーションガイド
Gitの適切な活用は、チームの連携やコードの品質を大幅に向上させることができます。このセクションでは、コミットのガイドライン、ブランチ戦略、ワークフロー、チームでの連携など、Gitのベストプラクティスをまとめます。
1. 投稿ガイドライン
(1) 標準化されたコミット情報はなぜ必要なのか?
適切な形式で提出された情報は、次のようなメリットがあります:
- 変更点を明確に記述する:各コミットに何が含まれているかを素早く把握できるようにする
- 自動化ツールのサポート:変更履歴を自動的に生成する
- 履歴の追跡が簡単:特定の機能の開発記録を検索できます
- コラボレーションの効率向上:コミュニケーションコストの削減
(2) 従来のコミット規格
現在、最も一般的なコミットメッセージの記述規則は以下の通りです:
TEXT
📖 参照専用
<type>(<scope>): <subject>
<body>
<footer>
各セクションの説明:
- タイプ(必須):提出の種類
- 範囲(任意):影響の範囲
- 件名(必須):簡単な説明(50文字以内)
- 本文(任意):詳細な説明
- フッター(任意):フッター情報(例:「イシューを閉じる」)
(3) 提出形式の詳細な説明
| 種類 | 説明 | 例 |
|---|---|---|
| feat | 新機能 | feat: ユーザーログイン機能を追加 |
| 修正 | バグ修正 | 修正:ログイン認証エラーを修正しました |
| docs | ドキュメントの更新 | docs: API ドキュメントの更新 |
| スタイル | コードの書式設定 | スタイル:コードのインデントを調整 |
| リファクタリング | リファクタリング | リファクタリング:クエリロジックの最適化 |
| perf | パフォーマンスの最適化 | perf: データベースクエリの最適化 |
| test | テスト | test: ユニットテストを追加 |
| タスク | ビルド/ツール | タスク: ビルド設定の更新 |
| ci | CIの設定 | ci: GitHub Actionsの追加 |
| 元に戻す | 元に戻す | 元に戻す:ログイン機能を元に戻す |
▶ サンプル:適切なコミットメッセージ
BASH
# Single-line commit
git commit -m "feat: Add User Login Functionality"
# Range-Based Submissions
git commit -m "feat(auth): AddJWTCertification Support"
# Multi-line commit
git commit -m "feat(auth): AddOAuth2.0Login Support" -m "- SupportGoogle、GitHubLog In" -m "- Add Login State Persistence" -m "Closes #123"
# Use the editor to write a detailed commit message
git commit
(4) 情報提出に関するベストプラクティス
適切なコミットメッセージ:
TEXT
📖 参照専用
feat(auth): AddOAuth2.0Login Support
- SupportGoogle、GitHub、WeChat Third-Party Login
- Add Login State Persistence
- Enable Auto-RefreshTokenMechanism
Closes #456
不適切なコミットメッセージ:
TEXT
📖 参照専用
update
fix bug
I made a few changes.
WIP
asdfasdf
ベストプラクティス:
- ✅ 命令形を使う(「Added」の代わりに「Add」とする)
- ✅ 最初の文字を小文字にする
- ✅ 文末にピリオドを付けないでください
- ✅ テーマを50文字以内で説明してください
- ✅ 「Body」のセクションでは、「何」と「なぜ」について説明しており、「どのように」については説明していません
2. 分岐戦略
(1) Git Flowモデル
Git Flow は、最も代表的なブランチ戦略です:
graph TB
main[main<br/>Production Environment] --> release[release/*<br/>Preparing for Release]
release --> develop[develop<br/>Development Environment]
develop --> feature[feature/*<br/>Feature Development]
main --> hotfix[hotfix/*<br/>Emergency Fix]
style main fill:#d4edda
style develop fill:#fff3cd
style feature fill:#e1f5ff
style hotfix fill:#f8d7da
支店種別:
- main: 本番環境用のコード。常にデプロイ可能な状態に保たれている
- 開発:開発環境でコードを開発し、さまざまな機能ブランチを統合する
- feature: 「develop」ブランチから作成された機能開発ブランチ
- リリース:
developから作成された、リリース準備完了のブランチ - ホットフィックス: main ブランチから作成された緊急修正ブランチ
▶ サンプル:Git Flow のワークフロー
BASH
# 1. Create a feature branch from develop
git checkout develop
git checkout -b feature/user-auth
# 2. Develop and Submit
git add .
git commit -m "feat(auth): Add User Authentication"
# 3. Merge back intodevelop
git checkout develop
git merge --no-ff feature/user-auth
git branch -d feature/user-auth
# 4. Create a release branch
git checkout -b release/v1.0.0
# 5. Preparing for Release(FixBug、Update version numbers, etc.)
git commit -m "chore: Update the version number to1.0.0"
# 6. Merge into main and develop
git checkout main
git merge --no-ff release/v1.0.0
git tag -a v1.0.0 -m "Version 1.0.0"
git checkout develop
git merge --no-ff release/v1.0.0
git branch -d release/v1.0.0
# 7. Emergency Fix
git checkout main
git checkout -b hotfix/critical-bug
git commit -m "fix: Urgent FixBug"
git checkout main
git merge --no-ff hotfix/critical-bug
git tag -a v1.0.1 -m "Version 1.0.1"
git checkout develop
git merge --no-ff hotfix/critical-bug
git branch -d hotfix/critical-bug
(2) GitHubフローモデル
GitHub Flowはよりシンプルで、継続的デプロイに適しています:
graph LR
A[main<br/>Always deployable] --> B[featureBranch]
B --> C[Pull Request]
C --> D[Merge intomain]
D --> E[Automatic Deployment]
style A fill:#d4edda
style E fill:#c3e6cb
特長:
- メインブランチは常にデプロイ可能です
mainから機能ブランチを作成する- 開発が完了したら、プルリクエストを作成してください
- レビュー後にmainブランチにマージする
- マージ後の自動デプロイ
▶ サンプル:GitHub Flow ワークフロー
BASH
# 1. Update Locallymain
git checkout main
git pull origin main
# 2. Create a feature branch
git checkout -b feature/new-feature
# 3. Develop and Submit
git add .
git commit -m "feat: Add a New Feature"
# 4. Push Branch
git push -u origin feature/new-feature
# 5. Create a Pull Request on GitHub
# 6. Merge after the code review is approved
# 7. Clean Up Branches
git checkout main
git pull origin main
git branch -d feature/new-feature
git push origin --delete feature/new-feature
(3) ブランチの命名規則
| ブランチの種類 | 命名規則 | 例 |
|---|---|---|
| 機能 | feature/* | feature/user-authentication |
| バグ修正 | fix/* | fix/login-validation |
| ホットフィックス | hotfix/* | hotfix/security-vulnerability |
| リリース | release/* | release/v1.0.0 |
| 実験 | experiment/* | experiment/new-architecture |
3. ワークフロー
(1) 日常の開発ワークフロー
sequenceDiagram
participant Developer
participant Local Warehouse
participant Remote Repository
participant CI/CD
Developer->>Local Warehouse: git pullUpdate the code
Developer->>Local Warehouse: Create a feature branch
Developer->>Local Warehouse: Develop and Submit
Developer->>Remote Repository: git pushPush Branch
Developer->>Remote Repository: CreatePull Request
Remote Repository->>CI/CD: Automated Testing
CI/CD->>Remote Repository: Test Passed
Remote Repository->>Local Warehouse: Merge intomain
Developer->>Local Warehouse: git pullSynchronize
(2) 機能開発プロセス
▶ サンプル:機能開発プロセスの全容
BASH
# 1. Start Developing New Features
git checkout main
git pull origin main
git checkout -b feature/user-profile
# 2. Submit Regularly(Iterate quickly)
git add src/profile.js
git commit -m "feat(profile): Add User Profile Page"
git add src/api/profile.js
git commit -m "feat(profile): Add InformationAPIInterface"
git add src/test/profile.test.js
git commit -m "test(profile): Add Unit Tests"
# 3. Stay in touch withmainSynchronize
git fetch origin
git rebase origin/main
# 4. Push and CreatePR
git push -u origin feature/user-profile
# 5. PRMerge after approval
# 6. Cleanup
git checkout main
git pull origin main
git branch -d feature/user-profile
(3) バグ修正プロセス
▶ サンプル:バグ修正のプロセス
BASH
# 1. Create a fix branch from main
git checkout main
git pull origin main
git checkout -b fix/login-error
# 2. Identify and FixBug
# View logs to troubleshoot issues
git log --grep="login"
# Fix the code
git add src/auth.js
git commit -m "fix(auth): Fix the login authentication error
- Fix the validation logic for empty passwords
- Add an input length check
Fixes #789"
# 3. Push and CreatePR
git push -u origin fix/login-error
# 4. Post-merger cleanup
git checkout main
git pull origin main
git branch -d fix/login-error
4. チームワーク能力
(1) コードレビュー
プルリクエストのベストプラクティス:
プルリクエストを作成する際は:
- ✅ PRのタイトルと説明文をわかりやすく書く
- ✅ 関連する課題へのリンク
- ✅ PRは小規模で、焦点を絞ったものにする(コード行数400行未満)
- ✅ CIテストが正常に実行されることを確認する
- ✅ 必要なスクリーンショットやデモを追加してください
プルリクエストをレビューする際は:
- ✅ コードの品質とロジックを確認する
- ✅ ローカルテストを実行する
- ✅ 建設的なフィードバックを提供する
- ✅ レビューのコメントには迅速に対応する
▶ サンプル:PRの説明文テンプレート
MARKDOWN
**Feature Description**
Add User Profile Page,Supports viewing and editing user information。
**Details of the Changes**
- New Profile Components
- Add Information Edit Form
- Implement the profile picture upload feature
- Add Unit Tests
**Test**
- [x] Unit tests passed
- [x] Manual testing completed
- [x] Responsive Layout Testing
**Screenshot**
[Add a screenshot]
**RelatedIssue**
Closes #123
(2) 紛争解決の戦略
▶ サンプル:対立の予防と解決
BASH
# Conflict Prevention
# 1. Synchronize remote code frequently
git fetch origin
git rebase origin/main
# 2. Iterate quickly,Frequent Submissions
# Commit after completing each small feature
# 3. Timely Communication,Scope of Coordinated Revisions
# Resolving Conflicts
# 1. Pull the latest code
git pull --rebase origin main
# 2. Resolving Conflicts
# Editing Files with Conflicts,Keep the correct content
# 3. Mark the conflict as resolved
git add .
# 4. Continuerebase
git rebase --continue
# 5. Push
git push origin feature
(3) 履歴を整理しておく
▶ サンプル:整理されたコミット履歴
BASH
# UsagerebaseMerge Commit
git rebase -i HEAD~3
# In the editor:
# pick a1b2c3d feat: Add FeatureA
# squash d4e5f6g feat: Improve functionalityA
# squash h7i8j9k feat: Optimization FeaturesA
# Edit the merged commit message after saving
# feat: Add FeatureA
# Usagerebaserather thanmerge
git pull --rebase origin main
# View the complete history
git log --oneline --graph
# Output:
# * a1b2c3d feat: Add FeatureC
# * d4e5f6g feat: Add FeatureB
# * h7i8j9k feat: Add FeatureA
5. Gitの設定に関するベストプラクティス
(1) 推奨されるグローバル設定
▶ サンプル:Gitの設定
BASH
# User Information
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Default Editor
git config --global core.editor "code --wait"
# Default branch name
git config --global init.defaultBranch main
# Automatic Line Break Conversion
git config --global core.autocrlf input # Linux/Mac
git config --global core.autocrlf true # Windows
# Pull Strategy
git config --global pull.rebase true
# Push Strategy
git config --global push.default simple
# Voucher Storage
git config --global credential.helper store
# Alias Configuration
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.lg "log --oneline --graph --all"
(2) .gitignore の設定
▶ サンプル:完全な .gitignore ファイル
TEXT
📖 参照専用
# Dependency Directory
node_modules/
vendor/
venv/
# Compilation Output
dist/
build/
out/
*.o
*.class
*.jar
*.exe
# IDELayout
.vscode/
.idea/
*.swp
*.swo
.DS_Store
# Environment Configuration
.env
.env.local
.env.*.local
config.local.js
# Log Files
*.log
logs/
npm-debug.log*
yarn-debug.log*
# Test Coverage
coverage/
.nyc_output/
# Temporary Files
tmp/
temp/
*.tmp
*.temp
# Operating System Files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
(3) Gitフック
▶ サンプル:pre-commit フック
BASH
#!/bin/bash
# .git/hooks/pre-commit
# Run Code Check
npm run lint
if [ $? -ne 0 ]; then
echo "❌ Code check failed,Please fix it and then submit it."
exit 1
fi
# Run Test
npm test
if [ $? -ne 0 ]; then
echo "❌ Test Failed,Please fix it and then submit it."
exit 1
fi
echo "✅ Code review and testing passed"
exit 0
6. よくある質問と解決策
(1) よくあるエラーへの対処
▶ サンプル:エラー処理
BASH
# Error1:Push Rejected
git push origin main
# ! [rejected] main -> main (fetch first)
# Resolve:
git pull --rebase origin main
git push origin main
# Error2:Merge Conflicts
git merge feature
# CONFLICT (content): Merge conflict in file.js
# Resolve:
# Editing Files with Conflicts
git add file.js
git commit
# Error3:detached HEAD
git checkout a1b2c3d
# You are in 'detached HEAD' state
# Resolve:
git switch -c new-branch
# Error4:Accidentally Deleted a Branch
git branch -D feature
# Restore:
git reflog
git checkout -b feature <commit-id>
(2) パフォーマンスの最適化
▶ サンプル:Gitのパフォーマンスを最適化する
BASH
# Optimizing the Performance of Large Repositories
git gc --aggressive
# Partial Clone(Large Warehouse)
git clone --filter=blob:none --sparse <url>
git sparse-checkout init --cone
git sparse-checkout add src/
# Shallow Cloning(Only the most recent history is needed)
git clone --depth=1 <url>
# Disable File Mode Change Detection(Windows)
git config core.fileMode false
❓ よくある質問
Q コミット履歴を整理しておくにはどうすればよいですか?
A
git rebase -i を使用して関連するコミットをマージし、「merge」の代わりに git pull --rebase を使用し、明確なコミットメッセージを記述し、意味のないコミットは避けるようにしてください。Q Git FlowとGitHub Flow、どちらを使うべきですか?
A Git Flowは明確なリリースサイクルがあるプロジェクトに適しており、GitHub Flowは継続的デプロイを行うプロジェクトに適しています。小規模なプロジェクトの場合は、GitHub Flowの方がシンプルで効率的であるため、こちらをお勧めします。
Q 長期的な機能開発にはどのように取り組むべきでしょうか?
A main/develop からの更新を定期的にマージして同期を保ち、フィーチャーフラグを使って機能の有効化を制御し、主要な機能を小さなプルリクエストに分割して段階的にマージするようにします。
Q マージの競合を避けるにはどうすればよいですか?
A リモートコードを頻繁に同期し、小さく素早いステップで頻繁にコミットを行い、変更の範囲を調整するために迅速にコミュニケーションを取り、
mergeの代わりにrebaseを使用してください。Q 情報はどの言語で提出すべきですか?
A 国際基準に準拠し、オープンソースでの協業を円滑にするため、英語の使用をお勧めします。チーム内のプロジェクトでは中国語を使用することも可能ですが、その場合は一貫性を保つ必要があります。
📖 まとめ
- コミットガイドライン:「Conventional Commits」のガイドラインに従い、明確なコミットメッセージを記述してください
- ブランチ戦略:Git Flowはリリースサイクルのあるプロジェクトに適しており、GitHub Flowは継続的デプロイに適しています
- ワークフロー:迅速に反復開発を行い、頻繁にコミットし、定期的に同期を取り、コードレビューを実施する
- チームでの連携:PRのレビュー、競合の解決、履歴の整理
- Gitの設定:効率化を図るために、エイリアス、認証情報、フックを設定する
- ベストプラクティス:標準化されたプロセス、明確なコミュニケーション、継続的な学習
📝 練習問題
-
基本演習:ユーザー情報、エイリアス、エディタなどを含むGit環境をセットアップし、ベストプラクティスに沿ったコミットメッセージを作成し、Gitの適切な使用習慣を身につけます。
-
応用演習:GitHub Flowのワークフローをすべて実践します。機能ブランチの作成、機能の開発、プルリクエストの作成(シミュレーション)、ブランチのマージ、ブランチのクリーンアップを行い、チームでの共同作業のプロセスを体験してください。
-
課題:チームメンバーがGitの正しい習慣を身につけられるよう、コミットのガイドライン、ブランチ作成のポリシー、ワークフロー、よくある問題への対処法などを盛り込んだGitユーザーガイドを作成してください。
🎉 おめでとうございます!Gitのチュートリアルをすべて完了し、バージョン管理の基本スキルを習得しました!
今後の研究に向けた提言:
- Gitの内部メカニズムに関する詳細な研究
- 高度な機能を探る:サブモジュール、ワークツリー、およびブランチのフィルタリング
- Gitサーバーの設定方法について学ぶ:GitLab、Gitea
- Gitと他のツール(CI/CD、IDEなど)との連携について学ぶ