为什么要清空 git 中的 commit 记录?

大多数开发者喜欢在 github 创建自己的 Repository,而后进行持续开发,然后就是不断的 add、commit、push 等,中间难免会把自己比较重要的隐私信息 push 到远端 origin,如果你删除了再 push 远端 origin, 提交 commit 记录里面也是存在的,并且大多是开发者创建的都是 Public Repository,免费的,所有人通过该仓库的独有链接可以直接 clone 到本地。那么就会造成隐式信息的直接暴露。

先通过 git checkout --help 了解一下 --orphan ,因为我们要用到它。

git checkout --help


QSharedMemory 清空 清除command history_工作空间

--orphan 的 --help


QSharedMemory 清空 清除command history_git 如何清理操作日志_02

对于--orphan < new_branch > 的解释就是:

// Create a new orphan branch, named , started from
// 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分支,HEAD指向当前分支,并自动切换到该分支;
// 分支没有父级结点,它是一个新的根记录,不与其他任何分支和提交记录有连接。
// The index and the working tree are adjusted as if you had
// previously run "git checkout ". This allows you to
// start a new history that records a set of paths similar to
// by easily running "git commit -a" to make the root
// commit.
// 中文翻译:
// 它会基于你之前执行"git checkout "的 start_point 分支,调整新的索引和分支树
// 你可以通过"git commit -a"提交一个新commit记录作为根提交记录,这样的话你就有个一个新的历史记录,
// 类似于 start_point 分支的一系列提交记录痕迹;
// This can be useful when you want to publish the tree from a commit
// without exposing its full history. You might want to do this to
// publish an open source branch of a project whose current tree is
// "clean", but whose full history contains proprietary or otherwise
// encumbered bits of code.
// 中文翻译:
// 如果你想把你的分支树变成只有一个commit记录,不想暴露他所有提交历史,那么它就很有用。
// 如果你想通过这样做发布一个开源分支工程,当前所有包含专利记录分支树就会被清空,否则就是一堆冗余的代码;
// If you want to start a disconnected history that records a set of
// paths that is totally different from the one of , then
// you should clear the index and the working tree right after
// creating the orphan branch by running "git rm -rf ." from the top
// level of the working tree. Afterwards you will be ready to prepare
// your new files, repopulating the working tree, by copying them from
// elsewhere, extracting a tarball, etc.
// 中文翻译:
// 如果你想开始一个全新的提交记录,完全与start_point分支不同,在你创建这个独立分支后,
// 通过 'git rm -rf',从根工作空间删除所有工作空间和索引里面的文件。
// 随后,你可以通过从别处复制准备你的新文件来从新填充你的工作空间。

复制代码

解决方案

那么如何解决这个问题?

思路如下:

使用 git checkout --orphan new_branch ,基于当前分支创建一个独立的分支new_branch;

git checkout --orphan new_branch

复制代码

添加所有文件变化至暂存空间

git add -A

复制代码

提交并添加提交记录

git commit -am "commit message"

复制代码

删除当前分支

(我的当前分支是master,个人小的项目没有使用 gitflow 工作流管理,切记master谨慎删除:grin:)

git branch -D master

复制代码

重新命名当前独立分支为 master

git branch -m master

复制代码

推送到远端分支

-f 是 --force 的缩写, 一定要谨慎使用,好多项目中你或者是别人的代码被覆盖都是这么操作的,除非只有你一个人在开发;

git push -f origin master

复制代码

好了,没了!

PS:

一定要记住,切记谨慎删除本地 master分支;

-D 是--delete的缩写;

-f是 --force 强制操作;

git rm -rf 谨慎使用;

以上不要随意使用,切记!切记!切记!

不然你可能会被人砍死:grin::grin::grin: