Git Guide: How to Remove Accidental Large Files from History
📑 Git Guide: How to Remove Accidental Large Files from History
When you commit a file larger than 100MB, GitHub will reject your push—even if you delete the file later. This happens because the file remains trapped inside your local commit history. Follow these steps to purge it.
Phase 1: Identify the Culprit 🔍
If your push hangs or fails, find out exactly which file is taking up all the space:
bash
git rev-list --objects --all | grep "$(git verify-pack -v .git/objects/pack/*.idx | sort -k 3 -n | tail -10 | awk '{print $1}')"
Use code with caution.
Look at the very last line of the output to find the exact file path of the heaviest object.
Phase 2: Purge the File from Git History ✂️
Once you have the path (e.g., code/frontend/node_modules.zip), run the following commands sequentially to erase it completely from every commit.
1. Rewrite the Commit History
Run this command to strip the file out of Git's memory across all local commits without changing your actual code files:
bash
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch PATH/TO/YOUR/LARGE/FILE" \
--prune-empty --tag-name-filter cat -- --all
Use code with caution.
(Replace PATH/TO/YOUR/LARGE/FILE with your actual file path).
2. Delete Git's Internal Backups
Git creates hidden backup references (refs/original/) during history rewrites. You must delete them, or the file size won't shrink:
bash
git update-ref -d refs/original/refs/heads/main 2>/dev/null
git update-ref -d refs/original/refs/heads/feature/mgmt 2>/dev/null
git reflog expire --expire=now --all
Use code with caution.
3. Aggressively Reclaim Disk Space
Force Git to break down its heavy history bundle (.pack file) and reconstruct a clean, lightweight version:
bash
git repack -a -d --depth=250 --window=250
git gc --prune=now --aggressive
Use code with caution.
Phase 3: Update .gitignore to Prevent a Recurrence 🛡️
Open your .gitignore file and ensure your rules apply globally across all subdirectories by using the double-asterisk (**/) syntax:
text
# Universal subdirectory catches
**/node_modules/
**/.next/
**/venv/
**/.venv/
**/dist/
# Block specific heavy extensions everywhere
*.zip
*.rar
*.whl
*.tar.gz
*.db
*.sqlite
Use code with caution.
Phase 4: Verify and Push ✅
1. Check your final repository pack size:
bash
git count-objects -vH
Use code with caution.
Verify that size-pack has dropped significantly.
2. Safely push your clean branch to GitHub:
bash
git push origin HEAD
Use code with caution.
Comments
Post a Comment