17. .gitignoreの設定

バージョン管理から除外するファイルを指定する.gitignoreファイルの設定方法。 言語やフレームワーク別の一般的なパターンも紹介します。

.gitignoreの基本

プロジェクトルートに.gitignoreファイルを作成し、除外したいファイルのパターンを記述します。

基本的なパターン

# .gitignoreファイルの例

# コメントは#で開始

# 特定のファイルを無視
secrets.txt
config.local.js

# 特定のディレクトリを無視(末尾に/)
node_modules/
.cache/
dist/

# ワイルドカード
*.log
*.tmp
*.swp

# パスを指定
path/to/file.txt
path/to/directory/

# 再帰的に無視(**)
**/temp/
**/*.backup

# 否定(!で例外を指定)
*.log
!important.log  # important.logは追跡する

パターンのルール

# 空白行と#コメントは無視される

# 末尾のスペースは無視される(\でエスケープ)
file.txt   # スペースは無視
file.txt\  # 末尾スペースを含む

# /で始まるパターンはルートからのパス
/file.txt       # ルートのfile.txtのみ
file.txt        # 全てのfile.txt

# /で終わるパターンはディレクトリのみ
directory/      # directoryディレクトリとその中身

# **は任意のディレクトリ階層
**/logs/        # すべてのlogsディレクトリ
docs/**/*.pdf   # docs以下の全PDF

言語・フレームワーク別パターン

一般的な開発環境で除外すべきファイルのパターン例です。

Node.js / JavaScript

# 依存関係
node_modules/

# ビルド成果物
dist/
build/
out/
.next/
.nuxt/

# 環境変数
.env
.env.local
.env.*.local

# ログファイル
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# キャッシュ
.cache/
.parcel-cache/
.eslintcache

# IDE / エディタ
.vscode/
.idea/
*.swp
*.swo
*~

Python

# バイトコード
__pycache__/
*.py[cod]
*$py.class

# 仮想環境
venv/
env/
ENV/
.venv

# 配布 / パッケージング
build/
develop-eggs/
dist/
*.egg-info/

# Jupyter Notebook
.ipynb_checkpoints

# pytest
.pytest_cache/
.coverage

# mypy
.mypy_cache/

Java

# コンパイル済みクラス
*.class

# パッケージファイル
*.jar
*.war
*.ear

# Maven
target/
pom.xml.tag
pom.xml.releaseBackup

# Gradle
.gradle/
build/

# IntelliJ IDEA
.idea/
*.iml
*.iws

# Eclipse
.classpath
.project
.settings/

汎用的なパターン

# OS生成ファイル
.DS_Store
Thumbs.db
desktop.ini

# バックアップファイル
*.bak
*.backup
*~

# ログファイル
*.log
logs/

# 一時ファイル
*.tmp
*.temp
tmp/
temp/

# 機密情報
.env
secrets/
*.key
*.pem
credentials.json

.gitignoreの管理

.gitignoreファイルを効果的に管理する方法です。

# .gitignoreを作成してコミット
touch .gitignore
# ファイルを編集
git add .gitignore
git commit -m "Add .gitignore"

# 既に追跡されているファイルを削除(ローカルファイルは残す)
git rm --cached file.txt
git rm --cached -r directory/

# .gitignoreを追加後、既存ファイルを一括削除
git rm -r --cached .
git add .
git commit -m "Apply .gitignore to existing files"

# 特定のファイルが無視されるかテスト
git check-ignore -v file.txt

# グローバル.gitignore(ユーザー全体に適用)
git config --global core.excludesfile ~/.gitignore_global

# ローカルのみの除外(.git/info/exclude)
echo "local-only-file.txt" >> .git/info/exclude

便利なリソース

.gitignore のテンプレートを生成するサービスとリポジトリです。

# gitignore.io - 言語/IDE別の.gitignoreテンプレート生成
# https://www.toptal.com/developers/gitignore

# GitHubの.gitignoreテンプレート集
# https://github.com/github/gitignore

# コマンドラインで生成(gitignore.io API)
curl -L https://www.toptal.com/developers/gitignore/api/node,react,vscode > .gitignore

18. Git Hooks

