// PACKFILES (gitformat-pack): what a client sends on push and what a server sends on fetch. // READ: parse a v2 pack — undeltified objects (zlib at an offset, consumed bytes from the kernel // inflater), OFS_DELTA and REF_DELTA resolved against earlier objects in the pack or the object // store, the trailing SHA-1 verified — and write every resolved object to the store. WRITE: a pack // of undeltified objects with the trailer, which every git accepts (deltas are an optimization a // twin does not owe a client). import { inflateZlib } from './inflate.ts'; import { GitObjectStore, bytesToHex, concat, deflateZlib, sha1Hex, type GitObjectType } from './objects.ts'; const TYPE_BY_CODE: Record = { 1: 'commit', 2: 'tree', 3: 'blob', 4: 'tag' }; const CODE_BY_TYPE: Record = { commit: 1, tree: 2, blob: 3, tag: 4 }; const OFS_DELTA = 6, REF_DELTA = 7; function readVarSize(input: Uint8Array, at: number): { value: number; type: number; next: number } { let c = input[at]!; const type = (c >> 4) & 7; let value = c & 15; let shift = 4; let i = at + 1; while (c & 0x80) { c = input[i++]!; value += (c & 0x7f) * 2 ** shift; shift += 7; } return { value, type, next: i }; } function readDeltaSize(d: Uint8Array, at: number): { value: number; next: number } { let value = 0, shift = 0, i = at, c: number; do { c = d[i++]!; value += (c & 0x7f) * 2 ** shift; shift += 7; } while (c & 0x80); return { value, next: i }; } /** Apply a git delta (copy / insert ops) to a base payload. */ export function applyDelta(base: Uint8Array, delta: Uint8Array): Uint8Array { let p = 0; const src = readDeltaSize(delta, p); p = src.next; if (src.value !== base.length) throw new Error(`delta: base size ${src.value} != ${base.length}`); const dst = readDeltaSize(delta, p); p = dst.next; const out = new Uint8Array(dst.value); let o = 0; while (p < delta.length) { const op = delta[p++]!; if (op & 0x80) { let off = 0, len = 0; if (op & 0x01) off |= delta[p++]!; if (op & 0x02) off |= delta[p++]! << 8; if (op & 0x04) off |= delta[p++]! << 16; if (op & 0x08) off |= delta[p++]! * 2 ** 24; if (op & 0x10) len |= delta[p++]!; if (op & 0x20) len |= delta[p++]! << 8; if (op & 0x40) len |= delta[p++]! << 16; if (len === 0) len = 0x10000; out.set(base.subarray(off, off + len), o); o += len; } else if (op > 0) { out.set(delta.subarray(p, p + op), o); o += op; p += op; } else throw new Error('delta: reserved op 0'); } if (o !== dst.value) throw new Error(`delta: produced ${o} bytes, expected ${dst.value}`); return out; } export type PackedObject = { type: GitObjectType; sha: string }; // Delta bases are re-read from the store they were just written to; only this many bytes of // resolved payloads stay in memory (git's own core.deltaBaseCacheLimit is 96 MiB). Holding every // payload until the pack ends made a full-history push cost the repository's whole inflated size. const DELTA_BASE_CACHE_BYTES = 96 * 1024 * 1024; /** Read a pack, resolve every object, write them to `store`; returns each object's type and sha in pack order. */ export async function readPack(pack: Uint8Array, store: GitObjectStore): Promise { const dec = new TextDecoder(); if (dec.decode(pack.subarray(0, 4)) !== 'PACK') throw new Error('pack: bad signature'); const version = (pack[4]! << 24) | (pack[5]! << 16) | (pack[6]! << 8) | pack[7]!; if (version !== 2 && version !== 3) throw new Error(`pack: version ${version}`); const count = ((pack[8]! << 24) | (pack[9]! << 16) | (pack[10]! << 8) | pack[11]!) >>> 0; const trailer = bytesToHex(pack.subarray(pack.length - 20)); const expected = await sha1Hex(pack.subarray(0, pack.length - 20)); if (trailer !== expected) throw new Error('pack: checksum mismatch'); type Resolved = { type: GitObjectType; payload: Uint8Array }; const cache = new Map(); let cached = 0; const remember = (sha: string, obj: Resolved) => { if (obj.payload.length > DELTA_BASE_CACHE_BYTES || cache.has(sha)) return; cache.set(sha, obj); cached += obj.payload.length; for (const [old, { payload }] of cache) { if (cached <= DELTA_BASE_CACHE_BYTES) break; cache.delete(old); cached -= payload.length; } }; const payloadOf = async (sha: string): Promise => { const hit = cache.get(sha); if (!hit) return store.read(sha); cache.delete(sha); cache.set(sha, hit); return hit; }; const byOffset = new Map(); const out: PackedObject[] = []; let at = 12; for (let n = 0; n < count; n++) { const start = at; const h = readVarSize(pack, at); at = h.next; let type: GitObjectType; let payload: Uint8Array; if (h.type === OFS_DELTA || h.type === REF_DELTA) { let baseSha: string; if (h.type === OFS_DELTA) { let c = pack[at++]!; let off = c & 0x7f; while (c & 0x80) { c = pack[at++]!; off = ((off + 1) * 128) + (c & 0x7f); } const entry = byOffset.get(start - off); if (!entry) throw new Error(`pack: ofs-delta base at ${start - off} not found`); baseSha = entry.sha; } else { baseSha = bytesToHex(pack.subarray(at, at + 20)); at += 20; } const base = await payloadOf(baseSha); if (!base) throw new Error(`pack: ${h.type === OFS_DELTA ? 'ofs' : 'ref'}-delta base ${baseSha} not found`); const z = inflateZlib(pack, at); at += z.consumed; type = base.type; payload = applyDelta(base.payload, z.out); } else { const known = TYPE_BY_CODE[h.type]; if (!known) throw new Error(`pack: object type ${h.type}`); const z = inflateZlib(pack, at); at += z.consumed; if (z.out.length !== h.value) throw new Error(`pack: object size ${z.out.length} != ${h.value}`); type = known; payload = z.out; } const obj = { type, sha: await store.write(type, payload) }; remember(obj.sha, { type, payload }); byOffset.set(start, obj); out.push(obj); } return out; } function encodeVarSize(type: number, size: number): Uint8Array { const bytes: number[] = []; let c = (type << 4) | (size & 15); size = Math.floor(size / 16); while (size > 0) { bytes.push(c | 0x80); c = size & 0x7f; size = Math.floor(size / 128); } bytes.push(c); return new Uint8Array(bytes); } /** Write a pack of undeltified objects, trailer included. */ export async function writePack(objects: Array<{ type: GitObjectType; payload: Uint8Array }>): Promise { const header = new Uint8Array(12); header.set(new TextEncoder().encode('PACK'), 0); header[7] = 2; header[8] = (objects.length >>> 24) & 255; header[9] = (objects.length >>> 16) & 255; header[10] = (objects.length >>> 8) & 255; header[11] = objects.length & 255; const parts: Uint8Array[] = [header]; for (const o of objects) parts.push(encodeVarSize(CODE_BY_TYPE[o.type], o.payload.length), await deflateZlib(o.payload)); const body = concat(...parts); const trailer = await sha1Hex(body); return concat(body, new Uint8Array(trailer.match(/../g)!.map((h) => parseInt(h, 16)))); }