快捷菜单
常用功能一站直达
更多功能请点顶栏「快捷菜单」

你想了解 git-filter-repo 工具的具体用法,核心是用它清理 Git 仓库提交历史中的敏感信息(比如密码、API 密钥、隐私文件等)。git-filter-repo 是官方推荐替代老旧且低效的 git filter-branch 的工具,更简洁、性能更好,我会从安装、核心用法、常见场景和注意事项完整讲解。
centos7.x默认yum安装的git版本为git version 1.8.3.1
首先需要确保你的系统安装了 git-filter-repo,不同系统安装方式如下:
1# Ubuntu/Debian
2sudo apt update && sudo apt install -y git-filter-repo
3
4# CentOS/RHEL(需先装epel源)
5sudo yum install -y epel-release
6sudo yum install -y git-filter-repo1# 用Homebrew安装
2brew install git-filter-repo如果系统包管理器没有,可手动下载安装:
1# 下载可执行文件
2curl -o /usr/local/bin/git-filter-repo https://raw.githubusercontent.com/newren/git-filter-repo/main/git-filter-repo
3
4# 添加执行权限
5chmod +x /usr/local/bin/git-filter-repo
6
7# 验证安装
8git filter-repo --versiongit-filter-repo 会不可逆地重写整个 Git 提交历史,操作前务必备份原仓库:
1# 克隆原仓库到本地(完整历史),作为备份
2git clone --mirror 原仓库URL backup-repo
3
4# 或直接复制本地仓库目录
5cp -r 你的仓库目录 你的仓库目录-backup以下是最常见的 3 种清理场景,覆盖绝大多数需求:
比如仓库历史中不小心提交了 config.json(含密码)、secret.key(含密钥),需要彻底移除这些文件的所有历史记录:
1# 进入本地仓库根目录
2cd 你的仓库目录
3
4# 清理单个敏感文件(比如 config.json)
5git filter-repo --path config.json --invert-paths
6
7git filter-repo --path hugo-teek-site/content/docs/config.yml --invert-paths
8
9# 清理多个敏感文件(比如 secret.key + token.txt)
10git filter-repo --path secret.key --path token.txt --invert-paths--path 文件名:指定要处理的文件路径(支持相对路径,比如 src/secret.key);--invert-paths:反向匹配,即删除指定路径的文件,而非保留。如果敏感信息是散落在代码/文档中的文本(比如 API_KEY=“123456”),需要批量替换为占位符(比如 API_KEY="***"):
replace.txt),格式为 原内容==>替换后的内容:1# replace.txt 内容示例
21234567890abcdef==>***REDACTED_API_KEY***
3admin@xxx.com==>user@example.com
4password=123456==>password=***1git filter-repo --replace-text replace.txt--replace-text 规则文件:按规则文件中的内容,批量替换所有提交历史中的文本;/、=),需转义。如果仓库里有超大文件(比如视频、压缩包)导致克隆缓慢,也可以用 git-filter-repo 清理:
1# 清理指定大小以上的文件(比如大于100MB)
2git filter-repo --strip-blobs-bigger-than 100M
3
4# 清理指定的大文件(比如 bigfile.zip)
5git filter-repo --path bigfile.zip --invert-paths清理完成后,验证敏感信息是否已移除:
1# 搜索仓库历史中是否还有敏感文本(比如搜索API密钥)
2git log --all --grep="1234567890abcdef"
3
4# 查看某个文件是否还存在于历史中
5git log --all --oneline -- config.json
6
7git log --all --oneline -- config.yml如果没有输出结果,说明清理成功。
因为重写了历史,需要强制推送到远程仓库(注意:会覆盖远程仓库的历史,团队协作需提前告知):
1# 强制推送所有分支和标签到远程(origin为远程仓库别名)
2git push origin --force --all
3
4# 推送标签(如果有)
5git push origin --force --tagsgit-filter-repo 是清理 Git 历史敏感信息的高效工具,优先替代 git filter-branch;--path 文件名 --invert-paths 删除敏感文件,--replace-text 规则文件 替换敏感文本;如果清理后想恢复原仓库,只需将备份的仓库重新推送到远程即可:
cd backup-repo && git push --mirror 原仓库URL。
结束。
日历 · 精选 · 友链 · 更多
如果内容对你有帮助,欢迎请我喝杯咖啡 ☕



One的公众号
爱折腾博客的小白