← All lessons
How Git works
What add and commit write
Working tree
Index
Objects
Refs
add.js
// git add <file>function add(name) { const id = hashObject("blob", read(name)); // hash the file and store it as a blob index.set(name, id); // the index records name -> blob id}commit.js
// git commit -m <message>function commit(message) { const tree = writeTree(index); // a snapshot of the index as one tree const parent = readRef("HEAD"); // the first commit has none const id = hashObject("commit", [ `tree ${tree}`, parent && `parent ${parent}`, `author ${me} ${now}`, "", message, ]); write(".git/refs/heads/main", id + "\n"); // a branch is a file holding one id}Hash a file yourself same bytes, same id
Bytes Git hashes
SHA-1
stored at
Object store
On disk the object is zlib-compressed, but its id comes from the uncompressed bytes
hash-object.js
function hashObject(type, body) { const header = `${type} ${byteLength(body)}\0`; const id = sha1(header + body); const path = `.git/objects/${id.slice(0, 2)}/${id.slice(2)}`; if (exists(path)) return id; // same content, same id: nothing to write write(path, deflate(header + body)); // compressed on disk return id;}Branch and merge only pointers move
branch.js
// git switch -c featurefunction createBranch(name) { write(`.git/refs/heads/${name}`, readRef("HEAD") + "\n"); write(".git/HEAD", `ref: refs/heads/${name}\n`);} function commitOnHead(tree, message) { const parent = readRef("HEAD"); const id = writeCommit({ tree, parents: [parent], message }); write(currentBranchFile(), id + "\n"); // only the current branch moves}merge.js
// git merge featurefunction merge(other) { const ours = readRef("HEAD"); const theirs = readRef(other); const base = mergeBase(ours, theirs); // the newest commit both branches share if (base === ours) return moveBranch(theirs); // nothing new on ours: just move the pointer const tree = threeWayMerge(base, ours, theirs); const id = writeCommit({ tree, parents: [ours, theirs] }); moveBranch(id);} // git branch -d featurefunction deleteBranch(name) { remove(`.git/refs/heads/${name}`); // the commits stay in the object store}Topics
Next: How containers work
Open lesson