为什么 Git 将文件添加到暂存区时将文件存储在存储库中?

Why does Git store the file in the repository when I just add it to the staging area?

根据我的理解,当你 git add 一个文件时,它只是在将文件添加到存储库之前暂存文件,但为什么我可以在提交之前看到它添加到 git 存储库是吗?

例如,如果我创建一个新的 git 存储库并创建一个名为 foo 的新文件并将内容 "hello world" 添加到其中,然后 git add foo,我在 .git 文件夹内的 objects 子目录中看到一个新项目。我什至可以使用 git cat-file -p 命令查看 objects 文件中新文件的内容。

.git/objects 文件夹中究竟添加了什么? 暂存文件在技术上有什么作用?比如文件上的 git add 是 运行 之后发生的步骤是什么?如果我知道这些步骤,也许我会更好地理解它。

I can even view the contents of the new file inside the objects file with the git cat-file -p command.

git diff --cached.

What exactly has been added to the .git/objects folder?

参见“Git Internals - Git Objects

You can see a file in the objects directory. This is how Git stores the content initially – as a single file per piece of content, named with the SHA-1 checksum of the content and its header. The subdirectory is named with the first 2 characters of the SHA-1, and the filename is the remaining 38 characters.

why can I see it added into the git repository before I've committed it?

不要忘记使用 git add -p (--patch) 您可以在提交之前添加文件的部分 ()。

索引的目标仍然是(在 git 添加的上下文中)以准备下一次提交。
反映了原来对Git, as created by Linus Torvalds in 2005的需求,即整合补丁(一开始只是一个merge manager)

what are the steps that take place after a git add is run on a file

虽然索引不包含任何文件内容,但 .objects 包含松散(非打包)对象:

步骤见Object Storage

  • Git constructs a header that starts with the type of the object, in this case a blob. Then, it adds a space followed by the size of the content and finally a null byte
  • Git concatenates the header and the original content and then calculates the SHA-1 checksum of that new content.
  • Git compresses the new content with zlib,
  • Finally, Git write the zlib-deflated content to an object on disk. Git determine the path of the object you want to write out (the first two characters of the SHA-1 value being the subdirectory name, and the last 38 characters being the filename within that directory)

暂存区是存储库的一部分。

我认为您将存储库的对象数据库与历史混淆了。只有提交是历史的一部分,但所有对象 Git 句柄都是对象数据库的一部分。

想一想:Git 不会驻留在内存中,那么除了在其对象数据库中,它还会在哪里记录暂存区的一部分?