2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Git】prune便利じゃん!

Posted at

pruneコマンドとは

Gitのpruneコマンドは、リポジトリから不要になったオブジェクトやリモートブランチの参照を削除するためのコマンドです。主に以下の2つの用途があります。

  1. git prune: 到達不可能なオブジェクトを削除
  2. 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!"

注意点

⚠️ 注意点

  1. git pruneは慎重に使用

    • 削除されたオブジェクトは復旧困難
    • 必ず--dry-runで事前確認
  2. 共有リポジトリでの使用

    # チーム開発では設定推奨
    git config fetch.prune true
    git config remote.origin.prune true
    
  3. リフログとの関係

    # リフログも同時にクリーンアップ
    git reflog expire --expire=now --all
    git prune
    

まとめ

  • git prune: 到達不可能なオブジェクトの削除
  • git remote prune: リモートブランチ参照の削除
  • git fetch --prune: fetch時に自動prune
  • 定期的なメンテナンスでリポジトリを健全に保つ
  • 実行前は必ず--dry-runで確認する
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?