// Git building blocks: pkt-lines, object ids, commit/tree parsing, pack reading and writing. import pako from 'pako'; import { Sha1, hex } from './sha1'; export const te = new TextEncoder(); export const td = new TextDecoder(); export const ZERO = '0'.repeat(40); export type ObjType = 'commit' | 'tree' | 'blob' | 'tag'; export const TYPE_NUM: Record = { commit: 1, tree: 2, blob: 3, tag: 4 }; export const NUM_TYPE: Record = { 1: 'commit', 2: 'tree', 3: 'blob', 4: 'tag' }; // ---------- pkt-line ---------- export function pkt(s: string | Uint8Array): Uint8Array { const body = typeof s === 'string' ? te.encode(s) : s; const out = new Uint8Array(body.length + 4); out.set(te.encode((body.length + 4).toString(16).padStart(4, '0')), 0); out.set(body, 4); return out; } export const FLUSH = te.encode('0000'); export function concat(parts: Uint8Array[]): Uint8Array { let n = 0; for (const p of parts) n += p.length; const out = new Uint8Array(n); let o = 0; for (const p of parts) { out.set(p, o); o += p.length; } return out; } /** Reads pkt-lines from a buffer. Returns lines (null = flush) and the offset after the last one read. */ export function readPkts(buf: Uint8Array, start = 0, stopAtFlush = false): { lines: (Uint8Array | null)[]; end: number } { const lines: (Uint8Array | null)[] = []; let o = start; while (o + 4 <= buf.length) { const len = parseInt(td.decode(buf.subarray(o, o + 4)), 16); if (Number.isNaN(len)) break; if (len === 0) { lines.push(null); o += 4; if (stopAtFlush) break; continue; } if (len < 4 || o + len > buf.length) break; lines.push(buf.subarray(o + 4, o + len)); o += len; } return { lines, end: o }; } /** Side-band-64k framing: band 1 = data, 2 = progress, 3 = error. */ export function* sideband(band: number, data: Uint8Array): Generator { for (let i = 0; i < data.length; i += 65515) { const chunk = data.subarray(i, Math.min(i + 65515, data.length)); const b = new Uint8Array(chunk.length + 1); b[0] = band; b.set(chunk, 1); yield pkt(b); } } // ---------- objects ---------- export function objectId(type: ObjType, data: Uint8Array): string { return hex(new Sha1().update(te.encode(`${type} ${data.length}\0`)).update(data).digest()); } export interface TreeEntry { mode: string; name: string; sha: string } export function parseTree(data: Uint8Array): TreeEntry[] { const out: TreeEntry[] = []; let o = 0; while (o < data.length) { const sp = data.indexOf(0x20, o); const nul = data.indexOf(0, sp); out.push({ mode: td.decode(data.subarray(o, sp)), name: td.decode(data.subarray(sp + 1, nul)), sha: hex(data.subarray(nul + 1, nul + 21)) }); o = nul + 21; } return out; } export function writeTree(entries: TreeEntry[]): Uint8Array { // Git sorts tree entries by name, with directories compared as if they end in '/'. const key = (e: TreeEntry) => e.mode === '40000' ? e.name + '/' : e.name; const sorted = [...entries].sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0)); const parts: Uint8Array[] = []; for (const e of sorted) { parts.push(te.encode(`${e.mode} ${e.name}\0`)); const s = new Uint8Array(20); for (let i = 0; i < 20; i++) s[i] = parseInt(e.sha.substr(i * 2, 2), 16); parts.push(s); } return concat(parts); } export interface Commit { tree: string; parents: string[]; author: string; committer: string; message: string; time: number } export function parseCommit(data: Uint8Array): Commit { const text = td.decode(data); const split = text.indexOf('\n\n'); const head = text.slice(0, split < 0 ? text.length : split); const c: Commit = { tree: '', parents: [], author: '', committer: '', message: split < 0 ? '' : text.slice(split + 2), time: 0 }; for (const line of head.split('\n')) { const sp = line.indexOf(' '); const k = line.slice(0, sp), v = line.slice(sp + 1); if (k === 'tree') c.tree = v; else if (k === 'parent') c.parents.push(v); else if (k === 'author') c.author = v; else if (k === 'committer') { c.committer = v; const m = v.match(/ (\d+) [+-]\d{4}$/); if (m) c.time = +m[1]; } } return c; } /** "Name 1700000000 +0000" -> name */ export const personName = (s: string) => s.replace(/\s*<.*$/, '').trim(); // ---------- deltas ---------- function readVar(d: Uint8Array, o: { i: number }) { let r = 0, s = 0, b; do { b = d[o.i++]; r |= (b & 0x7f) << s; s += 7; } while (b & 0x80); return r; } export function applyDelta(base: Uint8Array, delta: Uint8Array): Uint8Array { const o = { i: 0 }; const baseLen = readVar(delta, o); if (baseLen !== base.length) throw new Error('delta base size mismatch'); const outLen = readVar(delta, o); const out = new Uint8Array(outLen); let w = 0; while (o.i < delta.length) { const op = delta[o.i++]; if (op & 0x80) { let off = 0, size = 0; if (op & 1) off |= delta[o.i++]; if (op & 2) off |= delta[o.i++] << 8; if (op & 4) off |= delta[o.i++] << 16; if (op & 8) off |= delta[o.i++] << 24; if (op & 16) size |= delta[o.i++]; if (op & 32) size |= delta[o.i++] << 8; if (op & 64) size |= delta[o.i++] << 16; if (size === 0) size = 0x10000; out.set(base.subarray(off >>> 0, (off >>> 0) + size), w); w += size; } else if (op) { out.set(delta.subarray(o.i, o.i + op), w); w += op; o.i += op; } else throw new Error('bad delta op'); } if (w !== outLen) throw new Error('delta result size mismatch'); return out; } // ---------- pack reading ---------- export interface RawObj { type: ObjType; data: Uint8Array; sha: string } /** Parses a v2 pack. getBase looks up ref-delta bases that are already stored (thin packs). */ export async function readPack(buf: Uint8Array, getBase: (sha: string) => Promise): Promise { if (buf.length < 32 || td.decode(buf.subarray(0, 4)) !== 'PACK') throw new Error('not a pack'); const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); const count = dv.getUint32(8); const want = hex(buf.subarray(buf.length - 20)); const got = hex(new Sha1().update(buf.subarray(0, buf.length - 20)).digest()); if (want !== got) throw new Error('pack checksum mismatch'); let o = 12; type Ent = { off: number; kind: number; data: Uint8Array; baseOff?: number; baseSha?: string }; const ents: Ent[] = []; for (let n = 0; n < count; n++) { const off = o; let b = buf[o++]; const kind = (b >> 4) & 7; let size = b & 15, shift = 4; while (b & 0x80) { b = buf[o++]; size += (b & 0x7f) * 2 ** shift; shift += 7; } const e: Ent = { off, kind, data: new Uint8Array() }; if (kind === 6) { b = buf[o++]; let x = b & 0x7f; while (b & 0x80) { b = buf[o++]; x = ((x + 1) * 128) + (b & 0x7f); } e.baseOff = off - x; } else if (kind === 7) { e.baseSha = hex(buf.subarray(o, o + 20)); o += 20; } const inf = new pako.Inflate(); inf.push(buf.subarray(o), true); if (inf.err || !(inf.result instanceof Uint8Array)) throw new Error('bad zlib data in pack'); e.data = inf.result; o += (inf as unknown as { strm: { next_in: number } }).strm.next_in; if (e.data.length !== size) throw new Error('pack object size mismatch'); ents.push(e); } const byOff = new Map(); const bySha = new Map(); const out: RawObj[] = []; let pending = ents; while (pending.length) { const next: Ent[] = []; for (const e of pending) { let obj: RawObj | null = null; if (e.kind >= 1 && e.kind <= 4) { const t = NUM_TYPE[e.kind]; obj = { type: t, data: e.data, sha: objectId(t, e.data) }; } else { const base = e.kind === 6 ? byOff.get(e.baseOff!) : (bySha.get(e.baseSha!) || null); if (!base) { next.push(e); continue; } const data = applyDelta(base.data, e.data); obj = { type: base.type, data, sha: objectId(base.type, data) }; } byOff.set(e.off, obj); bySha.set(obj.sha, obj); out.push(obj); } if (next.length === pending.length) { // Remaining bases must already be in the repository (thin pack). let progressed = false; for (const e of next) if (e.kind === 7 && !bySha.has(e.baseSha!)) { const b = await getBase(e.baseSha!); if (b) { bySha.set(b.sha, b); progressed = true; } } if (!progressed) throw new Error('pack has a delta whose base is missing'); } pending = next; } return out; } // ---------- pack writing ---------- export function packObjHeader(type: number, size: number): Uint8Array { const bytes: number[] = []; let b = (type << 4) | (size & 15); size = Math.floor(size / 16); while (size > 0) { bytes.push(b | 0x80); b = size & 0x7f; size = Math.floor(size / 128); } bytes.push(b); return new Uint8Array(bytes); } export function packHeader(count: number): Uint8Array { const h = new Uint8Array(12); h.set(te.encode('PACK')); const dv = new DataView(h.buffer); dv.setUint32(4, 2); dv.setUint32(8, count); return h; } export const deflate = (d: Uint8Array) => pako.deflate(d); export const inflate = (d: Uint8Array) => pako.inflate(d);