Git 内部:工作原理与 .git 文件夹的作用
Source: Dev.to

大多数开发者每天都会使用 Git,执行 git init、git add、git commit 等命令,但只有少数人真正了解 Git 在内部是如何处理这些提交的。
在本文中,我们将深入 Git,了解它的内部工作原理,并探讨 .git 文件夹 的重要作用。
什么是 Git?(快速回顾)
Git 是一个版本控制系统,帮助开发者跟踪更改、协作并高效管理项目历史。
如果你想了解更多关于 Git 的信息,也可以阅读这篇博客。👇
Git 工作原理(内部视图)
Git 在三个主要区域工作:
- 工作目录 – 您的实际项目文件。
- 暂存区 – 准备更改的地方。
- 仓库 – Git 永久存储快照的地方。
每次提交时,Git:
- 对所有已跟踪的文件进行快照。
- 将其安全地存放在
.git目录中。 - 将提交链接在一起。

Git 的核心:.git 文件夹
When you run:
git init
Git creates a hidden folder inside your project root. It’s there—you just can’t see it in the file explorer.
👉 This folder is the entire brain of Git.
If it’s deleted, your project is no longer a Git repository.
.git 文件夹里有什么?
You can also view it from the command line:
cd .git
ls -la
objects/ – 所有内容的存储位置
This directory holds all Git data: commits, files, and directory structures.

- Commit objects – snapshots of the repository at a point in time.
- Tree objects – represent directory hierarchies.
- Blob objects – store file contents.
Note:
git logshows only commit objects, while.git/objectsalso contains trees and blobs, which is why you’ll see more directories than commits.
refs/ – 分支和标签指针
This folder keeps references to branches and tags.

- Branches (
refs/heads) – point to the latest commit of each branch. - Tags (
refs/tags) – mark specific commits.
Each branch is simply a pointer to a commit hash.

HEAD – 你当前所在的位置
The HEAD file tells Git:
- Which branch you are on.
- Which commit is currently checked out.

index – 暂存区
The index (or staging area) stores:
- Files you added with
git add. - The exact snapshot that will become the next commit.
It acts as a bridge between the working directory and the repository.
config – 仓库设置
The config file contains:
- Remote URLs.
- User configurations (name, email).
- Repository‑specific settings.

TL;DR
- Git 将所有内容存储在隐藏的
.git目录中。 objects/保存原始数据(提交、树、blob)。refs/跟踪分支和标签。HEAD指向当前分支/提交。index是暂存区。config保存仓库配置。
了解这些组件可以揭开 Git 如何跟踪更改的神秘面纱,也能解释 git commit、git checkout、git push 等操作为何如此工作。祝提交愉快! 🚀
基本工作流程
# Initialize a git repository
git init
# Stage changes
git add .
# Commit the staged changes
git commit -m "message"
Git 的工作原理
- 初始化 仓库会创建
.git目录。 git add将已暂存的文件存储为.git/objects/中的 blob 对象。git commit -m "message"构建一个表示目录结构的 tree 对象。- Git 随后创建一个包含以下内容的 commit 对象:
- 指向根树的指针。
- 指向父提交的指针(如果有的话)。
- 作者和提交者信息。
- 时间戳。
- 提交信息。

图片来源:freeCodeCamp
最后的思考
Git 看起来表面上很简单,但在内部它是一个 强大的数据库。
.git 文件夹不仅仅是一个配置文件夹;它包含了整个 项目的历史和结构。
感谢阅读! 如果你喜欢这篇文章,可以在下面阅读更多相关主题:
