首页 > 解决方案 > Git filter-branch 仅适用于分叉提交

问题描述

我分叉了另一个存储库,然后向其中添加了许多文件。我偶尔会合并原始存储库中的更改以保持最新。

我意识到我的 fork 中有一些文件应该被删除,所以我试图按照 [1] 从我的 git 存储库中删除一些文件。源代码库有数千个提交,而我有几百个。

当我执行命令时,它也会尝试搜索所有源提交,而不仅仅是我的 fork 提交,这将花费数小时而不是数分钟。

git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch filename.txt' --prune-empty @

两者之间有许多来自上游的合并。

master         A---B---C---D---E---F---G (HEAD)
                  /       /
upstream/master  H---I---J---K

[1] https://help.github.com/en/github/authenticating-to-github/removing-sensitive-data-from-a-repository

标签: gitgit-filter-branch

解决方案


我建议使用git filter-repo替换BFG 和git filter-branch.

注意:如果您在运行上述命令时收到以下错误消息:

Error: need a version of `git` whose `diff-tree` command has the `--combined-all-paths` option`

这意味着你必须更新git


请参阅“基于路径的过滤”:

git filter-repo --path file-to-remove --invert-paths

您可以将其与 ref 过滤结合使用:首先将原始 repo(您已分叉的)的 URL 添加到本地 repo:

cd /path/to/local/clone/of/my/fork
git remote add upstream /url/original/repo
git fetch upstream

这样,您可以将过滤限制为仅您的 fork 提交。
这是一个示例,假设您已在upstream/master.

git filter-repo --path file-to-remove --invert-paths \
  --refs upstream/master..<myBranch>

推荐阅读