Rewriting History Safely
What You'll Learn
You'll learn how to use git filter-branch and git filter-repo to perform large-scale history rewrites and scrub sensitive data from your entire Git repository.
The Nuclear Options for History Correction
Sometimes you need to rewrite not just recent commits (which you've done with interactive rebase), but the entire history of a repository. Common scenarios include accidentally committing passwords, API keys, or large binary files that bloat the repo forever.
git filter-branch: The Old Guard
git filter-branch is Git's built-in tool for traversing every commit and applying transformations:
# Remove a file from ALL commits
git filter-branch --tree-filter 'rm -f passwords.txt' HEAD
# Change all commit emails
git filter-branch --env-filter '
if [ "$GIT_AUTHOR_EMAIL" = "wrong@email.com" ]; then
export GIT_AUTHOR_EMAIL="correct@email.com"
fi
' HEAD
Warning: This is slow and dangerous. It rewrites every commit SHA, breaking everyone's local copies.
git filter-repo: The Modern Solution
git filter-repo is faster, safer, and now recommended by Git's documentation:
# Remove a sensitive file
git filter-repo --path passwords.txt --invert-paths
# Remove all files over 10MB
git filter-repo --strip-blobs-bigger-than 10M
Safety First
Before rewriting history:
- Notify your team — everyone will need to re-clone
- Make a backup:
git clone --mirror original-repo backup-repo - Force-push carefully:
git push --force-with-lease
Think of this like performing surgery on a shared family photo album — you're changing the past for everyone.
Key Takeaway: Use git filter-repo (preferred) or git filter-branch to rewrite entire repository histories, but coordinate with your team because all commit SHAs will change and collaborators must re-clone.