Inside Git: How It Works and the Role of the .git Folder
Git works differently than old version control systems. Instead of storing just differences between files, Git stores snapshots of project. Think of it like taking a photo of your project every time you commit.
Understanding the .git Folder
The .git folder is the brain of Git. It’s hidden in your project folder and contains all the information Git needs: commits, branches, history, configuration, and objects. Without this folder, Git cannot track your project.
Example: If you clone a project from GitHub, you get a .git folder inside the project. Even if you delete the files but keep .git Git still remembers the history of the project.
Git Objects: Blob, Tree, Commit
Git stores everything as objects:
Blob: Stores the content of a file. Nothing else, just the file data.
Example: If you have
main.jswith some code, Git creates a blob for it.Tree: Stores folder structure and points to blobs and other trees.
Example: Your
srcfolder containsmain.js(blob) anddatabase.js(blob). Git creates a tree object to remember this folder structure.Commit: Stores a snapshot of the project at a point in time. It points to a tree and its parent commit.
Example: You added
main.jsanddatabase.jsand commit them. Git creates a commit object pointing to the tree of these files.
How Git Tracks Changes
When you use git add and git commit Git does this internally:
git add: Git takes your changed files and creates blob objects for them in the staging area (index).
- Example:
git add main.js
- Example:
Git now knows “this file is ready to be committed.”
git commit: Git creates a tree object for your folder structure and a commit object pointing to that tree. It also links to the previous commit and gives a unique hash.
- Example:
git commit -m "Added feature"
- Example:
Git now has a snapshot of the project at this point in time.
Think of git add as preparing files and git commit as taking the photo of your project.
How Git Uses Hashes
Git generates a unique hash for each object based on its content.
If the content changes, the hash changes.
It also allows multiple developers to work safely without overwriting each other’s work.
Simple Mental Model
Imagine this workflow:
.gitfolder = the brainFiles you stage = blobs
Folder structure = trees
Each commit = snapshot of the project
Hashes = unique IDs that protect everything