How To Reset Git Repository to Remove Sensitive Information Committed Before

English 简体中文 Tiếng Việt
Summary

To completely purge a Git repository's history, such as to remove sensitive information, developers can perform a destructive reset by creating an orphan branch. This involves committing the current project state to the new branch, then deleting all old branches and renaming the new one to the default. Subsequently, a force push overwrites the remote repository, requiring verification on the hosting platform and potential contact with the provider for cache removal. This process is irreversible and should be coordinated in shared environments, with git-filter-repo offering a less drastic alternative for selective history rewriting.

要重置 Git 仓库并删除其所有历史记录(例如,从提交中消除敏感信息),请仔细按照以下步骤操作。请注意,此过程具有破坏性,并将重写仓库,因此请确保这就是您想要的。

1. 备份当前仓库

在进行任何不可逆转的更改之前,请创建仓库的备份,以防您以后需要参考旧数据。

2. 创建一个没有历史记录的新分支

# 移动到您的仓库
cd /path/to/your/repo

# 检查出一个新的孤儿分支
git checkout --orphan clean-history

孤儿分支从没有历史记录开始。

3. 暂存和提交当前文件

# 从索引中删除所有被跟踪的文件
git rm -rf --cached .

# 将所有当前文件添加到索引
git add .

# 提交当前状态
git commit -m "初始清理提交"

4. 删除所有旧分支

# 删除除新分支之外的所有分支
git branch -D main

(如果不同,请将main替换为您的默认分支名称,例如,在某些情况下为master)

5. 替换默认分支

将新分支重命名为您的默认分支名称:

git branch -m main

6. 强制推送以覆盖远程仓库(如果仓库尚未推送到远程,则可选)

此步骤将覆盖远程服务器上的仓库并删除历史记录:

git push --force origin main

7. 从远程服务器删除敏感信息

为确保敏感信息不再可访问:

  • 验证远程仓库的 Web 界面(如 GitHub 或 GitLab)不再显示提交历史记录。
  • 如有必要,请联系仓库主机删除任何缓存或存档的快照。

8. 重新克隆仓库(可选)

为确保干净的工作目录,请删除本地副本并重新克隆仓库:

rm -rf /path/to/local/repo
git clone <repo-url>

警告

  • 共享仓库:如果此仓库与协作者共享,请在强制推送更改之前与他们协调。
  • 敏感数据:虽然此方法删除了提交历史记录,但数据可能仍然存在于备份或缓存中(例如,GitHub 的系统)。您可能需要联系您的托管提供商以确保完全删除。

替代方案:使用 git-filter-repo

如果您想删除特定敏感数据同时保留一些历史记录,请使用 git-filter-repo 等工具。这允许您选择性地重写历史记录,如果您不想丢失所有提交历史记录,这可能是一个更好的选择。

HOW TO GIT RESET SENSITIVE INFORMATION

  RELATED

  COMMENTS

0

No comment for this article.