簡體   English   中英

Git - 在特定提交之前刪除所有歷史記錄

[英]Git - remove all history prior to a specific commit

我將 git 用於各種項目(僅限個人存儲庫),我想做一些家務

我有一個下載的 git 項目樹,它有大量的提交歷史。 下載后我自己做了一些。 但是,除了我下載它時的最新提交以及我所做的后續提交之外,我不需要任何東西。 所有先前的提交都占用了大量空間,我想擺脫它們。

應該做的是在下載后刪除.git 文件夾並創建一個新的個人存儲庫 - 但我沒有。

所以我的問題是:我是否可以清理存儲庫,以便刪除提交 X 之前的所有內容,就好像它從未存在過一樣,但以便維護后續提交? 如果是這樣,怎么做? 另外如果可能的話,如果當時有多個分支,我也可以刪除其他分支嗎?

(不確定這是否可能,因為我認為 git 的主張之一是錯誤地丟失舊數據有多難)。

我建議您通過以下方式壓縮您的本地提交:

git log --oneline

# Write down the hash commit prior to your first commit

git rebase -i <commit-hash>

# Now a text editor will open, so change **pick** into **squash** for the second commit and following, then save and exit editor...

現在,您所有的新提交都將合並到您的最新提交中。

你准備好推動它了。

這里有一個簡短的教程

這是我測試的;

  • 首先備份您的存儲庫。
  • 查找最舊的提交(例如,使用git log --reverse )。
  • 運行git rebase -i <oldest-commit> ,並將除您要保留的提交之外的所有提交標記為drop
  • 移除所有遙控器(例如git remote remove origin )。
  • 運行git reflog expire --all --expire=now
  • 運行git gc --aggressive

如果您在這些步驟之前和之后運行git fsck ,您應該會看到對象數量顯着減少。

我有一個下載的 git 項目樹,它有大量的提交歷史。 下載后我自己做了一些

由於您只希望保留“更多”,我將假設您的“新”歷史是線性的。 如果是這樣的話,那么這是非常容易做到的。 對於此示例,我們假設您要保留的分支稱為main

# make sure your status is clean
git status # verify it's "nothing to commit, working tree clean"

# Figure out your first commit ID
git log --reverse -n 1 # let's call the result <repo-root-commit-id>

# Figure out the commit you started from (parent of your first new commit)
git log # let's call the starting commit X, as stated in the question

# Make a new temp branch from the commit you started from (commit X)
git switch -c temp-branch X

# soft reset to the repo root commit
git reset --soft <repo-root-commit-id>

# Now the entire history from initial commit through X will be staged
# Make all of this a single commit
git commit -m "Squash repo history into a single commit"

# Now rebase all of your new commits onto the temp branch
git rebase X main --onto temp-branch

# Now your rewritten main branch is as desired, delete the temp branch
git branch -d temp-branch

由於您的目標是恢復舊歷史使用的空間,因此您可以刪除您的 remote刪除除 main 之外的所有本地分支,然后立即收集垃圾或將您的新 repo 重新克隆到另一個地方。 例如,這些鏈接總結如下:

# Remove the remote:
git remote remove origin

# Delete all local branches except main
git branch | grep -v main | xargs git branch -D

# Garbage Collect everything now
git reflog expire --expire=now --all
git gc --aggressive --prune=now

感謝所有評論,尤其是 mkreiger1。

這導致我重新發布git clone SRC DEST --depth=nn 這樣做了,節省了大約 90% 的空間。

由於它是本地克隆,因此必須在 SRC 前加上file://或 depth 被忽略。

還注意到它有一個.github文件夾,而不是.git。 不知道為什么,但所有相關的歷史似乎都存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM