This lesson combines 3 topics: Why Git? The Object Model and Getting Started, The Staging Area in Detail and the Art of Committing, Branching — Working in Parallel.
Learning Objectives
- Understand why Git became the industry standard and what problems it solves
- Distinguish a distributed VCS (Git) from a centralized VCS (SVN, CVS)
- Master Git's object model: blob, tree, commit, tag
- Practice
git init,git clone,git status - Understand the three areas: Working Directory, Staging Area, Repository
- Master
git add,git restore --staged,git diff,git diff --staged - Write good commit messages following Conventional Commits
- Understand the atomic commit principle
- Use
git logto read history - Understand what a branch is in the Git object model (a pointer)
- Create, switch and delete branches with
git branch,git switch - Distinguish a fast-forward merge from a merge commit
- Know the branch naming conventions
- Safely delete local and remote branches
Part 1: Why Git? The Object Model and Getting Started
1. The problem before Git
Before Git: copy-paste version control
project_v1/
project_v2/
project_v2_final/
project_v2_final_FINAL/
project_v2_final_FINAL_v3_use_this_one/
Real problems:
- You don't know which file is the latest
- You don't know who changed what, when, or why
- Merging the changes of 2 people who edited the same file is a nightmare
- Trying out a new idea means copying the whole folder
Centralized VCS (SVN, CVS, Perforce)
Problems with a centralized VCS:
- Server down = nobody can work, and history can be lost
- Committing and sharing are the same action — you can't commit experimentally on your machine
- Branching/merging is painful, so people tend to avoid it
- Slow, because every operation needs a network request to the server
2. Distributed VCS — Git
Advantages of a distributed VCS:
- Every clone is a full backup: complete history, no server needed
- Offline work: commit, branch and merge all work without a network
- Fast: most operations read from the local disk
- Lightweight branching/merging: Git is designed so that branches are cheap
3. Git's Object Model
Git does not store data as "diffs between versions"; it stores a snapshot of the entire project at each point in time. Each object is identified by a 40-character SHA-1 hash. (Git also supports SHA-256 — git init --object-format=sha256 — and that is the intended future default, but today's ecosystem still mostly uses SHA-1.)
The four object types
Blob — File content
A blob does not store the filename — only the raw content. Two files with different names but the same content → the same blob hash → Git stores it only once (deduplication).
Tree — Directory structure
Tree = directory listing: mode + type + hash + name. Each entry only contains the basename within that directory (a file inside src/ is listed in the src/ tree, not in the root tree). A tree points to blobs (files) or other trees (subdirectories).
Commit — Snapshot + metadata
The first commit has no parent. A merge commit has 2+ parents.
Tag — Annotated tag
How objects link together
When you change src/index.js:
- A new blob is created for
src/index.js - A new tree for
src/(pointing to the new blob) - A new root tree (pointing to the new
src/tree) - A new commit pointing to the new root tree
- Unchanged files (README.md, utils.js) still point to the old blobs — no duplication
4. The three areas
| Area | Stored in | Purpose |
|---|---|---|
| Working Directory | Regular filesystem | Where you edit files |
| Staging Area (Index) | .git/index | The "list" of changes that will go into the next commit |
| Repository | .git/objects/ | Immutable commit history |
Why have a Staging Area? — It lets you commit selectively. For example, you edit 5 files but only want to commit the 2 related to one feature; the other 3 wait for a later commit.
5. Getting-started commands
git init — Initialize a new repository
git clone — Copy a repository
# Clone from GitHub
git clone https://github.com/user/repo.git
# Clone into a specific directory name
git clone https://github.com/user/repo.git my-folder
# Clone over SSH (requires an SSH key setup)
git clone git@github.com:user/repo.git
# Clone only one specific branch (faster for large repos)
git clone --single-branch --branch main https://github.com/user/repo.git
# Shallow clone — only fetch the N most recent commits (very fast, used in CI)
git clone --depth 1 https://github.com/user/repo.git
git status — Current state
git status
# Output example:
# On branch main
# Your branch is up to date with 'origin/main'.
#
# Changes to be committed: ← staged
# (use "git restore --staged <file>..." to unstage)
# modified: src/app.js
#
# Changes not staged for commit: ← modified but not staged
# (use "git add <file>..." to update what will be committed)
# modified: README.md
#
# Untracked files: ← Git doesn't know this file yet
# (use "git add <file>..." to include in what will be committed)
# new-feature.js
# Shorter
git status -s
# M src/app.js ← staged modified (column 1 = staged, column 2 = unstaged)
# M README.md ← unstaged modified
# ?? new-feature.js ← untracked
6. Initial configuration
# Required before your first commit
git config --global user.name "Your Name"
git config --global user.email "email@example.com"
# Default editor (used when writing long commit messages)
git config --global core.editor "code --wait" # VS Code
git config --global core.editor "vim" # Vim
# Show all config
git config --list --global
# Config for the current repo only (no --global)
git config user.email "work@company.com"
# Config levels: system < global < local (local overrides global)
Part 2: The Staging Area in Detail and the Art of Committing
1. The Staging Area — A filter before committing
The staging area (also called the Index or Cache) is the intermediate area between the Working Directory and the Repository. This is where you select which changes go into the next commit.
Real-world scenario
Working Directory:
- src/auth.js ← login bug fix (related to ticket AUTH-42)
- src/dashboard.js ← UI refactor (separate work, ticket UI-15)
- README.md ← docs update (not finished)
You want to commit ticket AUTH-42 first without committing UI-15 or the unfinished docs.
→ git add src/auth.js
→ git commit -m "fix: resolve login token expiry bug (AUTH-42)"
At commit time the Staging Area contains only src/auth.js.
2. Core commands
git add — Stage changes
# Stage a specific file
git add src/auth.js
# Stage multiple files
git add src/auth.js src/utils.js
# Stage all files in the current directory (be careful)
git add .
# Stage all tracked files (skip untracked)
git add -u
# Stage all changes and untracked files
git add -A
# Interactive staging — choose hunk by hunk (block of code)
git add -p src/auth.js
# → Git asks: Stage this hunk? (y/n/s/q/?)
# y = yes, n = no, s = split smaller, q = quit
git add -p is a powerful tool: it lets you stage individual blocks of changes within a file, helping you create atomic commits even when you changed many things in the same file.
git restore — Discard changes
# Discard changes in the working directory (CANNOT be undone!)
git restore src/auth.js
# Unstage a file (back to unstaged but KEEP the changes in the working dir)
git restore --staged src/auth.js
# Unstage everything
git restore --staged .
# Restore to the state of a specific commit
git restore --source=HEAD~2 src/auth.js
Warning:
git restore <file>(without--staged) permanently deletes the changes in the working directory (they don't go to the trash). Only use it when you are sure you don't need them.
git diff — View changes
# Show changes NOT yet staged (working dir vs staging area)
git diff
# Show STAGED changes (staging area vs HEAD commit)
git diff --staged
# or
git diff --cached # equivalent
# Diff between two commits
git diff abc123 def456
# Diff between two branches
git diff main feature/auth
# Only show the changed file names (not the content)
git diff --name-only
git diff --stat
# Diff of a specific file
git diff src/auth.js
Remember the rule:
git diff= working directory vs staginggit diff --staged= staging vs last commitgit diff HEAD= working directory vs last commit (unstaged + staged)
3. git commit — Save a snapshot
# Commit with a short message
git commit -m "feat: add user login"
# Open the editor to write a long message (subject + body)
git commit
# Stage all tracked files and commit (skips untracked)
git commit -am "fix: correct typo in auth module"
# ⚠️ Use -am carefully — you may commit things you didn't intend
# See what will be committed (dry run)
git diff --staged --stat
4. Conventional Commits — Writing commit messages the right way
Conventional Commits is a popular convention that many automation tools rely on (changelog, version bump, CI).
Format
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
Common types
| Type | When to use |
|---|---|
feat | Add a new feature |
fix | Fix a bug |
docs | Documentation changes |
style | Code formatting, no logic change |
refactor | Restructure code without fixing a bug or adding a feature |
test | Add or fix tests |
chore | Update build, dependencies, tooling |
perf | Improve performance |
ci | Change CI/CD config |
revert | Revert a previous commit |
Real-world examples
# Short — enough for most cases
git commit -m "feat(auth): add JWT refresh token endpoint"
git commit -m "fix(api): handle null user in profile route"
git commit -m "docs: update deployment guide for production"
git commit -m "chore: upgrade eslint to v9"
# With a body — when you need to explain why
git commit -m "$(cat <<'EOF'
refactor(db): migrate connection pool to pg-pool v3
pg-pool v2 has a memory leak when connections timeout.
v3 fixes the issue and adds better error handling.
Closes #234
EOF
)"
# Breaking change — add ! after the type
git commit -m "feat(api)!: change response format to JSON:API spec"
# → Signals a MAJOR version bump in Semantic Versioning
Rules for a good description
# BAD — unclear what changed
fix bug
update file
WIP
# BAD — too long, not imperative
Fixed the bug where users couldn't login when their session expired
# GOOD — short, imperative, clear
fix: handle expired session in login flow
feat: add dark mode toggle to settings page
perf: cache database queries in product listing
# Rule: use imperative verbs (add, fix, update, remove)
# not "added", "fixes", "updating"
5. Atomic Commits — An important principle
Each commit should do exactly one thing and do it completely.
Why do atomic commits matter?
# BAD — one commit doing many unrelated things
"feat: add login page, fix navbar bug, update README, refactor utils"
Consequences:
- Hard to review (the reviewer must understand 4 different contexts)
- Hard to revert (reverting this commit reverts all 4 things)
- git bisect doesn't work properly
- History can't be read as documentation
# GOOD — each commit is one logical unit
commit 1: "feat: add login page with form validation"
commit 2: "fix: correct active state in navbar"
commit 3: "docs: update README with new auth setup"
commit 4: "refactor: extract common utils to shared module"
Pattern: commit often rather than rarely
# Atomic workflow
# 1. Finish one small task → commit right away
git add src/auth/login.js
git commit -m "feat(auth): add login form component"
# 2. Write tests for it → commit
git add src/auth/login.test.js
git commit -m "test(auth): add tests for login form validation"
# 3. Fix CSS → commit
git add src/styles/auth.css
git commit -m "style(auth): add login page responsive styles"
6. git log — Reading history
# Basic log
git log
# One line per commit
git log --oneline
# Graph view — see the branches
git log --oneline --graph --all
# Log for a specific file
git log --oneline src/auth.js
# Log by author
git log --author="Alice"
# Log by time range
git log --since="2024-01-01" --until="2024-06-30"
# Log with diff (patch)
git log -p src/auth.js
# Number of most recent commits
git log -5 --oneline
# Find commits whose message contains a keyword
git log --grep="AUTH-42"
# Custom format
git log --pretty=format:"%h %an %ar %s"
# %h = short hash, %an = author name, %ar = relative time, %s = subject
# Show details of a specific commit
git show abc1234
git show HEAD # current commit
git show HEAD~1 # previous commit
7. .gitignore — Excluding files you don't want to track
# .gitignore — placed at the project root
node_modules/ # dependency directory
.env # secrets — NEVER commit
.env.local
.env.*.local
dist/ # build output
build/
*.log # log files
.DS_Store # macOS metadata
Thumbs.db # Windows thumbnail cache
.idea/ # IDE config (JetBrains)
.vscode/ # VS Code settings (unless you want to share with the team)
coverage/ # test coverage reports
*.pyc # Python compiled
__pycache__/
.pytest_cache/
target/ # Java/Rust build output
*.class
# Check whether a file is ignored
git check-ignore -v node_modules/lodash
# Show all ignored files
git status --ignored
# Force-add an ignored file (rarely needed)
git add -f .env.example
Part 3: Branching — Working in Parallel
1. What is a branch in Git?
Unlike SVN, a branch in Git is extremely lightweight — just a text file containing the SHA-1 hash of the commit it points to.
.git/refs/heads/main → abc1234...
.git/refs/heads/feature/auth → def5678...
HEAD — The "where you are" pointer
When you create a new branch and switch to it:
HEAD is a symbolic reference: it usually points to a branch, and that branch points to a commit. When you make a new commit, the current branch automatically advances to the new commit.
"Detached HEAD" state
# Checking out a commit hash directly → detached HEAD
git checkout abc1234
# HEAD → abc1234 (not via a branch)
# Danger: commits made in detached HEAD will be garbage collected
# unless you create a branch to keep them
git switch -c save-my-work # create a branch to save them
2. Creating and switching branches
Modern syntax (Git 2.23+)
# List all local branches
git branch
# Also list remote branches
git branch -a
# Create a new branch (without switching to it)
git branch feature/user-login
# Create and switch immediately
git switch -c feature/user-login
# or the old syntax (still valid)
git checkout -b feature/user-login
# Switch to an existing branch
git switch main
git switch feature/user-login
# Switch back to the previous branch (like cd -)
git switch -
# Show the current branch
git branch --show-current
The difference between git switch and git checkout
git checkout does too many things (switch branches, restore files, check out commits). Git 2.23 split it into:
git switch— change branchesgit restore— restore files
Prefer switch and restore for new work because they are clearer.
3. Merge — Combining branches
Fast-forward merge
A fast-forward happens when the branch being merged has no commits that diverged from the target branch. Git simply moves the branch pointer forward.
git switch main
git merge feature/login
# Output: Fast-forward
# No new commit is created
Merge commit (3-way merge)
When both branches have their own commits, Git creates a new "merge commit" with 2 parents.
git switch main
git merge feature/login
# Output: Merge made by the 'ort' strategy
# Git creates merge commit M with the message "Merge branch 'feature/login'"
Disabling fast-forward (--no-ff)
# Always create a merge commit, even when fast-forward is possible
git merge --no-ff feature/login
# Benefit: history clearly shows where the feature was merged
# Used in Git Flow (merging features into develop)
4. Branch naming conventions
Good branch names help the team recognize the purpose immediately.
Common patterns
feature/<short-desc> feat/user-auth
fix/<short-desc> fix/login-500-error
hotfix/<desc> hotfix/payment-null-ptr
release/<version> release/1.4.0
chore/<desc> chore/upgrade-eslint
docs/<desc> docs/api-reference
refactor/<desc> refactor/db-connection-pool
Naming rules
# AVOID
feature/add login page # spaces
Feature/UserAuth # uppercase (git is case-sensitive on Linux)
my-fix # no prefix
fix_login_bug # underscores instead of hyphens
f/lg # too cryptic
# PREFER
feature/user-login # lowercase, hyphens
fix/AUTH-42-session-expiry # includes the ticket ID
hotfix/v1.4.1-null-deref # for hotfixes
5. Deleting branches
Deleting a local branch
# Delete a merged branch (safe — Git checks)
git branch -d feature/user-login
# Force delete — even if not merged (be careful)
git branch -D feature/abandoned-experiment
# List branches merged into main (safe to delete)
git branch --merged main
# List unmerged branches (be careful before deleting)
git branch --no-merged main
Deleting a remote branch
# Delete a branch on the remote (GitHub/GitLab)
git push origin --delete feature/user-login
# or the old syntax
git push origin :feature/user-login
# Clean up stale remote-tracking references
git remote prune origin
# or combine it with fetch
git fetch --prune origin
6. Merge conflicts — The basics
A conflict happens when two branches change the same line in the same file.
# Scenario: main and feature/login both changed line 5 of src/app.js
git switch main
git merge feature/login
# CONFLICT (content): Merge conflict in src/app.js
# Automatic merge failed; fix conflicts and then commit the result.
# See the conflicted file
git status
# both modified: src/app.js
# File content after the conflict:
<<<<<<< HEAD
const timeout = 30 * 60 * 1000; // 30 minutes (main branch)
=======
const timeout = 60 * 60 * 1000; // 60 minutes (feature/login)
>>>>>>> feature/login
# Edit the file manually → keep the version you want:
const timeout = 60 * 60 * 1000; // 60 minutes (keep feature)
# After resolving all conflicts
git add src/app.js
git commit # create the merge commit
# If you want to abandon the merge midway
git merge --abort
7. Branch workflow overview
Review Questions
-
What is the core difference between Git and SVN regarding where the repository is stored?
Show answer
Git is a distributed VCS — every clone is a full repository with the entire history. SVN is a centralized VCS — only the server holds the full repository; clients only have a working copy. As a result: Git works completely offline (commit, branch, merge), a dead server doesn't lose history, and most operations read from the local disk so they are faster.
-
Why do two files with different names but identical content produce only one blob in Git?
Show answer
A blob object in Git stores raw content only (no filename). The blob hash is computed from the content: same content → same SHA-1 hash → same blob object. The filename is stored in the tree object one level up. This is content-addressable storage — Git deduplicates automatically without any complex logic.
-
When you commit a new file, how many objects does Git create at minimum? What types are they?
Show answer
At least 3 objects: (1) blob — the file content, (2) tree — a directory listing pointing to the blob with its filename, (3) commit — points to the root tree and contains metadata (author, date, message, parent). If there are subdirectories, an extra tree object is needed for each directory level.
-
What role does the staging area (Index) play that the Working Directory cannot replace?
Show answer
The staging area enables selective commits. You can modify 10 files in the working directory but only stage and commit the 3 related to a specific feature — the other 7 keep waiting in the working directory.
git add -peven lets you stage individual hunks within the same file. The working directory is just a regular filesystem with no notion of "what will be committed". -
Which command shows a short status, and what does the first character in its output mean?
Show answer
git status -s(or--short). The output has 2 columns: the first column (index/staged status), the second column (working tree status). First-column characters:M= modified staged,A= added staged,D= deleted staged,?= untracked (shown as??). Examples:M file.js(staged modified),M file.js(unstaged modified),?? new.js(untracked). -
What is the difference between
git diffandgit diff --staged?Show answer
git diffcompares the working directory with the staging area — it shows changes not yet staged.git diff --staged(or--cached) compares the staging area with the HEAD commit — it shows staged changes that will go into the next commit. To see all changes relative to HEAD (both staged and unstaged), usegit diff HEAD. -
Which command stages only part of the changes in a file (not the whole file)?
Show answer
git add -p <file>(or--patch). Git splits the file into "hunks" and asks about each one:yto stage,nto skip,sto split smaller,qto quit. This is an important tool for creating atomic commits even when you changed many things in the same file. -
How does the commit message
"fix bug in login"violate Conventional Commits?Show answer
It violates two points: (1) It lacks a type prefix — it should be
fix:following the<type>: <description>format. (2) The description uses a noun phrase instead of an imperative verb — it should be"fix: resolve login token expiry bug", not"fix bug in login". Also, "bug" is too vague — describe it more specifically so the history can be read as documentation. -
Why do atomic commits matter when debugging with
git bisect?Show answer
git bisectuses binary search to find the first commit that introduced a bug — it checks out commits one by one and runs tests. If a large commit contains many unrelated changes, when bisect reports "this commit is bad" you still don't know which part of it caused the bug. Atomic commits (each commit doing exactly one thing) ensure that when bisect finds the commit, you immediately know exactly which change is the cause. -
How do
git restore src/app.jsandgit restore --staged src/app.jsdiffer?
Show answer
git restore src/app.js (no flag) discards the changes in the working directory — the file goes back to the state in the staging area. It cannot be undone — the changes are lost permanently (they don't go through the trash).
git restore --staged src/app.js unstages the file — it moves the changes from the staging area back to unstaged, but keeps the changes in the working directory. Much safer, it only affects the Index.
- What actually is a branch in Git at the storage level (not conceptually)?
Show answer
A branch is a small text file at .git/refs/heads/<branch-name> containing the SHA-1 hash of the commit it points to. That is why creating a branch in Git is extremely fast (it just creates a small file) and costs no space — completely different from an SVN branch, which has to copy the whole codebase.
- How does a fast-forward merge differ from a 3-way merge? When is fast-forward impossible?
Show answer
Fast-forward: the target branch has no new commits since the feature branch split off → Git just moves the branch pointer to the latest commit, no merge commit is created. 3-way merge: both branches have their own commits after diverging → Git must create a new merge commit with 2 parents.
Fast-forward is impossible when the target branch (main) has gained more commits after the feature branch was created.
- Why is
git branch -dsafer thangit branch -D?
Show answer
git branch -d checks whether the branch has been merged into the current branch or its upstream. If not, Git refuses to delete it and reports an error — protecting you from losing commits that haven't been integrated. git branch -D force deletes without checking and can lose commits if the branch has unmerged work. Always use -d first; use -D only when you are sure you want to drop that branch entirely.
- Which command lists all branches (local + remote)?
Show answer
git branch -a (or --all). It shows local branches and remote-tracking branches (remotes/origin/main, remotes/origin/feature/...). To see only remote branches: git branch -r. Remote-tracking branches are updated when you git fetch.
- What does "Detached HEAD" mean and how do you get out of it safely?
Show answer
Detached HEAD happens when HEAD points directly to a commit hash instead of through a branch. It occurs when you check out a specific commit (git checkout abc1234). The danger: if you commit in this state, that commit isn't tracked by any branch and will be garbage collected.
To get out safely: git switch -c new-branch-name to create a new branch that keeps that commit, or git switch main to discard it and return to a branch.
Hands-on Exercises
Part 1: Why Git? The Object Model and Getting Started
# 1. Initialize a new repo and explore the .git structure
mkdir git-lab && cd git-lab
git init -b main
ls -la .git/
# 2. Configure user info
git config user.name "Your Name"
git config user.email "you@example.com"
# 3. Create the first file and observe the status
echo "# My Project" > README.md
git status
# → Untracked files: README.md
# 4. Stage the file and observe the change
git add README.md
git status
# → Changes to be committed: new file: README.md
# 5. First commit
git commit -m "feat: initial commit"
# 6. Explore the objects that were created
find .git/objects -type f
# Try reading an object (replace hash with a real hash)
git cat-file -t <hash> # show the type (blob/tree/commit)
git cat-file -p <hash> # show the content
# 7. Clone a public repo to practice
cd /tmp
git clone https://github.com/github/gitignore.git
ls gitignore/
Part 2: The Staging Area in Detail and the Art of Committing
# Setup
mkdir git-commit-lab && cd git-commit-lab
git init -b main
git config user.name "Your Name"
git config user.email "you@example.com"
# 1. Create a few files
echo "# App" > README.md
echo "console.log('hello')" > app.js
echo "PORT=3000" > .env
printf '*.log\n.env\nnode_modules/\n' > .gitignore
# 2. Observe git status
git status # what do you see?
# 3. Stage README.md and commit
git add README.md
git status # README staged, app.js untracked, .env ignored
# 4. Try diff
git diff # nothing (working = staging for README)
echo "console.log('world')" >> app.js
git diff # shows the app.js change (unstaged)
git add app.js
git diff # nothing
git diff --staged # shows both README.md and app.js staged
# 5. Atomic commit
git commit -m "feat: add initial app files"
# 6. Unstage and try git add -p
echo "// auth function" >> app.js
echo "// utils function" >> app.js
git add -p app.js # try staging each hunk separately
# 7. View the log
git log --oneline
git log --oneline --graph --all
Part 3: Branching — Working in Parallel
# Setup
mkdir git-branch-lab && cd git-branch-lab
git init -b main
git config user.name "Your Name"
git config user.email "you@example.com"
# 1. Create a base on main
echo "version 1" > app.js
git add app.js
git commit -m "feat: initial version"
# 2. Create a feature branch
git switch -c feature/v2
echo "version 2 feature" >> app.js
git add app.js
git commit -m "feat: add v2 feature"
# 3. Fast-forward merge
git switch main
git merge feature/v2
git log --oneline --graph
# → linear history, no merge commit
# 4. Set up a 3-way merge scenario
git switch -c feature/v3
echo "version 3 on feature" >> app.js
git add app.js && git commit -m "feat: v3 on feature"
git switch main
echo "hotfix on main" >> app.js
git add app.js && git commit -m "fix: hotfix on main"
git merge feature/v3
git log --oneline --graph
# → you see a merge commit
# 5. Create and resolve a conflict
git switch -c conflict-branch
echo "line A" > conflict.txt
git add conflict.txt && git commit -m "add conflict.txt A"
git switch main
echo "line B" > conflict.txt
git add conflict.txt && git commit -m "add conflict.txt B"
git merge conflict-branch
# → CONFLICT! Resolve manually, then git add + git commit
# 6. Clean up
git branch -d feature/v2 feature/v3 conflict-branch
git branch
References
- Git internals — Plumbing and Porcelain
- Git objects
- Getting started with Git
- Conventional Commits specification
- Git Basics — Recording Changes
- git add -p walkthrough
- Git Branching — Branches in a Nutshell
- Basic Branching and Merging
- git switch documentation