main
1// Pure tree edits. A `lazy` node is an object the server already has (we send nothing for it). A `dir` is a tree
2// this commit is rebuilding. Empty directories are pruned; git does not store them. The root may be empty.
3import { plyError, encodeTree, hashObject } from 'ply';
4import { unwrap } from '../ply-result.ts';
5import { mapGet } from '../absent.ts';
6import { orNull } from '../option.ts';
7import { MODE_TREE, NOT_FOUND } from './constants.ts';
8import type { BlobMode } from './request.ts';
10export type Mem =
11 | { readonly kind: 'lazy'; readonly mode: string; readonly oid: string }
12 | { readonly kind: 'dir'; readonly entries: ReadonlyMap<string, Mem> };
14export type TreeObject = { readonly oid: string; readonly data: Uint8Array };
16export function emptyDir(): Mem {
17 return { kind: 'dir', entries: new Map() };
18}
20export function lazyNode(mode: string, oid: string): Mem {
21 return { kind: 'lazy', mode, oid };
22}
24export function isTree(node: Mem): boolean {
25 return node.kind === 'dir' || node.mode === MODE_TREE;
26}
28function withEntry(dir: Mem, name: string, child: Mem | null): Mem {
29 if (dir.kind !== 'dir') throw plyError('internal', 'withEntry on a file');
30 const entries = new Map(dir.entries);
31 if (child === null) entries.delete(name);
32 else entries.set(name, child);
33 return { kind: 'dir', entries };
34}
36/** Replace one child of an already-expanded directory. */
37export function setChild(dir: Mem, name: string, child: Mem): Mem {
38 return withEntry(dir, name, child);
39}
41export function lookup(node: Mem, comps: readonly string[]): Mem | null {
42 let cur = node;
43 for (const name of comps) {
44 if (cur.kind !== 'dir') return null;
45 const next = cur.entries.get(name);
46 if (!next) return null;
47 cur = next;
48 }
49 return cur;
50}
52/** Where `comps` sits inside the caller's full `path`. `name` is the component under consideration. */
53function pathPlace(path: string, comps: readonly string[], name: string): { readonly existingPath: string; readonly here: string } {
54 const at = comps.join('/');
55 const existingPath = path === at ? '' : path.slice(0, path.length - at.length - 1);
56 return { existingPath, here: existingPath === '' ? name : `${existingPath}/${name}` };
57}
59function requireDir(node: Mem, path: string): asserts node is { kind: 'dir'; entries: ReadonlyMap<string, Mem> } {
60 if (node.kind !== 'dir') throw plyError('internal', `${path}: tree was not expanded before the edit`);
61}
63/** Insert or replace `leaf` at `comps`. Intermediate directories are created. `overwrite` is write, not create. */
64export function putAt(node: Mem, comps: readonly string[], leaf: Mem, overwrite: boolean, path: string): Mem {
65 requireDir(node, path);
66 const [name, ...rest] = comps;
67 if (!name) throw plyError('bad_request', 'path is empty');
68 const prev = orNull(mapGet(node.entries, name));
69 if (rest.length === 0) {
70 if (prev && isTree(prev)) throw plyError('bad_request', `${path} is a directory`);
71 if (prev && !overwrite) throw plyError('bad_request', `${path} already exists`);
72 return withEntry(node, name, leaf);
73 }
74 if (prev && !isTree(prev)) throw plyError('bad_request', `${path} replaces a file with a directory`);
75 const child = prev && prev.kind === 'dir' ? prev : emptyDir();
76 if (prev && prev.kind !== 'dir') throw plyError('internal', `${path}: tree was not expanded before the edit`);
77 return withEntry(node, name, putAt(child, rest, leaf, overwrite, path));
78}
80/** Remove `comps`. A directory that becomes empty is dropped, so the root is the only tree that may have no entries. */
81export function removeAt(node: Mem, comps: readonly string[], path: string): Mem {
82 requireDir(node, path);
83 const [name, ...rest] = comps;
84 if (!name) throw plyError('bad_request', 'path is empty');
85 const prev = node.entries.get(name);
86 const place = pathPlace(path, comps, name);
87 if (!prev) throw plyError('not_found', `${path} not found`, { miss: { kind: 'path', missing: name, existingPath: place.existingPath } });
88 if (rest.length === 0) return withEntry(node, name, null);
89 if (prev.kind !== 'dir') throw plyError('not_found', `${path} not found`, { miss: { kind: 'not_directory', path: place.here, mode: prev.mode } });
90 const child = removeAt(prev, rest, path);
91 if (child.kind === 'dir' && child.entries.size === 0) return withEntry(node, name, null);
92 return withEntry(node, name, child);
93}
95export function renameAt(node: Mem, from: readonly string[], to: readonly string[]): Mem {
96 const source = from.join('/');
97 const dest = to.join('/');
98 if (source === dest) throw plyError('bad_request', `${source} is already ${dest}`);
99 if (dest.startsWith(`${source}/`)) throw plyError('bad_request', `cannot rename ${source} into itself`);
100 const found = lookup(node, from);
101 if (!found) throw plyError('not_found', `${source} not found`, { miss: { kind: 'path', missing: source, existingPath: '' } });
102 if (lookup(node, to)) throw plyError('bad_request', `${dest} already exists`);
103 return putAt(removeAt(node, from, source), to, found, false, dest);
104}
106export function fileLeaf(mode: BlobMode, oid: string): Mem {
107 return lazyNode(mode, oid);
108}
110/** Bottom-up encode. Lazy nodes contribute their oid and no bytes: the server already has them. */
111export function encodeMem(node: Mem): { oid: string; trees: TreeObject[] } {
112 if (node.kind === 'lazy') return { oid: node.oid, trees: [] };
113 const trees: TreeObject[] = [];
114 const seen = new Set<string>();
115 const entries: { mode: string; name: string; oid: string }[] = [];
116 for (const [name, child] of node.entries) {
117 const sub = encodeMem(child);
118 for (const tree of sub.trees) if (!seen.has(tree.oid)) { seen.add(tree.oid); trees.push(tree); }
119 entries.push({ mode: child.kind === 'dir' ? MODE_TREE : child.mode, name, oid: sub.oid });
120 }
121 const data = unwrap(encodeTree(entries)) as Uint8Array;
122 const oid = hashObject('tree', data) as string;
123 if (!seen.has(oid)) trees.push({ oid, data });
124 return { oid, trees };
125}
127function indexOfBytes(hay: Uint8Array, needle: Uint8Array, from: number): number {
128 if (needle.length === 0) return from;
129 const last = hay.length - needle.length;
130 for (let i = from; i <= last; i += 1) {
131 let matched = true;
132 for (let j = 0; j < needle.length; j += 1) if (hay[i + j] !== needle[j]) { matched = false; break; }
133 if (matched) return i;
134 }
135 return NOT_FOUND;
136}
138export type ReplaceResult = { readonly kind: 'replaced'; readonly data: Uint8Array } | { readonly kind: 'count'; readonly matches: number };
140/** Non-overlapping find, the same contract as ply's edit: exactly one match. */
141export function replaceOnce(hay: Uint8Array, needle: Uint8Array, insert: Uint8Array): ReplaceResult {
142 if (needle.length === 0) return { kind: 'count', matches: 0 };
143 const at = indexOfBytes(hay, needle, 0);
144 if (at === NOT_FOUND) return { kind: 'count', matches: 0 };
145 const second = indexOfBytes(hay, needle, at + needle.length);
146 if (second !== NOT_FOUND) {
147 let matches = 2;
148 let from = second + needle.length;
149 for (;;) {
150 const next = indexOfBytes(hay, needle, from);
151 if (next === NOT_FOUND) break;
152 matches += 1;
153 from = next + needle.length;
154 }
155 return { kind: 'count', matches };
156 }
157 const out = new Uint8Array(hay.length - needle.length + insert.length);
158 out.set(hay.subarray(0, at), 0);
159 out.set(insert, at);
160 out.set(hay.subarray(at + needle.length), at + insert.length);
161 return { kind: 'replaced', data: out };
162}
Diagnostics4 git calls · 26 ms
CallStatusSizeTime026 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B · hit4 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=4 git.response.bytes=145 git.response.cache=HIT git.response.duration_ms=4 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020040 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=41349 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=526b305930b8ef382f2d7a1f9c0238730a585921 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=41349 git.pkt.payload.max=41254 git.sideband.band1.bytes=41253 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=61 git.pack.bytes=41253 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=ab60efef4b7243678c75de64a4386986ee885c1c git.pack.full=61Open pack map
fetch2002.3 KiB · hit19 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=19 git.response.bytes=2386 git.response.cache=HIT git.response.duration_ms=19 git.fetch.wants=947234c3bef1349e59f83f7a942537e65ef52ea9 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=2386 git.pkt.payload.max=2365 git.sideband.band1.bytes=2364 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply-web.git
- Ref
- refs/heads/main
- Commit
- 526b305930b8ef382f2d7a1f9c0238730a585921
- cf-ray
- a5e23c84ae814bc2
- Request
- b7896b47…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format