Git: The Commit Graph, Branches, Merge, and Rebase
Git as a graph of hash-linked commits, branches as movable pointers, merge versus rebase, and the recovery commands (reflog, reset, revert) that save your work.
beginner45 min#git#version-control#dag#merge#rebase#reflog
Prerequisites: Testing: Unit, Integration, and Test Doubles
Why it matters
Git is the universal tool for tracking changes and collaborating. Most of the fear people feel around it ("I will lose my work", "I broke the repo") disappears once you see that Git is just a graph of immutable snapshots and a few movable labels. With that model, merges, rebases, and recovery commands stop being magic spells and become predictable operations.
Intuition
Picture a save-game system where every save is permanent, labeled with its predecessor, and never overwritten. A commit is such a save: a full snapshot of your project plus a pointer to the save it came from. A branch is a sticky note on one save that says "I am here". Making a new commit moves the sticky note forward. Creating a branch is just adding another sticky note, which is why it costs almost nothing.
Because saves are never edited, "destroying" history usually means moving a sticky note away from a save. The save itself stays around for a while, so it can be found again.
How it works
Commits are hash-linked objects. A commit stores a snapshot, author, message, and the hash of its parent commit(s). Its own id is a hash (SHA-1 or SHA-256) of that content. Change anything, even the message, and the hash changes. Because each commit includes its parent's hash, history forms a tamper-evident chain, like a blockchain without the coin.
A <-- B <-- C <-- F main (arrows point to parents)
\
D <-- E feature
Since commits can have more than one parent and never form cycles, the history is a directed acyclic graph (DAG).
References. A branch is a file holding a commit hash. HEAD says which branch (or commit) you currently have checked out. Tags are fixed labels. Remote branches such as origin/main are your last known copy of the remote's pointers.
Three areas. The working directory (your files), the staging area (index: what the next commit will contain), and the repository (committed history). git add copies to the index, git commit snapshots the index.
Merge joins two lines of work by creating a commit with two parents. If one branch is simply behind, Git just moves the pointer forward (fast-forward). Otherwise it finds the common ancestor and combines changes (a three-way merge). Conflicts arise when both sides changed the same lines, and you resolve them by hand. History keeps its true shape, which is accurate but can look busy.
Rebase takes your commits and replays them, one by one, on top of another base. The new commits have the same changes but different parents, so they get new hashes; the originals are abandoned. The result is a straight line that is easy to read.
before: A <-- B <-- C main after rebase onto main:
\ A <-- B <-- C <-- D' feature
D feature
Here is the same starting history joined each way. Step 1 is shared, steps 2 and 3 show a merge, steps 4 to 6 show a rebase.
Merge keeps both lines and adds a two-parent commit. Rebase rewrites feature's commits onto the new base, giving linear history at the price of new hashes.
The golden rule: do not rebase commits that others already have (anything pushed to a shared branch), because you rewrite history they built on. Rebase your private work; merge shared work.
Recovery commands
git status,git log --oneline --graph --all: look before you act.git restore filediscards unstaged changes to a file;git restore --staged fileunstages.git commit --amendrewrites the last commit (new hash).git revert Cadds a new commit that undoes C. Safe on shared branches.git reset --soft/--mixed/--hard Xmoves the current branch to X, optionally resetting the index and the working files.--harddiscards uncommitted work, the only one that can truly lose edits.git refloglists whereHEADand branches have been, even after a bad reset. Find the old hash, thengit branch rescue HASHorgit reset --hard HASH. Unreachable commits are only garbage-collected after weeks.git stashshelves uncommitted changes temporarily.git cherry-pick Ccopies one commit onto the current branch.git bisectbinary-searches history for the commit that introduced a bug.
| Operation | Time | Notes |
|---|---|---|
| Create a branch | O(1) | Writes one small file |
| Commit | O(files changed) | Unchanged files are shared, not copied |
| Find a merge base | O(commits) | Graph traversal from both tips |
| bisect | O(log n) steps | Binary search over history |
Code: a commit DAG in miniature
This script models Git's core: content-hashed commits with parent links, branches as pointers, a merge commit with two parents, a rebase that replays a commit and changes its hash, and a reflog that makes a hard reset recoverable. It uses only a standard hashing library, so the hashes are identical in both languages.
import hashlib
class Repo:
def __init__(self):
self.commits = {} # hash -> (message, parents)
self.branches = {} # name -> hash
self.head = "main"
self.reflog = []
def _tip(self):
return self.branches.get(self.head)
def commit(self, message, extra_parent=None):
parents = [p for p in (self._tip(), extra_parent) if p]
body = message + "|" + ",".join(parents)
h = hashlib.sha1(body.encode()).hexdigest()[:7]
self.commits[h] = (message, parents)
self.branches[self.head] = h
self.reflog.append(h)
return h
def branch(self, name):
self.branches[name] = self._tip()
def checkout(self, name):
self.head = name
def ancestors(self, h):
seen, stack = set(), [h]
while stack:
cur = stack.pop()
if cur not in seen:
seen.add(cur)
stack.extend(self.commits[cur][1])
return seen
def merge(self, other):
return self.commit(f"Merge {other} into {self.head}", self.branches[other])
def rebase(self, onto):
# replay this branch's own commits on top of `onto`
base_set = self.ancestors(self.branches[onto])
mine, cur = [], self._tip()
while cur not in base_set:
mine.append(cur)
cur = self.commits[cur][1][0]
self.branches[self.head] = self.branches[onto]
for old in reversed(mine):
self.commit(self.commits[old][0])
repo = Repo()
a = repo.commit("A")
repo.commit("B")
repo.branch("feature")
repo.commit("C") # main moves on
repo.checkout("feature")
repo.commit("D") # feature diverges
old_d = repo.branches["feature"]
repo.rebase("main") # replay D on top of C
new_d = repo.branches["feature"]
print("rebase changed hash:", old_d != new_d, "| message kept:", repo.commits[new_d][0])
repo.checkout("main")
m = repo.merge("feature") # like git merge --no-ff
print("merge parents:", len(repo.commits[m][1]), "| commits reachable:", len(repo.ancestors(m)))
before = repo.branches["main"]
repo.branches["main"] = a # simulate: git reset --hard A
print("after reset, main points at:", repo.commits[repo.branches["main"]][0])
print("reflog still has merge commit:", before in repo.reflog)
print("hash length:", len(a))import { createHash } from "node:crypto";
class Repo {
constructor() {
this.commits = new Map(); // hash -> [message, parents]
this.branches = new Map(); // name -> hash
this.head = "main";
this.reflog = [];
}
tip() {
return this.branches.get(this.head);
}
commit(message, extraParent = null) {
const parents = [this.tip(), extraParent].filter(Boolean);
const body = message + "|" + parents.join(",");
const h = createHash("sha1").update(body).digest("hex").slice(0, 7);
this.commits.set(h, [message, parents]);
this.branches.set(this.head, h);
this.reflog.push(h);
return h;
}
branch(name) {
this.branches.set(name, this.tip());
}
checkout(name) {
this.head = name;
}
ancestors(h) {
const seen = new Set();
const stack = [h];
while (stack.length) {
const cur = stack.pop();
if (!seen.has(cur)) {
seen.add(cur);
stack.push(...this.commits.get(cur)[1]);
}
}
return seen;
}
merge(other) {
return this.commit(`Merge ${other} into ${this.head}`, this.branches.get(other));
}
rebase(onto) {
// replay this branch's own commits on top of `onto`
const baseSet = this.ancestors(this.branches.get(onto));
const mine = [];
let cur = this.tip();
while (!baseSet.has(cur)) {
mine.push(cur);
cur = this.commits.get(cur)[1][0];
}
this.branches.set(this.head, this.branches.get(onto));
for (const old of mine.reverse()) this.commit(this.commits.get(old)[0]);
}
}
const repo = new Repo();
const a = repo.commit("A");
repo.commit("B");
repo.branch("feature");
repo.commit("C"); // main moves on
repo.checkout("feature");
repo.commit("D"); // feature diverges
const oldD = repo.branches.get("feature");
repo.rebase("main"); // replay D on top of C
const newD = repo.branches.get("feature");
console.log("rebase changed hash:", oldD !== newD, "| message kept:", repo.commits.get(newD)[0]);
repo.checkout("main");
const m = repo.merge("feature"); // like git merge --no-ff
console.log("merge parents:", repo.commits.get(m)[1].length, "| commits reachable:", repo.ancestors(m).size);
const before = repo.branches.get("main");
repo.branches.set("main", a); // simulate: git reset --hard A
console.log("after reset, main points at:", repo.commits.get(repo.branches.get("main"))[0]);
console.log("reflog still has merge commit:", repo.reflog.includes(before));
console.log("hash length:", a.length);The Python version prints True and False with a capital letter, JavaScript prints true and false; everything else is identical. The Python output is:
rebase changed hash: True | message kept: D
merge parents: 2 | commits reachable: 5
after reset, main points at: A
reflog still has merge commit: True
hash length: 7
The five reachable commits are A, B, C, the rebased D, and the merge commit. The original D was abandoned by the rebase, so it is not an ancestor of anything, yet its object still exists. Note that main was at C and feature sat directly on C, so a real git merge would fast-forward by default; the script forces a merge commit, like git merge --no-ff.
Common pitfalls
- Rebasing shared branches: it rewrites commits teammates already pulled, causing duplicate commits and painful conflicts. If you must force-push, use
git push --force-with-lease. - Committing secrets: removing a password in a later commit does not remove it from history. Rotate the secret, then rewrite history if needed.
- Giant mixed commits: commit one logical change at a time with a message that says why. Small commits make
revertandbisectwork. - Detached HEAD confusion: checking out a commit hash puts you off any branch. Commits made there are easy to lose; create a branch (
git switch -c name) before continuing. git add .surprises: it stages everything, including build outputs and local config. Use.gitignoreand review withgit statusandgit diff --staged.- Resolving conflicts blindly: after fixing markers, run the tests before committing the merge.
- Panicking after a mistake: stop, run
git reflog, and find the old hash. Nearly everything committed is recoverable.
Practice
Undo the last commit, keep the changes easy
Hint
Which reset mode leaves files alone?
Show solution
git reset --soft HEAD~1 moves the branch back one commit and keeps your changes staged. --mixed (the default) keeps them in the working directory unstaged. Both are safe for unpushed commits. If the commit is already pushed to a shared branch, use git revert HEAD instead.
Recover after a bad reset --hard medium
Hint
Where does Git remember where HEAD used to be?
Show solution
Run git reflog, find the entry from before the reset (for example a1b2c3d HEAD@{2}: commit: add search), then git reset --hard a1b2c3d or git branch rescue a1b2c3d. This works because the commit objects still exist, only the pointer moved. It cannot restore edits that were never committed.
Merge or rebase? medium
Hint
Who else has these commits?
Show solution
Your feature branch has five private commits and main moved ahead. Rebase onto main (git rebase main) for a clean linear history, then fast-forward merge. If the branch is shared with teammates, or you want a record of when the work landed, merge instead. Many teams squash-merge pull requests so main gets one commit per feature.
Find the commit that broke the build hard
Hint
History is sorted by time, so you can binary search it.
Show solution
Mark a known bad commit and a known good one: git bisect start, git bisect bad, git bisect good v1.2. Git checks out the midpoint, you test and answer good or bad, and about log2(n) steps later it names the first bad commit. With a test script, git bisect run ./test.sh automates the whole search, so 1000 commits take about 10 runs.
Interview questions
- What is a branch in Git? A lightweight movable pointer to a commit. Creating one is instant because no files are copied.
- Merge versus rebase? Merge preserves history with a merge commit; rebase replays commits for a linear history with new hashes. Never rebase shared history.
- What is the difference between
reset,revert, andrestore? Reset moves a branch pointer (history-rewriting), revert adds an inverse commit (history-preserving), restore changes files without moving any branch. - How would you undo a pushed commit?
git revert, which is safe for others. Resetting and force-pushing rewrites shared history. - How do you recover a deleted branch or lost commit? Use
git reflogto find the hash and recreate the branch there. - Why are commit hashes content-addressed? The id is derived from the content and parents, which provides integrity checking and deduplication.
Interviewers look for: explaining Git as a graph with pointers, knowing when rewriting history is safe, calm recovery steps using reflog, and good commit hygiene (small, focused commits with meaningful messages).
Quick check
You rebase your local feature branch onto main. What happens to your original commits?
Finished this lesson?
Further resources
- Pro Git: Git objects (book)
- Pro Git: Branches in a nutshell (book)
- Pro Git: Rebasing (book)
- git reflog documentation (docs)