特定のGitイベント発生時に自動実行されるスクリプト、Git Hooksの使い方。 コード品質の維持や自動化に役立ちます。

Hooksの種類と場所

Git Hooksは.git/hooks/ディレクトリに配置されます。

クライアント側フック

# .git/hooks/ディレクトリに配置

pre-commit         # コミット前に実行
prepare-commit-msg # コミットメッセージエディタ起動前
commit-msg         # コミットメッセージ検証
post-commit        # コミット後に実行
pre-rebase         # rebase前に実行
post-checkout      # checkout後に実行
post-merge         # マージ後に実行
pre-push           # push前に実行
pre-auto-gc        # 自動gc前に実行

サーバー側フック

pre-receive   # push受信前
update        # ブランチ更新時
post-receive  # push受信後
post-update   # ブランチ更新後

Hooksの作成例

実際に役立つHooksの実装例です。

pre-commit: コード検証

#!/bin/sh
# .git/hooks/pre-commit

# ESLintでJavaScriptをチェック
echo "Running ESLint..."
npm run lint
if [ $? -ne 0 ]; then
  echo "❌ ESLint failed. Please fix errors before committing."
  exit 1
fi

# Prettierでフォーマットチェック
echo "Checking code formatting..."
npm run format:check
if [ $? -ne 0 ]; then
  echo "❌ Code formatting issues found. Run 'npm run format' to fix."
  exit 1
fi

echo "✅ All checks passed!"
exit 0

commit-msg: コミットメッセージ検証

#!/bin/sh
# .git/hooks/commit-msg

COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")

# Conventional Commits形式を強制
PATTERN="^(feat|fix|docs|style|refactor|test|chore)(\\(.+\\))?: .{1,}"

if ! echo "$COMMIT_MSG" | grep -qE "$PATTERN"; then
  echo "❌ Invalid commit message format!"
  echo ""
  echo "Format: type(scope): description"
  echo ""
  echo "Types:"
  echo "  feat:     New feature"
  echo "  fix:      Bug fix"
  echo "  docs:     Documentation changes"
  echo "  style:    Code style changes (formatting, etc.)"
  echo "  refactor: Code refactoring"
  echo "  test:     Test changes"
  echo "  chore:    Build/tooling changes"
  echo ""
  echo "Example: feat(auth): add login functionality"
  exit 1
fi

exit 0

pre-push: テスト実行

#!/bin/sh
# .git/hooks/pre-push

# テストを実行
echo "Running tests..."
npm test
if [ $? -ne 0 ]; then
  echo "❌ Tests failed. Push aborted."
  exit 1
fi

# mainブランチへの直接pushを禁止
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" = "main" ] || [ "$BRANCH" = "master" ]; then
  echo "❌ Direct push to $BRANCH is not allowed!"
  echo "Please create a feature branch and open a PR."
  exit 1
fi

echo "✅ Pre-push checks passed!"
exit 0

Hooksの有効化

Hooksスクリプトを有効化する手順です。

# Hookスクリプトを作成
touch .git/hooks/pre-commit

# 実行権限を付与
chmod +x .git/hooks/pre-commit

# Hookをテスト
.git/hooks/pre-commit

# Hookを一時的にスキップ
git commit --no-verify
git commit -n

git push --no-verify
git push -n

HuskyでHooksを管理

Huskyを使用すると、Hooksをチーム全体で共有しやすくなります。

# Huskyのインストール(Node.jsプロジェクト)
npm install --save-dev husky
npx husky init

# Hookを追加
npx husky add .husky/pre-commit "npm test"
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'

# package.jsonに設定
{
  "scripts": {
    "prepare": "husky install"
  }
}

# lint-stagedと組み合わせてステージングされたファイルのみlint
npm install --save-dev lint-staged

# package.json
{
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
    "*.{css,scss}": ["prettier --write"],
    "*.{json,md}": ["prettier --write"]
  }
}

# .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged

19. 実務で役立つTips

実際の開発現場で役立つベストプラクティスやトラブルシューティング。 コミットメッセージの書き方、ブランチ戦略などを紹介します。

コミットメッセージのベストプラクティス

良いコミットメッセージは、プロジェクトの履歴を理解しやすくします。

