Lesson 4 of 6 · 12 min · 2 hands-on steps
How Git Works Inside
Commits are snapshots linked to their parents. Model it yourself and Git stops being magic.
Commits are snapshots in a chain
Every commit stores:
- A snapshot of all your files at that moment
- A message, author and time
- A pointer to its parent commit (two parents for a merge)
- A unique id (a hash like
a1b2c3d) calculated from all of the above
c1 ◄── c2 ◄── c3 ◄── c4 ← main
▲
└── f1 ◄── f2 ← feature
Branches are just names
A branch is a tiny file containing one commit id. Creating a branch is instant. It's just a new name pointing at a commit. HEAD means "the commit you're on now".
const branches = { main: "c4", feature: "f2" };
let HEAD = "main";
console.log(`On ${HEAD}, at commit ${branches[HEAD]}`);
branches.feature = "f3"; // a new commit on feature just moves its pointer
console.log(branches);Merging
To merge feature into main, Git finds the merge base (the last commit both share), compares both sides with it, and combines the changes. If both changed the same lines differently, you get a merge conflict to resolve by hand.
Why the hash matters
A commit's id is calculated from its content and its parent's id. Change anything in history and every later id changes. That's why rewriting history someone else has (with rebase or --force) causes problems, and why Git history is very hard to tamper with.
Once you see Git as "snapshots + pointers", commands like
reset,rebaseandcherry-pickbecome "move this pointer" or "copy these snapshots". Much less scary.
🧪 Practice: 2 steps
0 / 2 doneStep 1 of 2 · git log
Each commit points to its parent. Write log(commits, head) that returns the commit messages from head back to the first commit, the way git log does.
commits looks like { c3: { message: "Add footer", parent: "c2" }, … }; the first commit has parent: null.
function log(commits, head) {
const messages = [];
return messages;
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Where did branches split?
Write mergeBase(commits, a, b) that returns the id of the most recent commit both branches share. Git uses this to work out what to merge.
function mergeBase(commits, a, b) {
return null;
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What is a branch in Git?
What does each commit store?
Create a free account to track your progress.