[Git] 将某些文件从 Git / Github 中彻底删除

Author Avatar
空気浮遊 2022年07月11日
  • 在其它设备中阅读本文章

如果你不小心误上传了一些文件,并且在很久之后才发现,就会发现 rm 没法做到把 Git 中全部文件从全部 commit 和 branch 中彻底删除。

创建新分支

首先建议创建一个本地的新分支。

这样之后比较方便同步到 github 上。

安装 git-filter-repo

前往此处安装 git-filter-repo :https://github.com/newren/git-filter-repo

如果是 windows 用户,将下载的 git-filter-repo 文件拖放到某个特定路径即可,或者拖放到任意 $PATH 中包含的文件夹里。

这个特定路径你可以通过如下命令在 git bash 中查看:

git --exec-path

随后特别注意,如果 Windows 使用的是 python 而非 python3 命令来运行 python,则需要将脚本第一行的内容从 python3 改为 python

彻底删除文件

使用如下命令彻底删除文件:

git filter-repo --path <file/directory> --invert-paths

执行该命令可能会提示你该 git 库并非全新 clone 而来,操作不安全。如果想强制运行,往命令后面加上 --force 再次运行即可。

同步到 Github 上

在 Github 上上传该新分支,随后在 Github 上将旧分支彻底删除。如果有必要,前往 Github 的管理界面更改 default-branch 。

参考 & 扩展阅读

INSTALL.md - git-filter-repo

WARNING: git-filter-branch has a glut of gotchas generating mangled history rewrites - Serverfault