Version ControlIntermediate
Git & Version Control Mastery
Git is a content-addressable directed acyclic graph (DAG) storage system disguised as a version control tool.
Key Mental Models & Invariants
- -Commits are immutable snapshots, referenced by SHA-1/SHA-256 hashes.
- -Branches are nothing more than 41-byte pointer files containing a commit hash.
- -HEAD is a reference indicating what commit/branch you are currently working on.
- -Merge combines histories preserving chronologic graph nodes; Rebase rewrites history linearly.
- -The 3-tree model: Working Directory -> Staging Area (Index) -> Repository (HEAD).
Deep Dive Architecture
### The 3 Trees of Git
Git does not store diffs; it stores **snapshots**. When you run:
1. `git add <file>`: Git computes the SHA-1 of the file content, compresses it into a blob in `.git/objects`, and records the path & hash in the **Index** (Staging Area).
2. `git commit -m "msg"`: Git writes a tree object representing the directory structure, creates a commit object pointing to that tree and the parent commit, and moves the current branch pointer forward.
```text
Working Directory Staging Area (Index) Local Repo (.git)
┌─────────────────┐ ┌────────────────────┐ ┌───────────────────┐
│ modified files │ ───> │ git add . │ ───> │ git commit │
│ on your disk │ │ prepared snapshot │ │ immutable commit │
└─────────────────┘ └────────────────────┘ └───────────────────┘
```
### Merge vs Rebase
- **Merge**: Creates a new "merge commit" with 2 parents. Completely non-destructive, preserves exact historical context.
- **Rebase**: Replays your branch commits one by one on top of the target branch, creating new commits with new hashes. Results in a clean, linear git log.
Feature: C --- D
/
Main: A --- B ----------- M (Merge Commit)
\ /
(or Rebase: A --- B --- C' --- D')
Code Examplebash
# Undo last commit without losing changes on disk git reset --soft HEAD~1 # Stash untracked files too git stash -u # Interactive rebase last 3 commits git rebase -i HEAD~3
Soft reset unwinds the commit object back to the staging area. git stash -u stashes uncommitted and untracked files.