丢弃的 commit 去哪了

丢弃的 commit 去哪了

前言

在 Git 中只要提交记录产生,无论你是 resetrebase 还是 commit --amend 等操作都没事,最终都能在 git reflog 中找到。那么问题来了,reflog 为什么能够找到?

HEAD 指针

首先,要明白提交的 commit 纪录一旦产生就一直都在,无论是 reset 还是 rebase 等操作并没有对 commit 纪录进程删除和更改,只是修改了指向 commit 的 HEAD 指针而已。

是否真的丢弃了 commit

当我们通过 git commit --amendgit rebase 创建一个新的提交或者通过 git reset --hard HEAD^ 撤销 commit 时,旧的提交仍然保留着呢。您通过 git log 看不到它们的原因是因为没有指向它们的指针,这些 commit 就是 dangling commit(悬挂的 commit)。

dangling commit

你可以通过 git fsck --lost-found 命令查看 dangling commit 列表。

例如,我们通过 git reset --hard HEAD^ 撤销 commit 产生了 dangling commit,然后通过 git fsck --lost-found 命令查看 dangling commit 列表:

`git fsck --lost-found` 命令查看 dangling commit 列表

这些 dangling commit 平时放着没事,如果太多当你做一些 git 操作的时候,比如大量的 dangling commit 导致 git rebase 出现如下提示:


Auto packing the repository in background for optimum performance. See "git help gc" for manual housekeeping. error: The last gc run reported the following. Please corrent the root cause and remove .git/gc.log. Automatic cleanup will not be performed until the file is removed. warning: There are too many unreachable loose objects; run 'git prune' to remove them.

这时你就得手动删除了,也很简单:

git reflog expire --expire=now --all
git gc --prune=now
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文转载自图灵社区用户青年的翻译文章。 我使用 Git 大约已经有18个月时间,自认为能很好地驾驭它了。但是当我们...
    图灵教育阅读 997评论 1 25
  • 基本配置 Git 的配置文件为 .gitconfig,它在用户主目录下~/.gitconfig,针对当前用户是全局...
    mocobk阅读 386评论 0 0
  • Git Git是一些命令行工具的集合,可以用来跟踪、记录文件的变动,经常用于开源代码。比如你可以进行旧版本恢复、比...
    Lord_East阅读 3,349评论 0 2
  • 1,查看所有远程分支:%git branch -r 2, 拉取远程分支并创建本地分支git checkout -...
    will666阅读 2,103评论 0 18
  • 文章略长,预计阅读时间28分钟 一.git init 知识点: 创建版本库的两种方式可以创建git-demo目录,...
    shuxiaotai阅读 413评论 0 0