[Git]不要ファイル履歴削除

2019/05/28

・git clone が重い
・秘密のファイルを Commit してしまった

など、過去にファイルを Commit & Pull してしまった場合、問題ファイルをなかったことにしたい場合があります。

履歴の削除は「git filter-branch」を利用してできますが、破壊的に履歴変更するため事前バックアップするなど作業は自己責任で行ってください。

PHPサンプルスクリプト

destory_git_history.php

オブジェクト容量の大きいファイルを検出

git_find_big.sh で大きなオブジェクトを抽出

$ du -sh .git/objects 12M .git/objects
$ sh git_find_big.sh
Bash

「git_find_big.sh」は、gitコマンドを用いて「.git/objects/pack/pack」内の容量の多いオブジェクト順で抽出します。

履歴を抹消

抽出したファイルやディレクトリを削除 (refs/heads/master と refs/remotes/origin/master を書き換え)
※ディレクトリの場合は「git rm -r」

$ git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch ファイルパス' --prune-empty -- --all
Bash

ガベージコレクションを利用して、不要なオブジェクトやログを削除します。

$ git gc --aggressive --prune=now
Bash

git オブジェクトのリパックします。

$ git repack -A -d
Bash

強制的にPush

$ git push --force origin master
Bash

共同作業している場合は、clone してもらった方が安全かもしれません。