Repository navigation
Expand file tree
/
Copy pathgit.ts
More file actions
872 lines (829 loc) · 33.8 KB
/
Copy pathgit.ts
File metadata and controls
872 lines (829 loc) · 33.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
// git.ts — the git smart-HTTP protocol, implemented on the standard library:
// pkt-line framing, packfile reading and writing (full objects only, no deltas
// on the wire out; REF_DELTA and OFS_DELTA are resolved on the way in), the
// v0 and v2 upload-pack advertisements, ls-refs, fetch (including shallow and
// deepen) and receive-pack with per-ref report-status.
//
// The wire is exactly what the suite's git client speaks (kit program/env/src/
// git-client.ts): v2 is chosen by the `Git-Protocol: version=2` request header,
// v0 otherwise; receive-pack is v0 only.
import { deflateSync, inflateSync } from 'node:zlib';
import { createHash } from 'node:crypto';
import {
ZERO_OID,
parseCommit,
parseTag,
parseTree,
hashObject,
type GitObject,
type ObjType,
type Repo,
type Store,
} from './store.ts';
// -------------------------------------------------------------------------------------------
// pkt-line
// -------------------------------------------------------------------------------------------
export function pktLine(payload: string | Buffer): Buffer {
const body = typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload;
const head = Buffer.from((body.length + 4).toString(16).padStart(4, '0'), 'ascii');
return Buffer.concat([head, body]);
}
export function pktFlush(): Buffer {
return Buffer.from('0000', 'ascii');
}
export function pktDelim(): Buffer {
return Buffer.from('0001', 'ascii');
}
export interface Pkt {
kind: 'data' | 'flush' | 'delim' | 'end';
payload?: Buffer;
}
const HEX4 = /^[0-9a-fA-F]{4}$/;
/** Decode a whole buffer of pkt-lines; throws on malformed framing. */
export function decodePktLines(buf: Buffer): Pkt[] {
const out: Pkt[] = [];
let offset = 0;
while (offset < buf.length) {
if (offset + 4 > buf.length) throw new Error('truncated pkt-line');
const head = buf.subarray(offset, offset + 4).toString('ascii');
if (!HEX4.test(head)) throw new Error(`invalid pkt-line length ${JSON.stringify(head)}`);
const length = Number.parseInt(head, 16);
if (length === 0) {
out.push({ kind: 'flush' });
offset += 4;
} else if (length === 1) {
out.push({ kind: 'delim' });
offset += 4;
} else if (length === 2) {
out.push({ kind: 'end' });
offset += 4;
} else if (length === 3 || length > 65520) {
throw new Error(`invalid pkt-line length ${length}`);
} else {
if (offset + length > buf.length) throw new Error('truncated pkt-line');
out.push({ kind: 'data', payload: buf.subarray(offset + 4, offset + length) });
offset += length;
}
}
return out;
}
/** Split decoded packets into their text lines (without the trailing newline). */
export function pktLines(buf: Buffer): string[] {
const lines: string[] = [];
for (const packet of decodePktLines(buf)) {
if (packet.kind === 'data' && packet.payload !== undefined) {
lines.push(packet.payload.toString('utf8').replace(/\n$/, ''));
}
}
return lines;
}
// -------------------------------------------------------------------------------------------
// packfiles
// -------------------------------------------------------------------------------------------
const TYPE_CODE: Record<ObjType, number> = { commit: 1, tree: 2, blob: 3, tag: 4 };
const CODE_TYPE: Record<number, ObjType> = { 1: 'commit', 2: 'tree', 3: 'blob', 4: 'tag' };
const compressedCache = new WeakMap<object, Buffer>();
function writePackObjectHeader(type: ObjType, size: number): Buffer {
const code = TYPE_CODE[type];
const bytes: number[] = [];
let remaining = size;
let first = (code << 4) | (remaining & 0x0f);
remaining = Math.floor(remaining / 16);
while (remaining > 0) {
bytes.push(first | 0x80);
first = remaining & 0x7f;
remaining = Math.floor(remaining / 128);
}
bytes.push(first);
return Buffer.from(bytes);
}
/** Build a packfile from plain objects (no deltas), with the SHA-1 trailer. */
export function writePack(objects: Iterable<GitObject>): Buffer {
const list = [...objects];
const parts: Buffer[] = [];
const header = Buffer.allocUnsafe(12);
header.write('PACK', 0, 4, 'ascii');
header.writeUInt32BE(2, 4);
header.writeUInt32BE(list.length, 8);
parts.push(header);
for (const object of list) {
parts.push(writePackObjectHeader(object.type, object.data.length));
// Git objects are immutable once stored. Reuse the deterministic zlib
// stream across concurrent clones; this avoids repeating compression for
// the same object while preserving identical pack bytes.
let compressed = compressedCache.get(object.data);
if (compressed === undefined) {
compressed = deflateSync(object.data);
compressedCache.set(object.data, compressed);
}
parts.push(compressed);
}
let length = 0;
for (const part of parts) length += part.length;
const pack = Buffer.allocUnsafe(length + 20);
let offset = 0;
for (const part of parts) { part.copy(pack, offset); offset += part.length; }
createHash('sha1').update(pack.subarray(0, length)).digest().copy(pack, length);
return pack;
}
/** Inflate one zlib stream starting at `offset`; returns the bytes and the next offset. */
function inflateAt(buffer: Buffer, offset: number): { data: Buffer; next: number } {
const result = inflateSync(buffer.subarray(offset), { info: true }) as unknown as {
buffer: Buffer;
engine: { bytesWritten: number };
};
const written = result.engine.bytesWritten;
if (!written || written <= 0) throw new Error(`zlib stream at offset ${offset} consumed no bytes`);
return { data: result.buffer, next: offset + written };
}
function readVarint(buffer: Buffer, offset: number): { value: number; next: number } {
let value = 0;
let shift = 0;
let at = offset;
for (;;) {
if (at >= buffer.length) throw new Error('varint is truncated');
const byte = buffer[at++] as number;
value += (byte & 0x7f) * 2 ** shift;
shift += 7;
if (!(byte & 0x80)) break;
if (shift > 63) throw new Error('varint is too long');
}
return { value, next: at };
}
/** Apply a git delta instruction stream to a base object's bytes. */
export function applyDelta(base: Buffer, delta: Buffer): Buffer {
let offset = 0;
const readSize = (): number => {
const { value, next } = readVarint(delta, offset);
offset = next;
return value;
};
const sourceSize = readSize();
const targetSize = readSize();
if (sourceSize !== base.length) throw new Error(`delta expects a ${sourceSize}-byte base, got ${base.length}`);
const out = Buffer.allocUnsafe(targetSize);
let written = 0;
while (offset < delta.length) {
const op = delta[offset++] as number;
if (op & 0x80) {
let copyOffset = 0;
let copySize = 0;
let shift = 0;
for (let bit = 0; bit < 4; bit += 1) {
if (op & (1 << bit)) {
if (offset >= delta.length) throw new Error('delta copy offset is truncated');
copyOffset += (delta[offset++] as number) * 2 ** shift;
}
shift += 8;
}
shift = 0;
for (let bit = 4; bit < 7; bit += 1) {
if (op & (1 << bit)) {
if (offset >= delta.length) throw new Error('delta copy size is truncated');
copySize += (delta[offset++] as number) * 2 ** shift;
}
shift += 8;
}
if (copySize === 0) copySize = 0x10000;
if (copyOffset + copySize > base.length) throw new Error('delta copy is out of the base');
if (written + copySize > targetSize) throw new Error('delta writes past its target size');
base.copy(out, written, copyOffset, copyOffset + copySize);
written += copySize;
} else if (op !== 0) {
const literal = op & 0x7f;
if (offset + literal > delta.length) throw new Error('delta insert is truncated');
if (written + literal > targetSize) throw new Error('delta writes past its target size');
delta.copy(out, written, offset, offset + literal);
offset += literal;
written += literal;
} else {
throw new Error('delta opcode 0 is invalid');
}
}
if (written !== targetSize) throw new Error(`delta produced ${written} of ${targetSize} bytes`);
return out;
}
interface PackEntry {
type: ObjType | 'ref-delta' | 'ofs-delta';
data: Buffer;
baseOid?: string;
baseOffset?: number;
offset: number;
}
/**
* Read a packfile into objects, resolving REF_DELTA and OFS_DELTA entries
* against the pack itself and, when given, the repository's store.
*/
export function readPack(pack: Buffer, lookup?: (oid: string) => GitObject | undefined): GitObject[] {
if (pack.length < 32) throw new Error('pack is too short');
if (pack.subarray(0, 4).toString('ascii') !== 'PACK') throw new Error('pack has no PACK header');
const count = pack.readUInt32BE(8);
const trailer = pack.subarray(pack.length - 20).toString('hex');
const expected = createHash('sha1').update(pack.subarray(0, pack.length - 20)).digest('hex');
if (trailer !== expected) throw new Error('pack trailer checksum mismatch');
const entries: PackEntry[] = [];
const byOffset = new Map<number, PackEntry>();
let offset = 12;
for (let index = 0; index < count; index += 1) {
const entryOffset = offset;
if (offset >= pack.length) throw new Error('pack is truncated');
let byte = pack[offset++] as number;
const typeCode = (byte >> 4) & 0x07;
let size = byte & 0x0f;
let shift = 4;
while (byte & 0x80) {
if (offset >= pack.length) throw new Error('pack size varint is truncated');
byte = pack[offset++] as number;
size += (byte & 0x7f) * 2 ** shift;
shift += 7;
}
let entry: PackEntry;
if (typeCode >= 1 && typeCode <= 4) {
const inflated = inflateAt(pack, offset);
offset = inflated.next;
if (inflated.data.length !== size) throw new Error('pack object size mismatch');
entry = { type: CODE_TYPE[typeCode] as ObjType, data: inflated.data, offset: entryOffset };
} else if (typeCode === 6) {
const baseOid = pack.subarray(offset, offset + 20).toString('hex');
offset += 20;
const inflated = inflateAt(pack, offset);
offset = inflated.next;
if (inflated.data.length !== size) throw new Error('pack object size mismatch');
entry = { type: 'ref-delta', data: inflated.data, baseOid, offset: entryOffset };
} else if (typeCode === 7) {
let b = pack[offset++] as number;
let value = b & 0x7f;
while (b & 0x80) {
if (offset >= pack.length) throw new Error('ofs-delta base offset is truncated');
b = pack[offset++] as number;
value = (value + 1) * 128 + (b & 0x7f);
}
const baseOffset = entryOffset - value;
const inflated = inflateAt(pack, offset);
offset = inflated.next;
if (inflated.data.length !== size) throw new Error('pack object size mismatch');
entry = { type: 'ofs-delta', data: inflated.data, baseOffset, offset: entryOffset };
} else {
throw new Error(`unknown pack object type ${typeCode}`);
}
entries.push(entry);
byOffset.set(entryOffset, entry);
}
// Resolve plain entries first (their oids are known at once), then deltas:
// a delta's base is either in the store, a plain entry of this pack, or a
// delta entry resolved in an earlier pass. Packs the suite sends carry plain
// objects only; this is belt and braces.
const resolved = new Map<number, GitObject>();
const byOid = new Map<string, GitObject>();
for (const entry of entries) {
if (entry.type === 'ref-delta' || entry.type === 'ofs-delta') continue;
const object: GitObject = { type: entry.type as ObjType, data: entry.data };
resolved.set(entry.offset, object);
byOid.set(hashObject(object.type, object.data), object);
}
let remaining = entries.filter((entry) => entry.type === 'ref-delta' || entry.type === 'ofs-delta');
for (let pass = 0; pass < remaining.length + 1 && remaining.length > 0; pass += 1) {
const next: PackEntry[] = [];
for (const entry of remaining) {
let base: GitObject | undefined;
if (entry.type === 'ref-delta' && entry.baseOid !== undefined) {
base = byOid.get(entry.baseOid) ?? lookup?.(entry.baseOid);
} else if (entry.type === 'ofs-delta' && entry.baseOffset !== undefined) {
base = resolved.get(entry.baseOffset);
}
if (base === undefined) {
next.push(entry);
continue;
}
const object: GitObject = { type: base.type, data: applyDelta(base.data, entry.data) };
resolved.set(entry.offset, object);
byOid.set(hashObject(object.type, object.data), object);
}
if (next.length === remaining.length) throw new Error('delta base is missing');
remaining = next;
}
const out: GitObject[] = [];
for (const entry of entries) {
const object = resolved.get(entry.offset);
if (object === undefined) throw new Error('pack entry did not resolve');
out.push(object);
}
return out;
}
// -------------------------------------------------------------------------------------------
// Advertisements
// -------------------------------------------------------------------------------------------
const AGENT = 'anvil/1.0.0';
function sortedRefs(repo: Repo): Array<{ name: string; oid: string }> {
const out: Array<{ name: string; oid: string }> = [];
for (const name of [...repo.refs.keys()].sort()) {
out.push({ name, oid: repo.refs.get(name) as string });
}
return out;
}
function peeledOid(repo: Repo, oid: string): string | null {
const object = repo.objects.get(oid);
if (object === undefined || object.type !== 'tag') return null;
return parseTag(object.data).object;
}
/** The v0 advertisement body for a service, with the `# service=` preamble. */
export function advertisementV0(repo: Repo, service: 'git-upload-pack' | 'git-receive-pack'): Buffer {
const caps =
service === 'git-upload-pack'
? `multi_ack_detailed no-done side-band-64k thin-pack ofs-delta shallow agent=${AGENT} object-format=sha1 symref=HEAD:refs/heads/${repo.defaultBranch}`
: `report-status side-band-64k delete-refs ofs-delta agent=${AGENT} object-format=sha1`;
const parts: Buffer[] = [pktLine(`# service=${service}\n`), pktFlush()];
const refs = sortedRefs(repo);
const headTip = repo.refs.get(`refs/heads/${repo.defaultBranch}`);
if (refs.length === 0) {
parts.push(pktLine(`${ZERO_OID} capabilities^{}\0${caps}\n`));
} else {
const headOid = headTip ?? ZERO_OID;
parts.push(pktLine(`${headOid} HEAD\0${caps}\n`));
for (const ref of refs) {
parts.push(pktLine(`${ref.oid} ${ref.name}\n`));
const peeled = peeledOid(repo, ref.oid);
if (peeled !== null) parts.push(pktLine(`${peeled} ${ref.name}^{}\n`));
}
}
parts.push(pktFlush());
return Buffer.concat(parts);
}
/** The v2 capability advertisement body (no service preamble). */
export function advertisementV2(): Buffer {
const lines = [
'version 2\n',
'ls-refs=unborn\n',
'fetch=shallow wait-for-done\n',
'object-format=sha1\n',
`agent=${AGENT}\n`,
];
return Buffer.concat([...lines.map((line) => pktLine(line)), pktFlush()]);
}
// -------------------------------------------------------------------------------------------
// Fetch planning
// -------------------------------------------------------------------------------------------
interface FetchPlan {
toSend: GitObject[];
shallow: string[];
unshallow: string[];
}
/**
* Work out which objects a fetch must send. `wants` are commit or tag oids;
* `haves` are commits the client holds; `shallow` are the client's shallow
* boundaries (their parents are missing on the client); `depth` caps the
* generations walked from the wants.
*/
export function planFetch(
store: Store,
repo: Repo,
wants: readonly string[],
haves: readonly string[],
shallow: readonly string[],
depth: number | null,
): FetchPlan {
// The commits the walk starts from (tags peeled).
const wantCommits: string[] = [];
const wantTags: GitObject[] = [];
for (const want of wants) {
const object = repo.objects.get(want);
if (object === undefined) continue;
if (object.type === 'tag') {
wantTags.push(object);
const peeled = store.peelToCommit(repo, want);
if (peeled !== null) wantCommits.push(peeled);
} else if (object.type === 'commit') {
wantCommits.push(want);
}
}
// What the client already holds, as commits: the haves' closure, minus the
// ancestors of its shallow boundaries (those parents are exactly what a
// deepen has to deliver).
const held = store.reachableCommits(repo, haves);
for (const boundary of shallow) {
const object = repo.objects.get(boundary);
if (object === undefined || object.type !== 'commit') continue;
for (const parent of parseCommit(object.data).parents) {
for (const oid of store.reachableCommits(repo, [parent])) held.delete(oid);
}
}
const shallowSet = new Set(shallow);
// Breadth-first walk from the wants, tracking generations.
const included = new Set<string>();
const visited = new Set<string>();
const queue: Array<[string, number]> = wantCommits.map((oid) => [oid, 0] as [string, number]);
let queueAt = 0;
const seenGen = new Map<string, number>();
for (const [oid, gen] of queue) seenGen.set(oid, gen);
while (queueAt < queue.length) {
const [oid, gen] = queue[queueAt++] as [string, number];
if (visited.has(oid)) continue;
visited.add(oid);
const isHeld = held.has(oid);
const isBoundary = shallowSet.has(oid);
if (!isHeld && (depth === null || gen < depth)) included.add(oid);
// Walk through a commit when it is included, or when it is a shallow
// boundary the client holds (its parents are missing over there).
if (!included.has(oid) && !isBoundary) continue;
if (depth !== null && gen + 1 >= depth && included.has(oid)) {
// At the depth edge: the parents are cut off, no need to walk further.
continue;
}
const object = repo.objects.get(oid);
if (object === undefined || object.type !== 'commit') continue;
for (const parent of parseCommit(object.data).parents) {
const nextGen = gen + 1;
if (depth !== null && nextGen > depth) continue;
if (!seenGen.has(parent) || (seenGen.get(parent) as number) > nextGen) {
// Reached nearer than before: walk it again at the nearer generation.
seenGen.set(parent, nextGen);
visited.delete(parent);
queue.push([parent, nextGen]);
}
}
}
// The new shallow boundary: included commits with a parent neither included
// nor held. A root commit (no parents) is never a boundary.
const boundary: string[] = [];
for (const oid of included) {
const object = repo.objects.get(oid);
if (object === undefined || object.type !== 'commit') continue;
const parents = parseCommit(object.data).parents;
if (parents.length === 0) continue;
if (parents.some((parent) => !included.has(parent) && !held.has(parent))) boundary.push(oid);
}
// Unshallow: a previous boundary whose parents are all included or held now.
const unshallow: string[] = [];
const stillShallow: string[] = [];
for (const old of shallow) {
if (!visited.has(old)) continue;
if (boundary.includes(old)) continue;
const object = repo.objects.get(old);
if (object === undefined || object.type !== 'commit') continue;
const parents = parseCommit(object.data).parents;
if (parents.every((parent) => included.has(parent) || held.has(parent))) unshallow.push(old);
else stillShallow.push(old);
}
const shallowOut = [...new Set([...boundary, ...stillShallow])];
// Objects to send: the tree closures of the included commits (plus wanted
// tags), minus the closures of what the client holds.
const send = new Map<string, GitObject>();
const collectClosure = (commitOid: string): void => {
const object = repo.objects.get(commitOid);
if (object === undefined || object.type !== 'commit') return;
const commit = parseCommit(object.data);
send.set(commitOid, object);
const walkTree = (treeOid: string): void => {
const tree = repo.objects.get(treeOid);
if (tree === undefined) return;
send.set(treeOid, tree);
for (const entry of parseTree(tree.data)) {
const child = repo.objects.get(entry.oid);
if (child === undefined) continue;
if (entry.mode === '40000') walkTree(entry.oid);
else send.set(entry.oid, child);
}
};
walkTree(commit.tree);
};
for (const oid of included) collectClosure(oid);
for (const tag of wantTags) send.set(hashObject(tag.type, tag.data), tag);
const heldObjects = new Set<string>();
for (const oid of held) {
const object = repo.objects.get(oid);
if (object === undefined || object.type !== 'commit') continue;
heldObjects.add(oid);
const walkTree = (treeOid: string): void => {
const tree = repo.objects.get(treeOid);
if (tree === undefined) return;
heldObjects.add(treeOid);
for (const entry of parseTree(tree.data)) {
const child = repo.objects.get(entry.oid);
if (child === undefined) continue;
if (entry.mode === '40000') walkTree(entry.oid);
else heldObjects.add(entry.oid);
}
};
walkTree(parseCommit(object.data).tree);
}
for (const oid of heldObjects) send.delete(oid);
return { toSend: [...send.values()], shallow: shallowOut, unshallow };
}
/** Split pack bytes into sideband pkt-lines (band 1 = data). */
export function sidebandPack(pack: Buffer): Buffer {
const CHUNK = 32768;
const out = Buffer.allocUnsafe(pack.length + Math.ceil(pack.length / CHUNK) * 5);
let at = 0;
for (let offset = 0; offset < pack.length; offset += CHUNK) {
const size = Math.min(CHUNK, pack.length - offset);
out.write((size + 5).toString(16).padStart(4, '0'), at, 4, 'ascii');
out[at + 4] = 1;
pack.copy(out, at + 5, offset, offset + size);
at += size + 5;
}
return out;
}
// -------------------------------------------------------------------------------------------
// ls-refs (v2)
// -------------------------------------------------------------------------------------------
export function handleLsRefs(repo: Repo, args: readonly string[]): Buffer {
const peel = args.includes('peel');
const symrefs = args.includes('symrefs');
const prefixes = args.filter((arg) => arg.startsWith('ref-prefix ')).map((arg) => arg.slice('ref-prefix '.length));
const keep = (name: string): boolean => prefixes.length === 0 || prefixes.some((prefix) => name.startsWith(prefix));
const parts: Buffer[] = [];
const headTip = repo.refs.get(`refs/heads/${repo.defaultBranch}`);
if (keep('HEAD')) {
if (headTip === undefined) {
parts.push(pktLine(`unborn HEAD symref-target:refs/heads/${repo.defaultBranch}\n`));
} else if (symrefs) {
parts.push(pktLine(`${headTip} HEAD symref-target:refs/heads/${repo.defaultBranch}\n`));
} else {
parts.push(pktLine(`${headTip} HEAD\n`));
}
}
for (const ref of sortedRefs(repo)) {
if (!keep(ref.name)) continue;
let line = `${ref.oid} ${ref.name}`;
if (peel) {
const peeled = peeledOid(repo, ref.oid);
if (peeled !== null) line += ` peeled:${peeled}`;
}
parts.push(pktLine(`${line}\n`));
}
parts.push(pktFlush());
return Buffer.concat(parts);
}
// -------------------------------------------------------------------------------------------
// fetch (v2 and v0)
// -------------------------------------------------------------------------------------------
// Retain just the most recent pack per repository. The ordered immutable
// object identities are the cache key, so ref changes and new plans are safe.
const fetchPackCache = new WeakMap<Repo, { objects: GitObject[]; pack: Buffer }>();
function fetchPack(repo: Repo, objects: GitObject[]): Buffer {
const cached = fetchPackCache.get(repo);
if (cached !== undefined && cached.objects.length === objects.length &&
objects.every((object, index) => object === cached.objects[index])) return cached.pack;
const pack = sidebandPack(writePack(objects));
fetchPackCache.set(repo, { objects, pack });
return pack;
}
export function handleFetchV2(store: Store, repo: Repo, args: readonly string[]): Buffer {
const wants: string[] = [];
const haves: string[] = [];
const shallow: string[] = [];
let depth: number | null = null;
let done = false;
for (const arg of args) {
if (arg.startsWith('want ')) wants.push(arg.slice(5).trim());
else if (arg.startsWith('have ')) haves.push(arg.slice(5).trim());
else if (arg.startsWith('shallow ')) shallow.push(arg.slice(8).trim());
else if (arg.startsWith('deepen ')) {
const n = Number.parseInt(arg.slice(7).trim(), 10);
if (Number.isSafeInteger(n) && n > 0) depth = n;
} else if (arg === 'done') done = true;
}
const plan = planFetch(store, repo, wants, haves, shallow, depth);
const pack = fetchPack(repo, plan.toSend);
const parts: Buffer[] = [];
parts.push(pktLine('acknowledgments\n'));
parts.push(pktLine('NAK\n'));
if (done) parts.push(pktLine('ready\n'));
parts.push(pktDelim());
if (plan.shallow.length > 0 || plan.unshallow.length > 0) {
parts.push(pktLine('shallow-info\n'));
for (const oid of plan.shallow) parts.push(pktLine(`shallow ${oid}\n`));
for (const oid of plan.unshallow) parts.push(pktLine(`unshallow ${oid}\n`));
parts.push(pktDelim());
}
parts.push(pktLine('packfile\n'));
parts.push(pack);
parts.push(pktFlush());
return Buffer.concat(parts);
}
export function handleFetchV0(store: Store, repo: Repo, args: readonly string[]): Buffer {
const wants: string[] = [];
const haves: string[] = [];
const shallow: string[] = [];
let depth: number | null = null;
for (const arg of args) {
// The first want line carries the capability list after a NUL; drop it.
const bare = arg.includes('\0') ? arg.slice(0, arg.indexOf('\0')) : arg;
if (bare.startsWith('want ')) wants.push(bare.slice(5).trim());
else if (bare.startsWith('have ')) haves.push(bare.slice(5).trim());
else if (bare.startsWith('shallow ')) shallow.push(bare.slice(8).trim());
else if (bare.startsWith('deepen ')) {
const n = Number.parseInt(bare.slice(7).trim(), 10);
if (Number.isSafeInteger(n) && n > 0) depth = n;
}
}
const plan = planFetch(store, repo, wants, haves, shallow, depth);
const pack = fetchPack(repo, plan.toSend);
const parts: Buffer[] = [];
parts.push(pktLine('NAK\n'));
for (const oid of plan.shallow) parts.push(pktLine(`shallow ${oid}\n`));
for (const oid of plan.unshallow) parts.push(pktLine(`unshallow ${oid}\n`));
parts.push(pack);
parts.push(pktFlush());
return Buffer.concat(parts);
}
// -------------------------------------------------------------------------------------------
// receive-pack (v0)
// -------------------------------------------------------------------------------------------
export interface PushCommand {
oldOid: string;
newOid: string;
ref: string;
}
export interface PushReportLine {
ref: string;
ok: boolean;
reason: string;
}
/**
* Apply a receive-pack: store the pack's objects, then apply each command.
* Returns the unpack status and one report line per command, in order.
*/
export function handleReceivePack(
store: Store,
repo: Repo,
body: Buffer,
): { unpackOk: boolean; unpackDetail: string; refs: PushReportLine[] } {
let commands: PushCommand[] = [];
let packOffset = 0;
try {
// Walk the raw buffer: commands are pkt-lines up to the first flush,
// then the pack follows unframed. (Do not pkt-decode the whole body: the
// pack bytes are binary and are not pkt-lines.)
let at = 0;
for (;;) {
if (at + 4 > body.length) throw new Error('truncated pkt-line');
const head = body.subarray(at, at + 4).toString('ascii');
if (!HEX4.test(head)) throw new Error('invalid pkt-line length');
const length = Number.parseInt(head, 16);
if (length === 0) {
at += 4;
break;
}
if (length === 1 || length === 2 || length === 3 || length > 65520) throw new Error('bad pkt-line in command list');
const payload = body.subarray(at + 4, at + length).toString('utf8').replace(/\n$/, '');
const nul = payload.indexOf('\0');
const line = nul >= 0 ? payload.slice(0, nul) : payload;
const parts = line.split(' ');
if (parts.length !== 3) throw new Error('bad push command line');
commands.push({ oldOid: parts[0] as string, newOid: parts[1] as string, ref: parts[2] as string });
at += length;
}
packOffset = at;
} catch {
return { unpackOk: false, unpackDetail: 'error', refs: [] };
}
// The pack: everything after the command flush. A delete-only push sends none.
const hasUpdates = commands.some((command) => command.newOid !== ZERO_OID);
let unpackOk = true;
let unpackDetail = 'ok';
if (hasUpdates) {
const packBytes = body.subarray(packOffset);
if (packBytes.length === 0) {
unpackOk = false;
unpackDetail = 'error';
} else {
try {
const objects = readPack(packBytes, (oid) => repo.objects.get(oid));
for (const object of objects) store.putObjectIfAbsent(repo, object);
} catch {
unpackOk = false;
unpackDetail = 'error';
}
}
}
const refs: PushReportLine[] = [];
if (!unpackOk) {
// Nothing applies when the unpack failed.
for (const command of commands) refs.push({ ref: command.ref, ok: false, reason: 'unpack error' });
return { unpackOk, unpackDetail, refs };
}
for (const command of commands) {
const current = repo.refs.get(command.ref);
if (command.newOid === ZERO_OID) {
// Delete.
if (current === undefined) refs.push({ ref: command.ref, ok: false, reason: 'remote ref does not exist' });
else if (command.oldOid !== ZERO_OID && command.oldOid !== current) refs.push({ ref: command.ref, ok: false, reason: 'non-fast-forward' });
else {
repo.refs.delete(command.ref);
refs.push({ ref: command.ref, ok: true, reason: '' });
}
continue;
}
if (command.oldOid === ZERO_OID) {
// Create.
if (current !== undefined) {
refs.push({ ref: command.ref, ok: false, reason: 'already exists' });
continue;
}
} else {
// Update: the old tip must match and the new tip must descend from it.
if (current === undefined || current !== command.oldOid) {
refs.push({ ref: command.ref, ok: false, reason: 'non-fast-forward' });
continue;
}
if (!store.isAncestor(repo, command.oldOid, command.newOid)) {
refs.push({ ref: command.ref, ok: false, reason: 'non-fast-forward' });
continue;
}
}
if (!repo.objects.has(command.newOid)) {
refs.push({ ref: command.ref, ok: false, reason: 'missing object' });
continue;
}
repo.refs.set(command.ref, command.newOid);
refs.push({ ref: command.ref, ok: true, reason: '' });
}
return { unpackOk: true, unpackDetail: 'ok', refs };
}
/** The report-status body, pkt-lined inside sideband band 1. */
export function pushReportBody(result: { unpackOk: boolean; unpackDetail: string; refs: PushReportLine[] }): Buffer {
const lines: Buffer[] = [];
lines.push(pktLine(`unpack ${result.unpackOk ? 'ok' : result.unpackDetail}\n`));
for (const ref of result.refs) {
lines.push(pktLine(ref.ok ? `ok ${ref.ref}\n` : `ng ${ref.ref} ${ref.reason}\n`));
}
const report = Buffer.concat(lines);
const parts: Buffer[] = [];
const CHUNK = 32768;
for (let offset = 0; offset < report.length; offset += CHUNK) {
const piece = report.subarray(offset, Math.min(offset + CHUNK, report.length));
parts.push(pktLine(Buffer.concat([Buffer.from([1]), piece])));
}
parts.push(pktFlush());
return Buffer.concat(parts);
}
// -------------------------------------------------------------------------------------------
// upload-pack request parsing (v2 commands / v0 wants)
// -------------------------------------------------------------------------------------------
export interface UploadPackRequest {
protocol: 2 | 0;
command: 'ls-refs' | 'fetch' | null;
args: string[];
}
/** Parse a POST git-upload-pack body into its command and arguments. */
export function parseUploadPack(body: Buffer, version2: boolean): UploadPackRequest {
const packets = decodePktLines(body);
const lines: string[] = [];
let seenDelim = false;
for (const packet of packets) {
if (packet.kind === 'flush') break;
if (packet.kind === 'delim') {
seenDelim = true;
continue;
}
if (packet.kind === 'data' && packet.payload !== undefined) {
lines.push(packet.payload.toString('utf8').replace(/\n$/, ''));
}
}
if (!version2) {
// v0: wants, shallow/deepen, flush, haves, done, flush. The sections are
// separated by flush packets; flatten everything into one argument list.
return { protocol: 0, command: 'fetch', args: lines };
}
if (lines.length === 0) {
// An empty v2 body asks for the capability advertisement.
return { protocol: 2, command: null, args: [] };
}
const first = lines[0] ?? '';
if (first === 'command=ls-refs') {
// Capability lines sit before the delim; arguments after it.
const delimAt = packets.findIndex((packet) => packet.kind === 'delim');
const after: string[] = [];
let pastDelim = false;
for (const packet of packets) {
if (packet.kind === 'delim') {
pastDelim = true;
continue;
}
if (packet.kind === 'flush') break;
if (pastDelim && packet.kind === 'data' && packet.payload !== undefined) {
after.push(packet.payload.toString('utf8').replace(/\n$/, ''));
}
}
void delimAt;
void seenDelim;
return { protocol: 2, command: 'ls-refs', args: after };
}
if (first === 'command=fetch') {
const after: string[] = [];
let pastDelim = false;
for (const packet of packets) {
if (packet.kind === 'delim') {
pastDelim = true;
continue;
}
if (packet.kind === 'flush') break;
if (pastDelim && packet.kind === 'data' && packet.payload !== undefined) {
after.push(packet.payload.toString('utf8').replace(/\n$/, ''));
}
}
return { protocol: 2, command: 'fetch', args: after };
}
throw new Error(`unknown upload-pack command ${JSON.stringify(first)}`);
}