如何删除Git仓库过往提交中的无用大文件?
如何删除Git过往提交中的无用大文件以减小仓库体积?
问题场景
我的Git仓库因多次误提交大文件导致体积过大:
$ du -sh .git/objects 1.3G .git/objects
通过脚本检测出以下无用大文件:
$ sh git_find_big.sh All sizes are in kB's. The pack column is the size of the object, compressed, inside the pack file. -e size pack SHA location 810409984 495862913 4bb4caef2a85833bdf6f00bb9d85336db461c0f9 w2v_model/chive-1.2-mc90.magnitude 578685728 537201063 3f99a664faebd9230183c41d07afd82ca00ca798 w2v_model/chive-1.2-mc90_gensim/chive-1.2-mc90.kv.vectors.npy 223313372 89641673 ff6eabe882f56f49756e00ed09b36e872bd522ee w2v_model/ja/ja.tsv 60129680 55860848 efd88223905b1c814fd3799dbb29a76c7f5cfd73 w2v_model/ja/ja.bin.syn1neg.npy 60129680 55853784 ffc4ab2e30bc8ffec6f6c024ac2003b78fc5e72d w2v_model/ja/ja.bin.syn0.npy 57033294 54522375 a83910c4160775c3c9cb09f61ce0e53ecb2dca8e static/defapp/assets/accompaniment.wav
尝试删除单个文件时,因存在未暂存更改导致命令失败,仓库体积无变化:
$ git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch w2v_model/chive-1.2-mc90.magnitude' -- --all WARNING: git-filter-branch has a glut of gotchas generating mangled history rewrites. Hit Ctrl-C before proceeding to abort, then use an alternative filtering tool such as 'git filter-repo' instead. See the filter-branch manual page for more details; to squelch this warning, set FILTER_BRANCH_SQUELCH_WARNING=1. Proceeding with filter-branch... Cannot rewrite branches: You have unstaged changes.
$ du -sh .git/objects 1.3G .git/objects
解决步骤
处理未暂存更改
先提交或 stash 本地未暂存的修改,确保工作区处于干净状态。重写仓库历史,删除目标文件/目录
执行git filter-branch命令重写所有分支的历史,删除目标目录(此处示例删除整个w2v_model目录):
$ git filter-branch -f --index-filter 'git rm -r --cached --ignore-unmatch w2v_model' -- --all WARNING: git-filter-branch has a glut of gotchas generating mangled history rewrites. Hit Ctrl-C before proceeding to abort, then use an alternative filtering tool such as 'git filter-repo' instead. See the filter-branch manual page for more details; to squelch this warning, set FILTER_BRANCH_SQUELCH_WARNING=1. Proceeding with filter-branch... Rewrite 01787ee7aec64ee385de2127c23d08fb3ab2c9c8 (76/149) (7 seconds passed, remaining 6 predicted) rm 'w2v_model/.DS_Store' rm 'w2v_model/ja/ja.bin'
- 清理旧的引用和垃圾文件
执行以下命令清理过期的引用并彻底删除无用的Git对象:
$ git reflog expire --expire=now --all $ git gc --prune=now
- 验证结果
检查仓库体积,确认已成功减小:
du -sh .git/objects 343M .git/objects
内容的提问来源于stack exchange,提问作者whitebear
相关产品推荐
相关产品推荐

