Git
How Git works — snapshots and the object model (blobs, trees, commits), the three areas, branching and merging, rebase, resolving conflicts, remotes, undoing mistakes with reset, revert and reflog, and useful power tools.
Git is a distributed version control system: every clone has the full history, commits are local and fast, and collaboration happens by exchanging commits. Understanding its simple internal model makes every command make sense. (Team workflows — trunk-based development, pull requests — are in Version control workflows.)
Snapshots, not diffs
Each commit records a snapshot of the whole project (efficiently — unchanged files are shared), plus metadata and a pointer to its parent commit(s). History is a directed acyclic graph of commits.
The object model
Everything is stored in .git/objects, addressed by the SHA hash of its content (content-addressable storage):
| Object | Contains |
|---|---|
| Blob | File contents (no name) |
| Tree | A directory: names → blobs and subtrees |
| Commit | Root tree, parent commit(s), author, committer, message |
| Tag (annotated) | Points to a commit with a message and signature |
A branch is just a movable pointer (a 41-byte file) to a commit. HEAD points to the current branch. Creating a branch is therefore instant, and changing any byte of history changes every later hash — which is why history is tamper-evident.
The three areas
| Area | What | Commands |
|---|---|---|
| Working directory | Files you edit | — |
| Staging area (index) | The snapshot you're preparing for the next commit | git add, git restore --staged |
| Repository | Committed history | git commit |
git init / git clone <url>
git status # what changed, what's staged
git diff # working dir vs staged
git diff --staged # staged vs last commit
git add file.py # stage a file
git add -p # stage hunk by hunk (great for clean commits)
git commit -m "Add retry to payment client"
git log --oneline --graph --all # visual history
git show <commit> # one commit's changesBranching and merging
git switch -c feature/search # create and switch to a new branch
# … commit work …
git switch main
git merge feature/search- Fast-forward merge: if
mainhasn't moved, Git just moves the pointer forward — no merge commit. - Three-way merge: if both branches have new commits, Git combines them using their merge base (common ancestor) and creates a merge commit with two parents.
Before: After merge:
A─B─C main A─B─C─────M main
\ \ /
D─E feature D─E─┘Rebase
Rebase replays your commits on top of another branch, creating new commits with new hashes and a linear history:
Before: git rebase main (on feature):
A─B─C main A─B─C main
\ \
D─E feature D'─E' featuregit switch feature
git rebase main # replay D, E onto C
git rebase -i HEAD~4 # interactive: squash, reorder, reword, drop commits
git pull --rebase # rebase local commits on top of fetched ones| Merge | Rebase |
|---|---|
| Preserves exact history, including when branches diverged | Linear, cleaner history |
| Non-destructive | Rewrites commits (new hashes) |
| Merge commits can clutter history | Conflicts may need resolving commit by commit |
Resolving conflicts
When both sides changed the same lines, Git stops and marks the file:
<<<<<<< HEAD
timeout = 30
=======
timeout = 60
>>>>>>> feature/slow-apiEdit to the correct result, remove the markers, git add the file, then git commit (merge) or git rebase --continue. git merge --abort / git rebase --abort back out. Enable git config --global rerere.enabled true to remember resolutions.
Remotes
git remote -v # list remotes (origin = where you cloned from)
git fetch # download new commits; doesn't change your branches
git pull # fetch + merge (or rebase) into the current branch
git push -u origin feature/x # publish a branch and set upstream
git branch -vv # local branches with their upstream statusorigin/main is a remote-tracking branch: your local record of where main was on the remote at the last fetch.
Undoing things
| Situation | Command |
|---|---|
| Discard unstaged changes to a file | git restore file |
| Unstage a file | git restore --staged file |
| Fix the last commit (message or forgotten file) | git commit --amend (before pushing) |
| Undo a pushed commit safely | git revert <commit> — adds a new inverse commit |
| Move the branch back, keep changes staged | git reset --soft HEAD~1 |
| Move back, keep changes unstaged | git reset HEAD~1 (mixed, default) |
| Move back and discard changes | git reset --hard HEAD~1 (destructive) |
| Recover "lost" commits | git reflog then git switch -c rescue <hash> |
| Shelve work temporarily | git stash / git stash pop |
The reflog records every position HEAD has been at for ~90 days — after a bad reset or rebase, your commits are almost always still recoverable.
Power tools
git bisect start; git bisect bad; git bisect good v1.2 # binary-search for the commit that broke something
git bisect run ./test.sh # …automatically
git blame -L 40,60 app.py # who last changed each line (and in which commit)
git log -S "retry_count" # commits that added or removed a string ("pickaxe")
git cherry-pick <commit> # apply one commit onto the current branch
git worktree add ../hotfix main # a second working directory for another branch
git tag -a v1.4.0 -m "Release" # annotated release tag
git clean -fdn # preview deleting untracked files (-f to do it)Good practice
- Small, focused commits with messages explaining why: an imperative summary line ≤ 50 chars ("Add retry to payment client"), a blank line, then details. Conventional Commits (
feat:,fix:) enable automated changelogs (Semantic versioning). - A
.gitignorefor build output, dependencies and secrets. Never commit secrets — if you do, rotate them; deleting the file doesn't remove history. - Large binaries: Git LFS.
- Sign commits/tags (GPG or SSH signing) where provenance matters.
- Git stores snapshots as content-addressed objects: blobs, trees, commits; branches are movable pointers.
- Changes move from working directory → staging area → repository.
- Merges preserve history (fast-forward or merge commit); rebase rewrites commits into a linear history — never rebase shared branches.
- fetch downloads; pull = fetch + merge/rebase; push publishes.
- Undo with restore, revert (safe for shared history), reset (soft/mixed/hard), and recover with reflog.
- bisect, blame, log -S and cherry-pick are invaluable for debugging history.
QWhat is the difference between git merge and git rebase?easy
Both integrate changes from one branch into another. Merge creates a merge commit joining the two histories, preserving exactly what happened and never rewriting existing commits. Rebase re-applies your commits on top of the target branch, producing new commits and a linear history. Rebase is great for cleaning up local feature branches, but shouldn't be used on commits others already have, because it rewrites history.
QHow do you undo a commit that has already been pushed to main?easy
Use git revert on that commit: it creates a new commit applying the inverse change, so history isn't rewritten and collaborators aren't disrupted. Resetting and force-pushing a shared branch would rewrite history others depend on.