git如何清空所有的commit記錄

Wumw發表於2018-11-12

前言


為什麼要清空 git 中的 commit 記錄?

大多數開發者喜歡在 github 建立自己的 Repository,而後進行持續開發,然後就是不斷的 add、commit、push 等,中間難免會把自己比較重要的隱私資訊 push 到遠端 origin,如果你刪除了再 push 遠端 origin, 提交 commit 記錄裡面也是存在的,並且大多是開發者建立的都是 Public Repository,免費的,所有人通過該倉庫的獨有連結可以直接 clone 到本地。那麼就會造成隱式資訊的直接暴露。

先通過git checkout --help瞭解一下--orphan,因為我們要用到它。

git checkout --help

git checkout --help

--orphan 的 --help

--orphan的說明

對於--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分支,HEAD指向當前分支,並自動切換到該分支;
// 分支沒有父級結點,它是一個新的根記錄,不與其他任何分支和提交記錄有連線。

// The index and the working tree are adjusted as if you had
// previously run "git checkout <start_point>". This allows you to
// start a new history that records a set of paths similar to
// <start_point> by easily running "git commit -a" to make the root
// commit.
// 中文翻譯:
// 它會基於你之前執行"git checkout <start_point>"的 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 <start_point>, 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謹慎刪除?)
    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 謹慎使用;
  • 以上不要隨意使用,切記!切記!切記!
  • 不然你可能會被人砍死???

相關文章