前一段时间我添加的信息(文件)必须是私有的。从项目中删除不是问题,但我还需要从git历史中删除它。

我使用Git和Github(私人账号)。

注意:在这个线程中显示了一些类似的东西,但这里是一个添加到特性分支的旧文件,该分支合并到开发分支,最后合并到master,因此,做了很多更改。所以这是不一样的,需要的是改变历史,并隐藏这些文件的隐私。


当前回答

我找到了这个答案,它很有用:

git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch path_to_file' HEAD

在这里找到https://myopswork.com/how-remove-files-completely-from-git-repository-history-47ed3e0c4c35

其他回答

git-filter-repo

Git建议使用第三方插件Git -filter-repo(当执行Git filter-branch命令时)。有一长串为什么它比其他任何替代品都好(https://github.com/newren/git-filter-repo#why-filter-repo-instead-of-other-alternatives),我的经验是它非常简单,非常快。

这个命令从所有分支的所有提交中删除文件:

Git filter-repo——invert-paths——path <文件或目录>的路径

可以使用多个——path参数指定多个路径。你可以在这里找到详细的文档: https://www.mankier.com/1/git-filter-repo

使用bfg repo-cleaner包是git-filter-branch的另一个可行的替代方案。显然,它也更快……

删除文件并重写提交历史(这将从你提交的文件中创建新的提交哈希):

有两种方法:

使用git-filter-branch:

Git filter-branch——force——index-filter ' Git rm——cached——ignore-unmatch <path to file or directory>'——prune-empty——tag-name-filter cat -- --all

使用git-filter-repo:

pip3 install git-filter-repo
git filter-repo --path <path to the file or directory> --invert-paths

现在强制推repo: git推origin -force -all,并告诉你的合作者rebase。

我读了这篇GitHub文章,它让我想到了以下命令(类似于公认的答案,但更健壮一点):

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

为了删除特定文件的历史记录,应该在每个项目中逐一应用以下命令,但必须在一开始就从项目中进行备份,因为文件将被删除

Git filter-branch——index-filter " Git rm——cached——ignore-unmatch ProjectFolderName / src / main /资源/ application-prod。属性“头 Git push origin -force -all Git update-ref -d refs/original/refs/heads/master

..........................................................................

Git filter-branch——index-filter " Git rm——cached——ignore-unmatch ProjectFolderName / src / main /资源/应用程序。属性“头 Git push origin -force -all Git update-ref -d refs/original/refs/heads/master