Git - 删除特定提交之前的所有历史记录



我将 git 用于各种项目(仅限个人仓库),我想做一些内务管理

我有一个下载的 git 项目树,它有大量的提交历史。下载后,我自己又做了一些。但是,除了下载时的最新提交以及我所做的后续提交之外,我不需要任何东西。所有先前的提交都占用了大量空间,我想摆脱它们。

应该做的是在下载后删除 .git 文件夹并创建一个新的个人存储库 - 但我没有。

所以我的问题是:我是否可以清理存储库,以便删除提交 X 之前的所有内容,就好像它从未存在过一样,但可以维护后续提交?如果是这样,如何?另外,如果可能的话,如果当时有多个分支,我也可以删除其他分支吗?

(不确定这是否可能,因为我认为 git 的一个主张是错误丢失旧数据有多难)。

我有一个下载的 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

由于您的目标是恢复旧历史记录使用的空间,因此您可以删除远程,删除除 main 之外的所有本地分支,然后立即进行垃圾回收或将新存储库重新克隆到另一个位置。例如,这些链接总结如下:

# 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

我建议你通过以下方式压制你的本地提交:

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,您应该会看到对象数显著减少。

感谢您的所有评论,尤其是 mkreiger1。

这让我想到了一个帖子 regit clone SRC DEST --depth=nn.这样做了,节省了大约 90% 的空间。

由于它是本地克隆,因此需要为SRC添加file://或深度。

还注意到它有一个.github文件夹,而不是.git。不知道为什么,但所有相关的历史似乎都存在。

最新更新