使用 Git Prune 命令清理 Git 倉庫

John Wachira 2023年1月30日
  1. 使用 git prune 命令
  2. git prunegit fetch --prunegit remote prune 之間的區別
使用 Git Prune 命令清理 Git 倉庫

在本文中,我們將討論 git prune 命令及其用途。我們知道 Git 對我們的資料非常謹慎。

當我們刪除提交之類的資料時,Git 不會輕易丟失它們。這會導致我們機器中的陳舊資料堆積。

這就是 git prune 命令發揮作用的地方。

我們可以將 git prune 命令稱為 Git 中的一個內務實用程式,用於清理孤立或無法訪問的 Git 物件。當我們談論不可訪問的物件時,它們是我們倉庫中當前 refs 無法訪問的物件。

一個很好的例子是當我們使用 git reset <Commit ID> 命令回滾到之前的提交時。Git 會將刪除的提交儲存為懸空物件。

我們使用 git prune 命令來消除此類資料。

使用 git prune 命令

git prune 命令有幾個有用的選項,如下所示。

$ git prune --dry-run

我們執行上面的命令來獲取命令的輸出。它不執行 prune

$ git prune --verbose

上面的命令將向我們展示所有動作和相關物件。

$ git prune --progress

我們使用上面的命令來檢查 git prune 的進度。

$ git prune --expire <time>

我們使用上面的命令來刪除早於指定時間 (<time>) 的物件。

為了更好地理解這個概念,讓我們看一個實際的例子。讓我們執行 git log 命令來檢查本地倉庫中的提交歷史記錄。

$ git log --oneline

提交歷史

讓我們使用 git reset 命令回滾一次提交,這樣我們的 HEAD 處於 第六次更新

$ git reset --hard 27bd68b
HEAD is now at 27bd68b Sixth Update

讓我們嘗試找到已刪除的提交。

$ git fsck --lost-found

懸空

刪除的提交是第一個;我們可以用前七個字元來確認。

在執行 git prune 命令之前,我們必須執行一個 reflog,它將使早於 now 的條目過期。

$ git reflog expire --expire=now --expire-unreachable=now --all

最好是 dry run 這個命令,看看會發生什麼變化。

$ git prune --dry-run

git &ndash;dry-run

我們現在可以執行 prune 命令。

$ git prune --verbose --progress --expire=now

讓我們檢查懸空提交是否仍然存在於我們的倉庫中。

$ git fsck --lost-found

最後

git prunegit fetch --prunegit remote prune 之間的區別

git fetch --prunegit remote prune 命令具有相似的功能。我們使用它們來刪除遠端倉庫中刪除的分支的引用。

當作為一個團隊工作時,它會派上用場,並且你希望擺脫在合併到主分支後被刪除的遠端分支。

git fetch --prune 命令是以下各項的組合:

$ git fetch --all && git remote prune

它會在開始 prune 之前從我們的遠端倉庫中獲取。如前所述,基本的 git prune 命令將刪除本地物件。

作者: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

相關文章 - Git Prune