Branchwell / source / src / git / core.ts
| 1 | // Git building blocks: pkt-lines, object ids, commit/tree parsing, pack reading and writing. |
| 2 | import pako from 'pako'; |
| 3 | import { Sha1, hex } from './sha1'; |
| 4 | |
| 5 | export const te = new TextEncoder(); |
| 6 | export const td = new TextDecoder(); |
| 7 | export const ZERO = '0'.repeat(40); |
| 8 | export type ObjType = 'commit' | 'tree' | 'blob' | 'tag'; |
| 9 | export const TYPE_NUM: Record<ObjType, number> = { commit: 1, tree: 2, blob: 3, tag: 4 }; |
| 10 | export const NUM_TYPE: Record<number, ObjType> = { 1: 'commit', 2: 'tree', 3: 'blob', 4: 'tag' }; |
| 11 | |
| 12 | // ---------- pkt-line ---------- |
| 13 | export function pkt(s: string | Uint8Array): Uint8Array { |
| 14 | const body = typeof s === 'string' ? te.encode(s) : s; |
| 15 | const out = new Uint8Array(body.length + 4); |
| 16 | out.set(te.encode((body.length + 4).toString(16).padStart(4, '0')), 0); |
| 17 | out.set(body, 4); |
| 18 | return out; |
| 19 | } |
| 20 | export const FLUSH = te.encode('0000'); |
| 21 | |
| 22 | export function concat(parts: Uint8Array[]): Uint8Array { |
| 23 | let n = 0; for (const p of parts) n += p.length; |
| 24 | const out = new Uint8Array(n); let o = 0; |
| 25 | for (const p of parts) { out.set(p, o); o += p.length; } |
| 26 | return out; |
| 27 | } |
| 28 | |
| 29 | /** Reads pkt-lines from a buffer. Returns lines (null = flush) and the offset after the last one read. */ |
| 30 | export function readPkts(buf: Uint8Array, start = 0, stopAtFlush = false): { lines: (Uint8Array | null)[]; end: number } { |
| 31 | const lines: (Uint8Array | null)[] = []; |
| 32 | let o = start; |
| 33 | while (o + 4 <= buf.length) { |
| 34 | const len = parseInt(td.decode(buf.subarray(o, o + 4)), 16); |
| 35 | if (Number.isNaN(len)) break; |
| 36 | if (len === 0) { lines.push(null); o += 4; if (stopAtFlush) break; continue; } |
| 37 | if (len < 4 || o + len > buf.length) break; |
| 38 | lines.push(buf.subarray(o + 4, o + len)); |
| 39 | o += len; |
| 40 | } |
| 41 | return { lines, end: o }; |
| 42 | } |
| 43 | |
| 44 | /** Side-band-64k framing: band 1 = data, 2 = progress, 3 = error. */ |
| 45 | export function* sideband(band: number, data: Uint8Array): Generator<Uint8Array> { |
| 46 | for (let i = 0; i < data.length; i += 65515) { |
| 47 | const chunk = data.subarray(i, Math.min(i + 65515, data.length)); |
| 48 | const b = new Uint8Array(chunk.length + 1); b[0] = band; b.set(chunk, 1); |
| 49 | yield pkt(b); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // ---------- objects ---------- |
| 54 | export function objectId(type: ObjType, data: Uint8Array): string { |
| 55 | return hex(new Sha1().update(te.encode(`${type} ${data.length}\0`)).update(data).digest()); |
| 56 | } |
| 57 | |
| 58 | export interface TreeEntry { mode: string; name: string; sha: string } |
| 59 | export function parseTree(data: Uint8Array): TreeEntry[] { |
| 60 | const out: TreeEntry[] = []; |
| 61 | let o = 0; |
| 62 | while (o < data.length) { |
| 63 | const sp = data.indexOf(0x20, o); |
| 64 | const nul = data.indexOf(0, sp); |
| 65 | 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)) }); |
| 66 | o = nul + 21; |
| 67 | } |
| 68 | return out; |
| 69 | } |
| 70 | export function writeTree(entries: TreeEntry[]): Uint8Array { |
| 71 | // Git sorts tree entries by name, with directories compared as if they end in '/'. |
| 72 | const key = (e: TreeEntry) => e.mode === '40000' ? e.name + '/' : e.name; |
| 73 | const sorted = [...entries].sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0)); |
| 74 | const parts: Uint8Array[] = []; |
| 75 | for (const e of sorted) { |
| 76 | parts.push(te.encode(`${e.mode} ${e.name}\0`)); |
| 77 | const s = new Uint8Array(20); for (let i = 0; i < 20; i++) s[i] = parseInt(e.sha.substr(i * 2, 2), 16); |
| 78 | parts.push(s); |
| 79 | } |
| 80 | return concat(parts); |
| 81 | } |
| 82 | |
| 83 | export interface Commit { tree: string; parents: string[]; author: string; committer: string; message: string; time: number } |
| 84 | export function parseCommit(data: Uint8Array): Commit { |
| 85 | const text = td.decode(data); |
| 86 | const split = text.indexOf('\n\n'); |
| 87 | const head = text.slice(0, split < 0 ? text.length : split); |
| 88 | const c: Commit = { tree: '', parents: [], author: '', committer: '', message: split < 0 ? '' : text.slice(split + 2), time: 0 }; |
| 89 | for (const line of head.split('\n')) { |
| 90 | const sp = line.indexOf(' '); |
| 91 | const k = line.slice(0, sp), v = line.slice(sp + 1); |
| 92 | if (k === 'tree') c.tree = v; |
| 93 | else if (k === 'parent') c.parents.push(v); |
| 94 | else if (k === 'author') c.author = v; |
| 95 | else if (k === 'committer') { c.committer = v; const m = v.match(/ (\d+) [+-]\d{4}$/); if (m) c.time = +m[1]; } |
| 96 | } |
| 97 | return c; |
| 98 | } |
| 99 | /** "Name <email> 1700000000 +0000" -> name */ |
| 100 | export const personName = (s: string) => s.replace(/\s*<.*$/, '').trim(); |
| 101 | |
| 102 | // ---------- deltas ---------- |
| 103 | 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; } |
| 104 | export function applyDelta(base: Uint8Array, delta: Uint8Array): Uint8Array { |
| 105 | const o = { i: 0 }; |
| 106 | const baseLen = readVar(delta, o); |
| 107 | if (baseLen !== base.length) throw new Error('delta base size mismatch'); |
| 108 | const outLen = readVar(delta, o); |
| 109 | const out = new Uint8Array(outLen); let w = 0; |
| 110 | while (o.i < delta.length) { |
| 111 | const op = delta[o.i++]; |
| 112 | if (op & 0x80) { |
| 113 | let off = 0, size = 0; |
| 114 | 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; |
| 115 | if (op & 16) size |= delta[o.i++]; if (op & 32) size |= delta[o.i++] << 8; if (op & 64) size |= delta[o.i++] << 16; |
| 116 | if (size === 0) size = 0x10000; |
| 117 | out.set(base.subarray(off >>> 0, (off >>> 0) + size), w); w += size; |
| 118 | } else if (op) { out.set(delta.subarray(o.i, o.i + op), w); w += op; o.i += op; } |
| 119 | else throw new Error('bad delta op'); |
| 120 | } |
| 121 | if (w !== outLen) throw new Error('delta result size mismatch'); |
| 122 | return out; |
| 123 | } |
| 124 | |
| 125 | // ---------- pack reading ---------- |
| 126 | export interface RawObj { type: ObjType; data: Uint8Array; sha: string } |
| 127 | /** Parses a v2 pack. getBase looks up ref-delta bases that are already stored (thin packs). */ |
| 128 | export async function readPack(buf: Uint8Array, getBase: (sha: string) => Promise<RawObj | null>): Promise<RawObj[]> { |
| 129 | if (buf.length < 32 || td.decode(buf.subarray(0, 4)) !== 'PACK') throw new Error('not a pack'); |
| 130 | const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); |
| 131 | const count = dv.getUint32(8); |
| 132 | const want = hex(buf.subarray(buf.length - 20)); |
| 133 | const got = hex(new Sha1().update(buf.subarray(0, buf.length - 20)).digest()); |
| 134 | if (want !== got) throw new Error('pack checksum mismatch'); |
| 135 | let o = 12; |
| 136 | type Ent = { off: number; kind: number; data: Uint8Array; baseOff?: number; baseSha?: string }; |
| 137 | const ents: Ent[] = []; |
| 138 | for (let n = 0; n < count; n++) { |
| 139 | const off = o; |
| 140 | let b = buf[o++]; const kind = (b >> 4) & 7; let size = b & 15, shift = 4; |
| 141 | while (b & 0x80) { b = buf[o++]; size += (b & 0x7f) * 2 ** shift; shift += 7; } |
| 142 | const e: Ent = { off, kind, data: new Uint8Array() }; |
| 143 | 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; } |
| 144 | else if (kind === 7) { e.baseSha = hex(buf.subarray(o, o + 20)); o += 20; } |
| 145 | const inf = new pako.Inflate(); |
| 146 | inf.push(buf.subarray(o), true); |
| 147 | if (inf.err || !(inf.result instanceof Uint8Array)) throw new Error('bad zlib data in pack'); |
| 148 | e.data = inf.result; o += (inf as unknown as { strm: { next_in: number } }).strm.next_in; |
| 149 | if (e.data.length !== size) throw new Error('pack object size mismatch'); |
| 150 | ents.push(e); |
| 151 | } |
| 152 | const byOff = new Map<number, RawObj>(); |
| 153 | const bySha = new Map<string, RawObj>(); |
| 154 | const out: RawObj[] = []; |
| 155 | let pending = ents; |
| 156 | while (pending.length) { |
| 157 | const next: Ent[] = []; |
| 158 | for (const e of pending) { |
| 159 | let obj: RawObj | null = null; |
| 160 | if (e.kind >= 1 && e.kind <= 4) { const t = NUM_TYPE[e.kind]; obj = { type: t, data: e.data, sha: objectId(t, e.data) }; } |
| 161 | else { |
| 162 | const base = e.kind === 6 ? byOff.get(e.baseOff!) : (bySha.get(e.baseSha!) || null); |
| 163 | if (!base) { next.push(e); continue; } |
| 164 | const data = applyDelta(base.data, e.data); |
| 165 | obj = { type: base.type, data, sha: objectId(base.type, data) }; |
| 166 | } |
| 167 | byOff.set(e.off, obj); bySha.set(obj.sha, obj); out.push(obj); |
| 168 | } |
| 169 | if (next.length === pending.length) { |
| 170 | // Remaining bases must already be in the repository (thin pack). |
| 171 | let progressed = false; |
| 172 | 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; } } |
| 173 | if (!progressed) throw new Error('pack has a delta whose base is missing'); |
| 174 | } |
| 175 | pending = next; |
| 176 | } |
| 177 | return out; |
| 178 | } |
| 179 | |
| 180 | // ---------- pack writing ---------- |
| 181 | export function packObjHeader(type: number, size: number): Uint8Array { |
| 182 | const bytes: number[] = []; |
| 183 | let b = (type << 4) | (size & 15); size = Math.floor(size / 16); |
| 184 | while (size > 0) { bytes.push(b | 0x80); b = size & 0x7f; size = Math.floor(size / 128); } |
| 185 | bytes.push(b); |
| 186 | return new Uint8Array(bytes); |
| 187 | } |
| 188 | export function packHeader(count: number): Uint8Array { |
| 189 | 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; |
| 190 | } |
| 191 | export const deflate = (d: Uint8Array) => pako.deflate(d); |
| 192 | export const inflate = (d: Uint8Array) => pako.inflate(d); |