Git Filter Repo

Git 進階

Amanda Crawford-Adamo

Software and Data Engineer

什麼是 git filter-repo?

Git filter-repo 指令

git filter-repo

可快速且安全重寫 Git 儲存庫歷史的工具。

  • 重新命名檔案或目錄
  • 同步作用於所有分支

用途

  1. 移除敏感資料(如密碼、權杖)
  2. 清理不必要的檔案
  3. 重構儲存庫結構
  4. 減少儲存庫大小
Git 進階

Filter-Repo 流程

  1. 用 pip 安裝 git filter-repo

    pip install git-filter-repo
    
  2. 從每一次提交中移除 secrets.txt

    git filter-repo --path secrets.txt --invert-paths
    

Filter-Repo 相關參數

--path:指定要操作的路徑

--invert-paths:對除 --path 指定外的所有路徑進行操作

Git 進階

Filter-Repo 結果

輸出

  Parsed 150 commits
  New history written in 0.10 seconds; now repacking/cleaning...
  Repacking your repo and cleaning out old unneeded objects

關鍵影響

  • 已更新所有分支與提交
  • 所有提交雜湊值已更改
  • 之後需要強制推送(force push)
  • 團隊成員需要重新 clone 儲存庫
Git 進階

何時使用 filter-repo

使用情境

  • 移除敏感資料(如密碼)
  • 清理臃腫的儲存庫
  • 在所有提交間重新命名或重組檔案

小訣竅

  • 在使用 filter-repo 前務必先備份儲存庫
  • 在推送重寫後的歷史前,先與協作者協調
Git 進階

一起來練習吧!

Git 進階

Preparing Video For Download...