Conventional Commits

# 形式
type(scope): subject

body

footer

# 例
feat(auth): add JWT authentication

Implement JWT-based authentication system:
- Add login endpoint
- Create token verification middleware
- Update user model

Closes #123

# 主なtype
feat:     新機能
fix:      バグ修正
docs:     ドキュメントのみの変更
style:    コードの意味に影響しない変更(空白、フォーマットなど)
refactor: リファクタリング
test:     テストの追加・修正
chore:    ビルドプロセスやツールの変更
perf:     パフォーマンス改善
ci:       CIの変更
build:    ビルドシステムの変更
revert:   以前のコミットを元に戻す

良いコミットメッセージのルール

# ✅ 良い例
feat: add user registration form
fix: resolve memory leak in data processing
docs: update API documentation for v2.0

# ❌ 悪い例
fixed stuff
update
WIP
aaa

# ルール
1. 一行目は50文字以内
2. 一行目と本文は空行で区切る
3. 一行目は命令形("Add"、"Fix"など)
4. 本文は72文字で改行
5. 「Why」を説明(「What」だけでなく)
6. Issue番号を参照
7. 破壊的変更はBREAKING CHANGE:を明記

ブランチ戦略

プロジェクトの規模やチームに合わせたブランチ戦略を選択しましょう。

GitHub Flow(シンプル)

# 小規模チーム、高頻度デプロイに適している

1. mainブランチは常にデプロイ可能状態
2. 新機能はmainからブランチを作成
3. 定期的にpushしてバックアップ
4. Pull Requestでレビュー
5. mainにマージ後、すぐにデプロイ

Git Flow(複雑)

# 大規模プロジェクト、計画的リリースに適している

メインブランチ:
- main/master: 本番環境のコード
- develop: 開発中のコード

