Recovery Tools

Learn to use Git's powerful recovery and maintenance tools

Learning Objectives

  • Master Git's reflog for recovering lost work
  • Use git fsck to find dangling objects
  • Learn advanced repository maintenance
  • Understand Git's garbage collection process

Git Recovery Tools

Git provides powerful tools for recovering lost work and maintaining repository health. Understanding these tools is crucial for handling complex recovery scenarios.

Key Tools

  • reflog:Reference history tracking
  • fsck:File system check
  • gc:Garbage collection

Recovery Scenarios

  • Lost commits and branches
  • Corrupted repositories
  • Accidental overwrites

Using Git Reflog

The reflog records updates to branch tips and other references, providing a safety net for recovering lost work.

Reflog Commands
# View reflog
$ git reflog
# Detailed reflog for specific branch
$ git reflog show main
# Restore to previous state
$ git reset --hard HEAD@{2}
# Recover deleted branch
$ git checkout -b recover-branch HEAD@{4}
# View detailed reflog entries
$ git reflog --date=iso

Common Recovery Scenarios

Recover from Bad Reset

# Find commit before reset
$ git reflog
# Reset to previous state
$ git reset --hard HEAD@{1}

Restore Deleted Branch

# Find last commit of branch
$ git reflog
# Create new branch at that point
$ git checkout -b branch-name HEAD@{4}

File System Check (fsck)

Git fsck verifies the connectivity and validity of objects in your database, helping you find unreachable objects that might contain lost work.

Using Git FSCK
# Basic repository check
$ git fsck
# Find dangling objects
$ git fsck --dangling
# Full verification
$ git fsck --full
# Check with progress
$ git fsck --progress

Recovery Process

  • 1.

    Find Lost Objects

    $ git fsck --lost-found
  • 2.

    Examine Content

    $ git show <object-hash>
  • 3.

    Recover Objects

    $ git branch recover-branch <object-hash>

Repository Maintenance

Regular maintenance keeps your repository healthy and performs optimally. Understanding maintenance commands helps prevent issues before they occur.

Garbage Collection

# Run garbage collection
$ git gc
# Aggressive collection
$ git gc --aggressive
# Prune loose objects
$ git prune
# Clean untracked files
$ git clean -fd

Repository Optimization

# Repack repository
$ git repack -a -d
# Verify objects
$ git fsck --full
# Count objects
$ git count-objects -v
# Optimize repository
$ git maintenance run

Maintenance Schedule

  • Daily: git gc --auto
  • Weekly: git repack -a -d
  • Monthly: git gc --aggressive

What's Next?

Now that you understand Git's recovery tools, let's learn about debugging techniques to track down issues in your repository. In the next lesson, you'll learn about:

  • Using git blame for code archaeology
  • Binary search with git bisect
  • Debugging strategies and workflows
  • Performance profiling and optimization