maintenance Git Command Guide
The git maintenance command runs tasks to optimize Git repository data, speeding up Git commands and reducing storage requirements. It provides flexible scheduling for repository optimization tasks that user-facing commands defer for performance reasons.
git maintenance Syntax:
Section titled “git maintenance Syntax:”git maintenance run [<options>]git maintenance start [--scheduler=<scheduler>]git maintenance (stop|register|unregister) [<options>]Subcommands:
Section titled “Subcommands:”Repository Management:
Section titled “Repository Management:”| Subcommand | Description |
|---|---|
run [<options>] | Run one or more maintenance tasks |
start [--scheduler=<scheduler>] | Start background maintenance scheduling |
stop | Halt background maintenance schedule |
register | Add repository to maintenance schedule |
unregister | Remove repository from maintenance schedule |
Maintenance Options:
Section titled “Maintenance Options:”| Option | Description |
|---|---|
--task=<task> | Specify maintenance task to run |
--schedule=<frequency> | Set maintenance frequency |
--scheduler=<type> | Scheduler type (launchd |
--quiet | Suppress output |
Maintenance Tasks:
Section titled “Maintenance Tasks:”Data Optimization Tasks:
Section titled “Data Optimization Tasks:”| Task | Description |
|---|---|
gc | Clean up unnecessary files and optimize repository |
commit-graph | Write commit-graph file for faster commit lookup |
prefetch | Download objects from configured remotes |
incremental-repack | Repack objects incrementally |
loose-objects | Consolidate loose objects into pack files |
pack-refs | Pack references for better performance |
Automatic Task Selection:
Section titled “Automatic Task Selection:”# Run default enabled tasks (gc only)git maintenance run
# Run specific tasksgit maintenance run --task=commit-graph --task=pack-refs
# Run scheduled tasks (for background jobs)git maintenance run --schedule=dailyBasic Usage Examples:
Section titled “Basic Usage Examples:”One-time Maintenance:
Section titled “One-time Maintenance:”# Run default maintenance (gc by default)git maintenance run
# Run multiple specific tasksgit maintenance run --task=commit-graph --task=pack-refs --task=gc
# Run all available tasksgit maintenance run --task=commit-graph --task=pack-refs --task=gc --task=prefetch --task=incremental-repackBackground Scheduling:
Section titled “Background Scheduling:”# Start automatic maintenancegit maintenance start
# Stop automatic maintenancegit maintenance stop
# Register repository for maintenance (without scheduling)git maintenance register
# Unregister repositorygit maintenance unregisterCustom Schedules:
Section titled “Custom Schedules:”# Start with custom schedulergit maintenance start --scheduler=launchd
# Configure maintenance frequencygit config maintenance.strategy incremental
git config maintenance.gc.enabled truegit config maintenance.commit-graph.enabled trueAdvanced Maintenance Configuration:
Section titled “Advanced Maintenance Configuration:”Task Configuration:
Section titled “Task Configuration:”# Enable specific tasksgit config maintenance.gc.enabled truegit config maintenance.commit-graph.enabled truegit config maintenance.prefetch.enabled true
# Disable tasksgit config maintenance.gc.enabled false
# Configure task schedulesgit config maintenance.gc.schedule "30 2 * * *" # Daily at 2:30 AMgit config maintenance.commit-graph.schedule "0 3 * * *" # Daily at 3:00 AMRepository-Specific Settings:
Section titled “Repository-Specific Settings:”# Per-repository maintenance settingsgit config maintenance.repo "/path/to/repo"
# Multiple repository maintenancegit maintenance register --repo=/path/to/repo1git maintenance register --repo=/path/to/repo2
# Bulk maintenancefor repo in ~/projects/*; do if [ -d "$repo/.git" ]; then git maintenance register --repo="$repo" fidoneMaintenance Strategies:
Section titled “Maintenance Strategies:”Incremental Strategy (Default):
Section titled “Incremental Strategy (Default):”# Config for incremental maintenancegit config maintenance.strategy incremental
# Incremental configuration benefits:# - Runs smaller, faster operations# - Reduces I/O load# - Better for frequent runsScheduled Maintenance Approaches:
Section titled “Scheduled Maintenance Approaches:”# Daily maintenance tasksgit config maintenance.daily.enabled truegit config maintenance.daily.schedule "30 2 * * *,45 14 * * *"
# Weekly maintenance tasksgit config maintenance.weekly.enabled truegit config maintenance.weekly.schedule "0 3 * * 0" # Sundays at 3 AM
# Monthly maintenance tasksgit config maintenance.monthly.enabled truegit config maintenance.monthly.schedule "0 4 1 * *" # First day at 4 AMPlatform-Specific Schedulers:
Section titled “Platform-Specific Schedulers:”Systemd (Linux):
Section titled “Systemd (Linux):”# Enable systemd schedulergit maintenance start --scheduler=systemd
# Systemd service configurationsystemctl --user enable git-maintenance@hourly.timersystemctl --user start git-maintenance@hourly.timerLaunchd (macOS):
Section titled “Launchd (macOS):”# Enable launchd schedulergit maintenance start --scheduler=launchd
# Manual launchd configurationlaunchctl load ~/Library/LaunchAgents/git-maintenance-hourly.plistCron (Linux/Unix):
Section titled “Cron (Linux/Unix):”# Standard cron setupecho "@hourly git maintenance run --schedule=hourly" | crontab -
# Advanced cron configuration# Add to crontab:# 30 2 * * * /usr/bin/git maintenance run --schedule=daily# 0 3 * * 0 /usr/bin/git maintenance run --schedule=weeklyTask Scheduler (Windows):
Section titled “Task Scheduler (Windows):”# Enable scheduled task (Windows)git maintenance start --scheduler=schtasks
# Manual task creationschtasks /create /tn "Git Maintenance" /tr "git maintenance run" /sc hourlyMonitoring and Debugging:
Section titled “Monitoring and Debugging:”Status Monitoring:
Section titled “Status Monitoring:”# Check maintenance statusgit maintenance run --dry-run
# View maintenance logsgit config maintenance.log.filetail -f ~/.git-maintenance.log
# Check task statesgit config --list | grep maintenancePerformance Monitoring:
Section titled “Performance Monitoring:”# Time maintenance operationstime git maintenance run
# Monitor repository size changesdu -sh .git/before-maintenancegit maintenance rundu -sh .git/after-maintenance
# Track optimization improvementsgit log --oneline -10 --stat > before.txtgit maintenance run --task=commit-graphgit log --oneline -10 --stat > after.txtdiff before.txt after.txtMaintenance Task Details:
Section titled “Maintenance Task Details:”Garbage Collection (gc):
Section titled “Garbage Collection (gc):”# Manual garbage collectiongit gc
# Through maintenancegit maintenance run --task=gc
# Aggressive garbage collectiongit gc --aggressive --prune=now
# Configurationgit config gc.auto 0 # Disable auto-gcgit config gc.autoDetach false # Run gc in foregroundCommit Graph Generation:
Section titled “Commit Graph Generation:”# Generate commit graphgit commit-graph write
# Through maintenancegit maintenance run --task=commit-graph
# Verify commit graphgit commit-graph verify
# Configuration for large repositoriesgit config core.commitGraph truegit config commitGraph.generationVersion 2Reference Packing:
Section titled “Reference Packing:”# Pack loose referencesgit pack-refs
# Through maintenancegit maintenance run --task=pack-refs
# Check packed refsls -la .git/packed-refscat .git/packed-refs | wc -lIncremental Repack:
Section titled “Incremental Repack:”# Repack incrementallygit repack -d --write-bitmap-index
# Through maintenancegit maintenance run --task=incremental-repack
# Full repack (occasional)git repack -a -d -f --write-bitmap-indexIntegration with Workflows:
Section titled “Integration with Workflows:”Development Environment Setup:
Section titled “Development Environment Setup:”#!/bin/bash# Configure maintenance for development repository
# Enable essential tasksgit config maintenance.gc.enabled truegit config maintenance.commit-graph.enabled truegit config maintenance.prefetch.enabled true
# Set maintenance strategygit config maintenance.strategy incremental
# Start background maintenancegit maintenance start
# Verify configurationecho "Maintenance configuration:"git config --list | grep maintenanceCI/CD Pipeline Integration:
Section titled “CI/CD Pipeline Integration:”#!/bin/bash# Maintenance in CI pipeline
# Check if maintenance is neededif [ "$(du -s .git | awk '{print $1}')" -gt 1000000 ]; then echo "Repository large, running maintenance" git maintenance run --task=incremental-repack --task=commit-graphelse echo "Repository size OK, light maintenance" git maintenance run --task=commit-graphfi
# Performance optimizationgit config core.commitGraph truegit config pack.threads 0 # Auto-detect CPU countRepository Health Monitoring:
Section titled “Repository Health Monitoring:”#!/bin/bash# Monitor repository health and run maintenance
# Check for loose objectsloose_count=$(find .git/objects -type f -name '[0-9a-f]*' | wc -l)if [ "$loose_count" -gt 1000 ]; then echo "High loose object count: $loose_count" git maintenance run --task=loose-objectsfi
# Check repository sizerepo_size=$(du -sh .git | awk '{print $1}')echo "Repository size: $repo_size"
# Check commit count for commit-graph benefitcommit_count=$(git rev-list --all --count)if [ "$commit_count" -gt 10000 ]; then echo "Large commit count: $commit_count, enabling commit-graph" git maintenance run --task=commit-graphfiTroubleshooting Common Issues:
Section titled “Troubleshooting Common Issues:”Maintenance Not Starting:
Section titled “Maintenance Not Starting:”# Check scheduler supportgit maintenance start --scheduler=auto
# Manual scheduler detectionif command -v systemctl >/dev/null; then git maintenance start --scheduler=systemdelif command -v launchctl >/dev/null; then git maintenance start --scheduler=launchdelse echo "No supported scheduler found"fiTask Execution Errors:
Section titled “Task Execution Errors:”# Debug maintenance runsGIT_TRACE=1 git maintenance run
# Check specific taskgit maintenance run --task=gc 2>&1 | tee maintenance.log
# Verify repository integrity firstgit fsck --unreachable | head -10Performance Issues:
Section titled “Performance Issues:”# Monitor long-running taskstimeout 300 git maintenance run || echo "Maintenance timed out"
# Split large maintenance tasksgit maintenance run --task=commit-graphgit maintenance run --task=gc --task=pack-refs
# Resource limitingulimit -v 1000000 # Memory limitnice -n 10 git maintenance run # Lower priorityConfiguration Conflicts:
Section titled “Configuration Conflicts:”# Reset maintenance configgit config --unset-regexp ^maintenance\.
# Check for conflicting settingsgit config --list | grep -E "(gc|commit)"
# Clean restartgit maintenance stopgit maintenance unregistergit maintenance registergit maintenance startReal-World Usage Examples:
Section titled “Real-World Usage Examples:”After Large Import:
Section titled “After Large Import:”#!/bin/bash# Repository optimization after massive import
echo "Running comprehensive maintenance after large import"
# Step 1: Initial cleanupgit maintenance run --task=loose-objects
# Step 2: Generate optimizationsgit maintenance run --task=commit-graph --task=pack-refs
# Step 3: Full garbage collectiongit maintenance run --task=gc
# Step 4: Final incremental repackgit maintenance run --task=incremental-repack
# Verificationecho "Repository size after maintenance:"du -sh .git/echo "Loose objects remaining:"find .git/objects -type f -name '[0-9a-f]*' | wc -lRegular Development Workflow:
Section titled “Regular Development Workflow:”# Nightly maintenance script#!/bin/bash# Scheduled development repository maintenance
LOG_FILE="/var/log/git-maintenance.log"
{ echo "=== Git Maintenance Run: $(date) ==="
# Check if repository needs maintenance if ! git diff --quiet HEAD 2>/dev/null; then echo "Working directory not clean, skipping maintenance" exit 0 fi
# Run light maintenance echo "Running daily maintenance" time git maintenance run --task=commit-graph --task=pack-refs
# Conditional garbage collection (weekly) if [ $(date +%u) = 7 ]; then echo "Running weekly garbage collection" time git maintenance run --task=gc fi
# Monthly full repack if [ $(date +%d) = 1 ]; then echo "Running monthly repack" time git maintenance run --task=incremental-repack fi
echo "Maintenance completed successfully"
} >> "$LOG_FILE" 2>&1Server Repository Management:
Section titled “Server Repository Management:”#!/bin/bash# Multi-repository server maintenance
SERVER_REPOS="/srv/git/repositories"LOG_FILE="/var/log/git-server-maintenance.log"
echo "Starting server-wide maintenance: $(date)" >> "$LOG_FILE"
for repo in "$SERVER_REPOS"/*; do if [ ! -d "$repo/.git" ]; then continue; fi
echo "Maintaining $repo" >> "$LOG_FILE"
# Enter repository cd "$repo" || continue
# Run maintenance based on repo size repo_size=$(du -s .git | awk '{print $1}')
if [ "$repo_size" -gt 10000000 ]; then # 10GB+ echo "Heavy maintenance for large repo" >> "$LOG_FILE" git maintenance run --task=incremental-repack --task=commit-graph >> "$LOG_FILE" 2>&1 else echo "Light maintenance for small repo" >> "$LOG_FILE" git maintenance run --task=commit-graph --task=pack-refs >> "$LOG_FILE" 2>&1 fi
# Weekly full GC if [ $(date +%u) = 7 ]; then echo "Running GC for $repo" >> "$LOG_FILE" git maintenance run --task=gc >> "$LOG_FILE" 2>&1 fi
done
echo "Server maintenance completed: $(date)" >> "$LOG_FILE"What’s the relationship between maintenance and git gc?
Section titled “What’s the relationship between maintenance and git gc?”git maintenance run —task=gc calls git gc internally with optimized settings. Maintenance provides scheduling and selective task execution.
How do I disable automatic maintenance?
Section titled “How do I disable automatic maintenance?”Run git maintenance stop to stop background scheduling, or git maintenance unregister to remove repository from maintenance tracking.
What’s the impact on repository users during maintenance?
Section titled “What’s the impact on repository users during maintenance?”Most tasks (except gc) allow concurrent access. GC requires exclusive repository access. Schedule during low-activity periods.
Can maintenance work on bare repositories?
Section titled “Can maintenance work on bare repositories?”Yes, all maintenance tasks work on bare repositories. Useful for optimizing server-side repositories where gc alone runs traditionally.
How do I troubleshoot failing maintenance tasks?
Section titled “How do I troubleshoot failing maintenance tasks?”Run with GIT_TRACE=1 for debugging output. Check repository integrity with git fsck. Test individual tasks manually before automation.
What’s the difference between incremental and aggressive maintenance?
Section titled “What’s the difference between incremental and aggressive maintenance?”Incremental runs smaller optimizations frequently; aggressive (like gc —aggressive) does thorough optimization but takes longer and should run less often.
Can maintenance tasks be run manually without scheduling?
Section titled “Can maintenance tasks be run manually without scheduling?”Yes, use git maintenance run —task=
How do I monitor maintenance effectiveness?
Section titled “How do I monitor maintenance effectiveness?”Compare repository size, object counts, and git log performance before/after maintenance. Use time command to measure task duration.
What happens if maintenance is interrupted?
Section titled “What happens if maintenance is interrupted?”Most tasks are atomic - partial completion doesn’t corrupt repository. Restart maintenance to continue. Loose object consolidation may need retry.
Can maintenance be configured per-branch or per-user?
Section titled “Can maintenance be configured per-branch or per-user?”Maintenance is repository-level, not branch-specific. User-specific configuration through global git config. Per-branch optimization through commit-graph generation.
How frequently should maintenance run?
Section titled “How frequently should maintenance run?”Light tasks (commit-graph, pack-refs): Daily. GC: Weekly. Incremental repack: Monthly or every 1000 commits. Adjust based on repository size/activity.
What’s the storage impact of maintenance tasks?
Section titled “What’s the storage impact of maintenance tasks?”Maintenance typically reduces storage through packing and garbage collection, though commit-graph adds small overhead for better performance.
Can maintenance work with Git LFS repositories?
Section titled “Can maintenance work with Git LFS repositories?”Works normally - LFS pointers are Git objects like any other. Maintenance optimizes the Git repository structure, not LFS server storage.
How do I handle maintenance in shared repository scenarios?
Section titled “How do I handle maintenance in shared repository scenarios?”For shared repositories, coordinate maintenance windows with users. Use git gc —auto or background maintenance during low-activity periods.
What’s the relationship between maintenance and git gc —auto?
Section titled “What’s the relationship between maintenance and git gc —auto?”git gc —auto triggers based on operation counts; maintenance provides scheduled optimization. Use both: auto for immediate response, scheduled for thorough maintenance.
Applications of the git maintenance command
Section titled “Applications of the git maintenance command”- Repository Performance Optimization: Speed up Git commands through data structure optimization
- Storage Space Reduction: Clean up unnecessary files and repack objects efficiently
- Automated Background Tasks: Set up scheduled maintenance for unattended repository care
- Large Repository Management: Handle optimization of massive repositories with controlled resource usage
- Server Repository Administration: Manage maintenance across multiple server-hosted repositories
- Development Workflow Enhancement: Maintain repository health as part of development processes