有些時候不小心上傳了一些敏感文件(例如密碼), 或者不想上傳的文件(沒及時或忘了加到.gitignore里的),
而且上傳的文件又特別大的時候, 這將導致別人clone你的代碼或下載zip包的時候也必須更新或下載這些無用的文件,
因此, 我們需要一個方法, 永久的刪除這些文件(包括該文件的歷史記錄).
首先, 可以參考 github 的幫助:
https://help.github.com/articles/remove-sensitive-data
步驟一: 從你的資料庫中清除文件
以Windows下為例(Linux類似), 打開項目的Git Bash,使用命令:
$ git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch path-to-your-remove-file' --prune-empty --tag-name-filter cat -- --all
其中, path-to-your-remove-file 就是你要刪除的文件的相對路徑(相對於git倉庫的跟目錄), 替換成你要刪除的文件即可. 注意一點,這里的文件或文件夾,都不能以 '/' 開頭,否則文件或文件夾會被認為是從 git 的安裝目錄開始。
如果你要刪除的目標不是文件,而是文件夾,那么請在 `git rm --cached' 命令后面添加 -r 命令,表示遞歸的刪除(子)文件夾和文件夾下的文件,類似於 `rm -rf` 命令。
此外,如果你要刪除的文件很多, 可以寫進一個.sh文件批量執行, 如果文件或路徑里有中文, 由於MinGW或CygWin對中文路徑設置比較麻煩, 你可以使用通配符*號, 例如: sound/music_*.mp3, 這樣就把sound目錄下以music_開頭的mp3文件都刪除了.
例如這樣, 新建一個 bash 腳本文件,del-music-mp3.sh:
$ git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch projects/Moon.mp3' --prune-empty --tag-name-filter cat -- --all
$ git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch sound/Music_*.mp3' --prune-empty --tag-name-filter cat -- --all
Rewrite 48dc599c80e20527ed902928085e7861e6b3cbe6 (266/266) # Ref 'refs/heads/master' was rewritten
如果顯示 xxxxx unchanged, 說明repo里沒有找到該文件, 請檢查路徑和文件名是否正確.
注意: 補充一點, 如果你想以后也不會再上傳這個文件或文件夾, 請把這個文件或文件夾添加到.gitignore文件里, 然后再push你的repo.
步驟二: 推送我們修改后的repo
以強制覆蓋的方式推送你的repo, 命令如下:
$ git push origin master -f
執行結果類似下面:
Counting objects: 4669, done. Delta compression using up to 4 threads. Compressing objects: 100% (4352/4352), done. Writing objects: 100% (4666/4666), 35.16 MiB | 51 KiB/s, done. Total 4666 (delta 1361), reused 0 (delta 0) To https://github.com/defunkt/github-gem.git + beb839d...81f21f3 master -> master (forced update)
$ git push origin master --force --tags
步驟三: 清理和回收空間
雖然上面我們已經刪除了文件, 但是我們的repo里面仍然保留了這些objects, 等待垃圾回收(GC), 所以我們要用命令徹底清除它, 並收回空間.
命令如下:
$ rm -rf .git/refs/original/ $ git reflog expire --expire=now --all $ git gc --prune=now
Counting objects: 2437, done.
# Delta compression using up to 4 threads. # Compressing objects: 100% (1378/1378), done. # Writing objects: 100% (2437/2437), done. # Total 2437 (delta 1461), reused 1802 (delta 1048)
$ git gc --aggressive --prune=now
Counting objects: 2437, done.
# Delta compression using up to 4 threads. # Compressing objects: 100% (2426/2426), done. # Writing objects: 100% (2437/2437), done. # Total 2437 (delta 1483), reused 0 (delta 0)
現在你再看看你的.git目錄文件大小是不是變小了.