1. 程式人生 > >從儲存庫中刪除敏感資料(刪除檔案歷史)

從儲存庫中刪除敏感資料(刪除檔案歷史)

1、如果您的歷史記錄中還沒有包含敏感資料的儲存庫的本地副本,請將儲存庫克隆到本地計算機。

git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
Initialized empty Git repository in /Users/YOUR-FILE-PATH/YOUR-REPOSITORY/.git/
remote: Counting objects: 1301, done.
remote: Compressing objects: 100% (769/769), done.
remote: Total 1301 (delta 724), reused 910
(delta 522) Receiving objects: 100% (1301/1301), 164.39 KiB, done. Resolving deltas: 100% (724/724), done.

 

2、切換到儲存庫的工作目錄,克隆完成後庫的根目錄。

cd YOUR-REPOSITORY

 

3、執行以下命令,替換為要刪除的檔案PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA路徑,而不僅僅是檔名這些論點將:

  • 強制Git處理,但不檢查每個分支和標記的整個歷史記錄
  • 刪除指定的檔案,以及作為結果生成的任何空提交
  • 覆蓋現有標籤,重寫歷史
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA' \
--prune-empty --tag-name-filter cat -- --all
Rewrite 48dc599c80e20527ed902928085e7861e6b3cbe6 (266/266)
Ref 'refs/heads/master' was rewritten
Ref 'refs/remotes/origin/master
' was rewritten WARNING: Ref 'refs/remotes/origin/master' is unchanged

 

4、新增包含敏感資料的檔案,.gitignore 以確保您不會意外地再次提交它。 

echo "YOUR-FILE-WITH-SENSITIVE-DATA" >> .gitignore
git add .gitignore
git commit -m "Add YOUR-FILE-WITH-SENSITIVE-DATA to .gitignore"
[master 051452f] Add YOUR-FILE-WITH-SENSITIVE-DATA to .gitignore
 1 files changed, 1 insertions(+), 0 deletions(-)

5、仔細檢查您是否從儲存庫的歷史記錄中刪除了所需的所有內容,並檢查了所有分支機構。

 

6、一旦您對儲存庫的狀態感到滿意,強制推送您的本地更改以覆蓋您的GitHub儲存庫,以及您推送的所有分支:

git push origin --force --all
Counting objects: 1074, done.
Delta compression using 2 threads.
Compressing objects: 100% (677/677), done.
Writing objects: 100% (1058/1058), 148.85 KiB, done.
Total 1058 (delta 590), reused 602 (delta 378)
To https://github.com/YOUR-USERNAME/YOUR-REPOSITORY.git
 + 48dc599...051452f master -> master (forced update)

 

7、要從標記版本中刪除敏感檔案,您還需要強制推送Git標記:

git push origin --force --tags
Counting objects: 321, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (166/166), done.
Writing objects: 100% (321/321), 331.74 KiB | 0 bytes/s, done.
Total 321 (delta 124), reused 269 (delta 108)
To https://github.com/YOUR-USERNAME/YOUR-REPOSITORY.git
 + 48dc599...051452f master -> master (forced update)

 

8、經過一段時間後,您確信 git filter-branch 沒有意外的副作用,您可以使用以下命令(使用Git 1.8.5或更高版本)強制取消引用本地儲存庫中的所有物件並進行垃圾回收:

git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
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)

 

9、執行完成後會刪除你的操作的資料檔案

 

相關文章:Removing sensitive data from a repository

            徹底清除Github上某個檔案的歷史(針對誤上傳密碼檔案等情況)