pruneコマンドとは
Gitのprune
コマンドは、リポジトリから不要になったオブジェクトやリモートブランチの参照を削除するためのコマンドです。主に以下の2つの用途があります。
- git prune: 到達不可能なオブジェクトを削除
- git remote prune: 削除されたリモートブランチの参照を削除
到達不可能なオブジェクトとは
- 削除されたブランチに含まれていたコミット
- リベースやリセットによって履歴から外れたコミット
- 一時的に作成されたが、最終的に使用されなかったオブジェクト
git pruneの基本
基本的な使い方
# 到達不可能なオブジェクトを削除
git prune
# 削除されるオブジェクトを確認(実際には削除しない)
git prune --dry-run
# より古いオブジェクトも含めて削除
git prune --expire=now
どんな時に使うのか
- リポジトリのサイズが大きくなりすぎた時
- 開発環境のメンテナンス時
git remote pruneの使い方
リモートブランチの参照を削除
# originリモートの削除されたブランチ参照を削除
git remote prune origin
# 全てのリモートに対して実行
git remote prune origin upstream
# 削除される参照を事前確認
git remote prune origin --dry-run
fetchと同時に実行
# fetchと同時にpruneも実行
git fetch --prune
# 設定でデフォルト動作にする
git config fetch.prune true
実践例
シナリオ1: リモートで削除されたブランチのローカル参照を削除
# 現在のリモートブランチ一覧を確認
git branch -r
# リモートで削除されたブランチの参照を削除
git remote prune origin
# 結果確認
git branch -r
シナリオ2: ローカルブランチも含めた完全クリーンアップ
# 1. リモート参照をクリーンアップ
git fetch --prune
# 2. マージ済みのローカルブランチを確認
git branch --merged main
# 3. 不要なローカルブランチを削除
git branch -d feature/completed-feature
# 4. オブジェクトのクリーンアップ
git gc --aggressive
git prune
シナリオ3: 定期メンテナンス用スクリプト
#!/bin/bash
# Git リポジトリクリーンアップスクリプト
echo "=== Git Repository Cleanup ==="
echo "1. Fetching with prune..."
git fetch --prune
echo "2. Cleaning up merged branches..."
git branch --merged main | grep -v main | xargs -n 1 git branch -d
echo "3. Running garbage collection..."
git gc --aggressive
echo "4. Pruning unreachable objects..."
git prune
echo "Cleanup completed!"
注意点
⚠️ 注意点
-
git pruneは慎重に使用
- 削除されたオブジェクトは復旧困難
- 必ず
--dry-run
で事前確認
-
共有リポジトリでの使用
# チーム開発では設定推奨 git config fetch.prune true git config remote.origin.prune true
-
リフログとの関係
# リフログも同時にクリーンアップ git reflog expire --expire=now --all git prune
まとめ
-
git prune
: 到達不可能なオブジェクトの削除 -
git remote prune
: リモートブランチ参照の削除 -
git fetch --prune
: fetch時に自動prune - 定期的なメンテナンスでリポジトリを健全に保つ
- 実行前は必ず
--dry-run
で確認する