在开发项目过程中,很可能在提交 git 时泄露了一些敏感信息,本地尚且无妨。倘若要同步到 GitHub 等公开平台,那就一定要消除这些信息。

操作方式如下:

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

删除 .git 文件夹可能会导致 git 存储库出现问题。如果要删除所有提交历史记录但保持代码处于当前状态,则执行此操作非常安全,如下所示:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D master

  5. Rename the current branch to master

    git branch -m master

  6. Finally, force update your repository

    git push -f origin master

PS: this will not keep your old commit history around

这组命令对于发布开源分支来说很有帮助,新的分支含有之前的全部代码但不包含之前的提交记录,就算你不小心把敏感信息提交到了 GitHub,也可以用它来亡羊补牢。

命令说明

git checkout --orphan <new_branch>

Create a new orphan branch, named <new_branch>, started from <start_point> and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.

创建一个名为 <new_branch> 的新孤立分支,从 <start_point> 启动并切换到该分支。在这个新分支上进行的第一次提交将没有父项,它将成为与所有其他分支和提交完全断开的新历史的根。

大致意思就是:创建一个名为 <new_branch> 的 全新的孤立分支,可以当成一个全新的根节点。

参考链接

  1. how to delete all commit history in github?

  2. Git checkout 用法总结

  3. checkout - Git 官方文档