Git・GitHubとは?バージョン管理の重要性
Gitは世界中のエンジニアが使うバージョン管理システムです。コードの変更履歴管理・チーム開発・リリース管理まで、現代の開発に不可欠なツールです。本記事では、Gitの基礎コマンドから高度なワークフローまで体系的に解説します。
Gitの基本コマンド完全リファレンス
初期設定
# ユーザー設定(初回必須)
git config --global user.name "あなたの名前"
git config --global user.email "your@email.com"
git config --global core.editor "code --wait" # VS Code
git config --global init.defaultBranch main
# 設定確認
git config --list
リポジトリ操作の基本
# リポジトリ初期化
git init
# クローン
git clone https://github.com/username/repo.git
git clone https://github.com/username/repo.git my-folder # フォルダ名指定
# ステータス確認
git status
git status -s # 短縮表示
# 変更の確認
git diff # ステージ前の変更
git diff --staged # ステージ済みの変更
git diff HEAD # 最新コミットとの比較
# ステージング
git add . # 全ファイル
git add -p # 変更を対話的に選択
git add src/ # ディレクトリ指定
# コミット
git commit -m "feat: ログイン機能を追加"
git commit --amend # 直前のコミットを修正
ブランチ戦略:GitHubフローとGit-flow
GitHubフロー(推奨・シンプル)
# ブランチ作成・切り替え
git checkout -b feature/user-authentication
# または
git switch -c feature/user-authentication
# ブランチ一覧
git branch -a
# リモートへプッシュ
git push -u origin feature/user-authentication
# マージ(GitHubのPull Requestで行うことが多い)
git checkout main
git merge feature/user-authentication
git push origin main
# ブランチ削除
git branch -d feature/user-authentication
git push origin --delete feature/user-authentication
Gitのリセット・巻き戻し
# 直前のコミットを取り消し(変更は保持)
git reset HEAD~1
git reset --soft HEAD~1 # ステージングに残す
# 完全に元に戻す(注意:変更が消える)
git reset --hard HEAD~1
# 特定ファイルの変更を元に戻す
git checkout -- filename.txt
# または(Git 2.23+)
git restore filename.txt
# コミットの取り消し(安全な方法・履歴を残す)
git revert HEAD
git revert <commit-hash>
便利なGitコマンド・エイリアス
# 一時的に変更を退避
git stash
git stash save "作業中のログイン機能"
git stash list
git stash pop
# コミットログをグラフ表示
git log --oneline --graph --all --decorate
# おすすめエイリアス設定
git config --global alias.lg "log --oneline --graph --all --decorate"
git config --global alias.st "status -s"
git config --global alias.co "checkout"
git config --global alias.br "branch"
コミットメッセージのベストプラクティス
チームでの開発では、わかりやすいコミットメッセージが非常に重要です。Conventional Commits形式が広く採用されています:
# 形式: type(scope): description
# 例:
feat(auth): JWTによるログイン機能を実装
fix(api): ユーザー検索のN+1問題を解決
docs(readme): インストール手順を更新
refactor(db): クエリのパフォーマンスを改善
test(user): ユーザー登録のユニットテストを追加
chore(deps): React 19にアップグレード
GitHubの便利機能
- Pull Request:コードレビューと議論の場
- GitHub Actions:CI/CDの自動化
- GitHub Copilot:AIコーディング支援
- GitHub Projects:タスク管理・スプリント計画
- GitHub Security:Dependabot・Code Scanning
まとめ
Gitは習得に時間がかかりますが、日々の実践で必ず身につきます。まず基本コマンド(add・commit・push・pull)をマスターし、ブランチ戦略を理解することで、チーム開発が格段にスムーズになります。