Git技巧:指定文件保留在工作区且仅存于最新提交
Solution: Keep Reference PDFs in Latest Commit, Remove from History, and Keep .git Lean
Alright, let's walk through this step by step to hit all your requirements—keeping your .git folder lightweight, syncing critical PDFs across systems via GitHub, and ensuring old PDF versions are purged from history.
Step 1: Configure .gitignore and Prepare Current Files
First, we'll set up Git to ignore PDFs by default, while keeping your reference copies in the latest commit:
- Stop tracking existing PDF files but preserve them in your local working directory:
# Use this for all PDFs, or list specific files like ref1.pdf ref2.pdf git rm --cached *.pdf - Add
*.pdfto your.gitignoreto block future accidental commits of PDFs:echo "*.pdf" >> .gitignore - Commit the .gitignore update and untracked change:
git add .gitignore git commit -m "Stop tracking PDFs, add to .gitignore" - Re-add the reference PDFs you want synced in the latest commit only (use
-fto bypass the .gitignore rule):# Replace with your specific PDF files if needed git add -f *.pdf git commit -m "Add reference PDFs to latest commit for cross-system sync"
Step 2: Remove PDFs from All Historical Commits
This step rewrites Git history to delete every PDF file from past commits—this is the key to shrinking your .git folder size. Important note: If this is a shared repository, notify collaborators first, as this changes commit history irreversibly.
- Use
git filter-repo(the modern, safer alternative tofilter-branch) to strip PDFs from all past commits:# This removes all PDF files across every commit in your repo's history git filter-repo --path-glob '*.pdf' --invert-paths - Force-push the cleaned history to GitHub (replace
mainwith your branch name if it's different):git push origin main --force
Step 3: Post-Cleanup and Ongoing Maintenance
- Backup first: Before rewriting history, always make a copy of your repo folder as a safety net—better safe than sorry!
- Updating synced PDFs: When you need to update your reference PDFs later, just modify them and use
git add -f <your-pdf-file>to commit the change. The-fflag lets you bypass .gitignore for those specific files. - Avoid accidental bloat: Regular
git add .commands won't pick up new or unrelated PDFs thanks to your .gitignore rule, so you won't accidentally bloat the repo again.
内容的提问来源于stack exchange,提问作者Porcupine
相关产品推荐
相关产品推荐

