git: remove big files in historical commits

最近git push一直提示文件太大,無法push,想到應該是自己之前不小心git add *把可執行文件什麼的也加入跟蹤列表了,於是就想把它們從歷史commits中刪除,步驟總結如下:

  1. 查看歷史提交中有哪些非源代碼文件,然後把它們記錄下來:
    git log --stat
  2. 刪除歷史提交中的非源代碼文件:
    git filter-branch --tree-filter 'rm -f non_code_files' HEAD
  3. 如果步驟2中漏掉了某些大文件,則可以再執行2中的命令,不過要加一個參數-f:
    git filter-branch -f --tree-filter 'rm -f non_code_files_left' HEAD
  4. 最後把本地提交強制push到遠端:
    git push -f