サポートブランチ:
- feature/*: 新機能開発
- release/*: リリース準備
- hotfix/*: 緊急修正

Trunk-Based Development

# 高頻度インテグレーション

1. メインブランチ(trunk)に直接コミット
2. ブランチは短命(1日以内)
3. Feature Flagで未完成機能を管理
4. 自動テストが充実

トラブルシューティング

よくある問題とその解決方法です。

間違ったファイルをコミットしてしまった

# 直前のコミットからファイルを削除
git rm --cached unwanted-file.txt
git commit --amend --no-edit

# 過去のコミットから削除(履歴を書き換え)
git filter-branch --tree-filter 'rm -f unwanted-file.txt' HEAD

大きなファイルを誤ってコミット

# BFG Repo-Cleanerを使用(推奨)
bfg --delete-files large-file.zip
git reflog expire --expire=now --all
git gc --prune=now --aggressive

# Git LFSに移行
git lfs install
git lfs track "*.zip"
git add .gitattributes
git add large-file.zip
git commit --amend

コミットを間違ったブランチにしてしまった

# 1. 正しいブランチを作成
git branch correct-branch

# 2. 間違ったブランチをリセット
git reset --hard HEAD~1

# 3. 正しいブランチに切り替え
git checkout correct-branch

パフォーマンス最適化

大規模リポジトリでのGitパフォーマンスを改善する方法です。

# 浅いクローン(履歴を制限)
git clone --depth 1 https://github.com/user/repo.git

# 部分クローン(特定フォルダのみ)
git clone --filter=blob:none --sparse https://github.com/user/repo.git
cd repo
git sparse-checkout init --cone
git sparse-checkout set path/to/needed/folder

# ガベージコレクションで最適化
git gc --aggressive --prune=now

# ファイルシステムモニタを有効化(大規模リポジトリ)
git config core.fsmonitor true
git config core.untrackedcache true

セキュリティベストプラクティス

機密情報の扱いとコミット署名の基本です。

# 機密情報をコミットしない
# - .envファイルは.gitignoreに追加
# - APIキーやパスワードをハードコードしない
# - 秘密鍵(.key, .pem)をコミットしない

# コミットに署名(GPG)
git config --global user.signingkey YOUR_GPG_KEY_ID
git config --global commit.gpgsign true
git commit -S -m "Signed commit"

# 機密情報を間違ってコミットした場合
# 1. 直ちに.gitignoreに追加
# 2. 履歴から完全に削除
# 3. キー/パスワードを変更
# 4. リモートにプッシュ済みなら報告

20. GitHub固有の操作

GitHub CLIやPull Requestの作成など、GitHub固有の機能とGitコマンドの組み合わせ。 現代的な開発フローで必須の知識です。

GitHub CLI (gh)

GitHub CLIを使用すると、コマンドラインからGitHubの操作ができます。

インストール

# macOS (Homebrew)
brew install gh

# Windows (Scoop)
scoop install gh

# Linux (Debian/Ubuntu)
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
sudo apt update
sudo apt install gh

# 認証
gh auth login

Pull Request操作

# PRを作成
gh pr create --title "Add new feature" --body "Description of changes"

# 対話形式でPR作成
gh pr create

# PRの一覧
gh pr list

# PRをチェックアウト
gh pr checkout 123

# PRの詳細を表示
gh pr view 123

# PRをブラウザで開く
gh pr view 123 --web

# PRをマージ
gh pr merge 123

# PRを閉じる
gh pr close 123

# レビューを追加
gh pr review 123 --approve
gh pr review 123 --request-changes --body "Please fix..."
gh pr review 123 --comment --body "Looks good!"

Issue操作

# Issueを作成
gh issue create --title "Bug report" --body "Description"

# Issueの一覧
gh issue list

# Issueを表示
gh issue view 456

# Issueを閉じる
gh issue close 456

# Issueにコメント
gh issue comment 456 --body "Working on this"

リポジトリ操作

# リポジトリを作成
gh repo create my-project --public
gh repo create my-project --private

# リポジトリをクローン
gh repo clone user/repository

# リポジトリをフォーク
gh repo fork user/repository

# リポジトリをブラウザで開く
gh repo view --web

GitHub Actionsとの連携

GitHub Actionsをコマンドラインから操作できます。

# Workflowの一覧
gh workflow list

# Workflowを実行
gh workflow run ci.yml

# Workflowの実行結果を表示
gh run list
gh run view 123456

# Workflowのログを表示
gh run view 123456 --log

GitHub固有の.git設定

GitHubとの連携をスムーズにする設定です。

# GitHubのユーザー名を設定
git config --global github.user "your-username"

# SSH接続をデフォルトに
git config --global url."git@github.com:".insteadOf "https://github.com/"

# PRブランチを取得できるようにする
git config --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/origin/pr/*'
git fetch origin
git checkout origin/pr/123

# デフォルトブランチをmainに
git config --global init.defaultBranch main

便利なGitHub機能

Web 上での編集やバッジ表示など、よく使う機能の例です。

GitHub上でファイルを直接編集

# URLに.github.devを付けるor 「.」キーを押す
https://github.com/user/repo
↓
https://github.dev/user/repo

# VSCodeがweb上で起動し、直接編集可能

特定のコミットでファイルを参照

# URLにcommit SHAを含める
https://github.com/user/repo/blob/abc123/path/to/file.js

# 行番号を指定
https://github.com/user/repo/blob/main/file.js#L10-L20

READMEでバッジを表示

# CIステータス
![CI](https://github.com/user/repo/workflows/CI/badge.svg)

# カバレッジ
![Coverage](https://codecov.io/gh/user/repo/branch/main/graph/badge.svg)

# ライセンス
![License](https://img.shields.io/github/license/user/repo)

ベストプラクティス

PR・Issue・リポジトリ運用のポイントです。

# Pull Requestのベストプラクティス

1. 小さく保つ(変更行数を少なく)
2. 明確なタイトルと説明
3. 関連Issueをリンク
4. レビューアを指定
5. CIが通ってからマージ依頼
6. マージ後はブランチを削除
7. Draft PRを活用して早めにフィードバック

# Issueのベストプラクティス

1. 再現手順を明記
2. 環境情報を追加
3. スクリーンショットを添付
4. ラベルで分類
5. テンプレートを活用

# コラボレーション

1. CODE_OF_CONDUCT.mdを追加
2. CONTRIBUTING.mdで貢献方法を説明
3. Issue/PRテンプレートを設定
4. READMEを充実させる
5. ライセンスを明記