You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 *.pdf to your .gitignore to 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 -f to 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 to filter-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 main with 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 -f flag 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:06:41