HxHippy

Git Repository Cleanup

Clean up Git repositories: prune branches, remove untracked files, optimize repo size.

Last updated: 2024-12-15

Overview

Maintain clean Git repositories by removing merged branches, pruning remote tracking branches, cleaning untracked files, and optimizing repository size.

The Script

#!/bin/bash
# Git Repository Cleanup Script

set -euo pipefail

DO_BRANCHES=false
DO_REMOTE=false
DRY_RUN=false

# Verify we're in a git repository
if ! git rev-parse --git-dir &>/dev/null; then
    echo "Error: Not a git repository"
    exit 1
fi

MAIN_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@' || echo "main")

# Get repository stats
echo "Repository: $(basename "$(git rev-parse --show-toplevel)")"
echo "Current branch: $(git branch --show-current)"
echo "Main branch: $MAIN_BRANCH"
echo "Remote: $(git remote get-url origin 2>/dev/null || echo "none")"

# Count items
LOCAL_BRANCHES=$(git branch | wc -l)
REMOTE_BRANCHES=$(git branch -r | wc -l)

echo "Local branches: $LOCAL_BRANCHES"
echo "Remote branches: $REMOTE_BRANCHES"
echo "Repo size: $(du -sh .git | cut -f1)"

# Clean merged branches
if [ "$DO_BRANCHES" = true ]; then
    MERGED_BRANCHES=$(git branch --merged "$MAIN_BRANCH" | grep -vE "^\\*|\\s*(main|master|develop)$" || true)

    if [ -z "$MERGED_BRANCHES" ]; then
        echo "No merged branches to remove"
    else
        echo "Branches merged into $MAIN_BRANCH:"
        echo "$MERGED_BRANCHES"
    fi
fi

echo "Cleanup complete!"
echo "New repo size: $(du -sh .git | cut -f1)"

Usage

# Preview all cleanup actions
./git-cleanup.sh -a -d

# Remove merged branches
./git-cleanup.sh -b

# Full cleanup without prompts
./git-cleanup.sh -a -f

# Just garbage collection
./git-cleanup.sh -g

Quick Commands

# Delete merged branches (one-liner)
git branch --merged main | grep -vE "^\\*|main|master" | xargs -r git branch -d

# Prune remote branches
git remote prune origin

# Aggressive garbage collection
git gc --aggressive --prune=now

# Remove all untracked files
git clean -fd
beginner Development Updated 2024-12-15
  • git
  • cleanup
  • branches
  • prune
  • gc
  • repository
  • maintenance