天天看點

如何清洗 Git Repo 代碼倉庫

相信不少團隊的代碼倉庫 git repo 變得越來越大。除了代碼的送出外,時常有人會把二進制檔案比如 jar 包或者不小心把不該送出到代碼庫的檔案送出到代碼庫中,比如使用者名密碼之類的保密資訊。如何清洗代碼倉庫 git repo,徹底從曆史中删除此類檔案呢?

如何清洗 Git Repo 代碼倉庫

<a target="_blank"></a>

首先進行 git 垃圾回收:

<code>git gc --auto</code>

其次檢視 git 倉庫占用空間:

<code>$ du -hs .git/objects</code>

<code>45m .git/objects</code>

然後找出曆史中超過一定大小的檔案,最後在曆史中删除并且送出。如果感興趣手動處理這個過程可以參照文章後邊的連結。

清理曆史中的檔案:

<code>git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch ****/nohup.out' --prune-empty --tag-name-filter cat -- --all</code>

<code>git filter-branch --index-filter 'git rm --cached --ignore-unmatch ****/nohup.out' head</code>

<code>git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d</code>

強制送出覆寫:

<code>git reflog expire --expire=now --all</code>

<code>git gc --prune=now</code>

<code>git push --all --force</code>

<code>git push --all --tags --force</code>

但是這個方案有 2 個問題:

處理速度慢,嘗試清理 2g 大小的代碼庫,用了一晚上還沒跑完。

隻能按檔案名清理,如果不同的路徑有同樣的檔案名就無法處理了,可能誤删檔案或者忽略某些檔案。

當然有個非常好的解決方案完美解決了這個問題。如下:

<code>java -jar bfg-1.11.7.jar --delete-files *.zip myrepo.git</code>

<code>java -jar bfg-1.11.7.jar --delete-files *.log myrepo.git</code>

<code>java -jar bfg-1.11.7.jar --delete-files *.out myrepo.git</code>

<code>java -jar bfg-1.11.7.jar --strip-blobs-bigger-than 1m myrepo.git</code>

複制代碼倉庫:

<code>git clone --bare /var/www/html/myrepo.git</code>

git 後悔藥,覆寫最後一次修改:

<code>git add .</code>

<code>git commit --amend</code>

<code>git push origin master -f</code>

git 放棄本地修改:

<code>git checkout .</code>

git 銷毀最後一次送出:

<code>git reset --hard head^</code>

<code>git push -f origin head^:master</code>

打包時候嵌入版本号:

<code>git rev-parse head &gt; version.txt</code>

<b></b>

<b>原文釋出時間為:2015-07-07</b>

<b>本文來自雲栖社群合作夥伴“linux中國”</b>