← Semua pelajaran
Cara kerja Git
Yang ditulis add dan commit
Working tree
Index
Object
Ref
add.js
// git add <file>function add(name) { const id = hashObject("blob", read(name)); // hash file-nya lalu simpan sebagai blob index.set(name, id); // index mencatat nama -> id blob}commit.js
// git commit -m <message>function commit(message) { const tree = writeTree(index); // snapshot index sebagai satu tree const parent = readRef("HEAD"); // commit pertama tidak punya const id = hashObject("commit", [ `tree ${tree}`, parent && `parent ${parent}`, `author ${me} ${now}`, "", message, ]); write(".git/refs/heads/main", id + "\n"); // branch adalah file berisi satu id}Hash file sendiri byte sama, id sama
Byte yang di-hash Git
SHA-1
disimpan di
Object store
Di disk object-nya dikompres zlib, tapi id-nya dihitung dari byte sebelum dikompres
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; // isi sama, id sama: tidak perlu ditulis write(path, deflate(header + body)); // dikompres di disk return id;}Branch dan merge yang bergerak cuma pointer
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"); // cuma branch aktif yang bergerak}merge.js
// git merge featurefunction merge(other) { const ours = readRef("HEAD"); const theirs = readRef(other); const base = mergeBase(ours, theirs); // commit terbaru yang dimiliki kedua branch if (base === ours) return moveBranch(theirs); // tidak ada yang baru di sisi kita: cukup geser 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}`); // commit-nya tetap ada di object store}Topik
Berikutnya: Cara kerja container
Buka pelajaran