GitHubivarvong
ply
main
1// A new customer's first day, as README.md "Quick start: a repo end to end" writes it: every `// quick-start:` block is
2// read from the README and executed as written (imports from 'ply' bound to the package entry, src/index.ts), in order,
3// against `git http-backend`, and after every step real git says the repository is what git would have made (rev-parse,
4// ls-tree, show, merge-tree, rev-list, cat-file, clone + diff -r, fsck --strict). test/types/readme.typetest.ts is the
5// same blocks as TypeScript (generated from the README; this file fails when it drifts: UPDATE_README_TYPETEST=1).
6//
7// Two server configurations:
8// default makeBareRepo: uploadpack.allowFilter, allowAnySHA1InWant, protocol.version 2 (the fixture every suite uses)
9// stock makeBareRepo { stock: true }: upload-pack at git's defaults (no filter, no any-SHA-1 wants), as a
10// `git init --bare` behind `git http-backend` with `http.receivepack true` serves it
11// The stock server runs the whole lifecycle on one repository, and again step by step, each step from a copy of the
12// default run's repository just before it (with the default run's variables), so each step is judged on its own too.
13import { test, describe, beforeAll as before, afterAll as after } from 'vitest';
14import assert from 'node:assert/strict';
15import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
16import { join } from 'node:path';
17import { spawnSync } from 'node:child_process';
18import * as ply from '../src/index.js';
19import * as plyCheckoutNode from '../src/checkout-node.js';
20import { git, tmpRoot, makeBareRepo, startGitServer, fsckProblems, commitFiles, initRepo } from './server.js';
22const ZERO = '0'.repeat(40);
23const README_PATH = new URL('../README.md', import.meta.url);
24const TYPETEST_PATH = new URL('./types/readme.typetest.ts', import.meta.url);
25const MODULES = { ply, 'ply/checkout-node': plyCheckoutNode };
26const TS_SPECIFIER = { ply: '../../src/index.js', 'ply/checkout-node': '../../src/checkout-node.js' };
28// ---- the README's quick-start blocks ----
29const BLOCK = /```js\n\/\/ quick-start: ([\w-]+)\n([\s\S]*?)```/g;
30const IMPORT = /^import \{([^}]+)\} from '([^']+)';\n/gm;
31function readmeBlocks(text) {
32 return [...text.matchAll(BLOCK)].map(([, step, code]) => {
33 const imports = [...code.matchAll(IMPORT)].map(([, names, from]) => ({ names: names.split(',').map(s => s.trim()).filter(Boolean), from }));
34 const body = code.replace(IMPORT, '');
35 const declared = [...body.matchAll(/^(?:const|let) (\w+)/gm)].map(m => m[1]);
36 return { step, code, imports, body, declared };
37 });
38}
39const BLOCKS = readmeBlocks(readFileSync(README_PATH, 'utf8'));
40const STEPS = BLOCKS.map(b => b.step).filter(s => s !== 'setup');
42// The TypeScript twin: every block in order, its imports pointed at src/. Top-level await, never run (tsc only).
43function typetestOf(blocks) {
44 const head = '// GENERATED from README.md "Quick start" by test/e2e-customer.test.js (UPDATE_README_TYPETEST=1 rewrites it).\n'
45 + '// The README blocks as a TypeScript consumer writes them, plain strings for refs and paths: `npm run typecheck` compiles\n'
46 + '// it, under tsconfig.isolated.json too.\n';
47 return head + blocks.map(b => `\n// ---- ${b.step} ----\n${b.code.replace(IMPORT, (_, names, from) => `import {${names}} from '${TS_SPECIFIER[from] ?? from}';\n`)}`).join('');
48}
50// A silent console that keeps what the blocks print.
51const quietConsole = () => { const lines = []; const keep = (...a) => { lines.push(a); }; return { lines, log: keep, warn: keep, error: keep, info: keep }; };
52const AsyncFunction = (async () => {}).constructor;
53// Run one block with `scope` as its free variables (earlier blocks' declarations and imports, the setup values);
54// returns the scope plus what the block declared at top level.
55async function runBlock(block, scope) {
56 const bound = { ...scope };
57 for (const { names, from } of block.imports) for (const n of names) bound[n] = MODULES[from][n];
58 const names = Object.keys(bound);
59 const fn = new AsyncFunction(...names, `${block.body}\nreturn { ${block.declared.join(', ')} };`);
60 return { ...bound, ...(await fn(...names.map(n => bound[n]))) };
61}
63// ---- git as the oracle ----
64const rev = (bare, r) => git(bare, ['rev-parse', '--verify', '-q', r]).trim();
65const has = (bare, r) => spawnSync('git', ['rev-parse', '--verify', '-q', r], { cwd: bare }).status === 0;
66const show = (bare, spec) => git(bare, ['show', spec]);
67const files = bare => git(bare, ['ls-tree', '-r', '--name-only', 'main']).trim().split('\n');
68const parentsOf = (bare, r) => git(bare, ['rev-list', '--parents', '-n', '1', r]).trim().split(' ').slice(1);
69const subject = (bare, r) => git(bare, ['log', '-1', '--format=%s', r]).trim();
70const clean = bare => assert.deepEqual(fsckProblems(bare), [], 'git fsck --strict');
71// The tree git itself writes for `files` applied to `parent` (a clone, the edits, add -A, write-tree).
72function gitTree(bare, parent, apply) {
73 const work = `${bare}-work-${Math.random().toString(36).slice(2)}`;
74 git(join(bare, '..'), ['clone', '-q', '--no-checkout', bare, work]);
75 git(work, ['-c', 'advice.detachedHead=false', 'checkout', '-q', parent]);
76 apply(work);
77 git(work, ['add', '-A']);
78 return git(work, ['write-tree']).trim();
79}
81// What each step must leave behind, given the scope after it ran.
82const CHECKS = {
83 'first-commit': (bare, s) => {
84 assert.equal(rev(bare, 'refs/heads/main'), s.first.value.newCommit);
85 assert.deepEqual(parentsOf(bare, 'main'), [], 'a root commit');
86 assert.equal(git(bare, ['ls-tree', 'main', 'bin/build']).split(' ')[0], '100755');
87 assert.equal(show(bare, 'main:src/config.ts'), 'export const VERSION = "1.2.3";\n');
88 assert.equal(s.first.value.newTree, gitTree(bare, 'main', () => {}), 'tree git writes for the same files');
89 clean(bare);
90 },
91 read: (bare, s) => {
92 assert.equal(s.head.value.oid, rev(bare, 'main'));
93 assert.equal(s.head.value.tree, rev(bare, 'main^{tree}'));
94 assert.equal(s.head.value.message, git(bare, ['cat-file', 'commit', 'main']).split('\n\n').slice(1).join('\n\n'));
95 const lsTree = git(bare, ['ls-tree', 'main:src']).trim().split('\n').map(l => { const [meta, name] = l.split('\t'); const [mode, type, oid] = meta.split(' '); return { mode, type, oid, name }; });
96 assert.deepEqual(s.listing.value.entries.map(e => ({ mode: e.mode, type: e.type, oid: e.oid, name: e.name })), lsTree);
97 assert.equal(s.config, show(bare, 'main:src/config.ts'));
98 },
99 edit: (bare, s) => {
100 assert.equal(rev(bare, 'main'), s.bump.value.newCommit);
101 assert.equal(s.bump.value.noop, false);
102 assert.deepEqual(parentsOf(bare, 'main'), [s.first.value.newCommit]);
103 assert.equal(show(bare, 'main:src/config.ts'), 'export const VERSION = "1.2.4";\n');
104 assert.equal(git(bare, ['diff', '--name-only', 'main^', 'main']).trim(), 'src/config.ts');
105 assert.equal(subject(bare, 'main'), 'Bump version to 1.2.4');
106 clean(bare);
107 },
108 'commit-changes': (bare, s) => {
109 assert.equal(s.change.value.outcome, 'commit');
110 assert.equal(rev(bare, 'main'), s.change.value.oid);
111 assert.deepEqual(parentsOf(bare, 'main'), [s.bump.value.newCommit]);
112 const expected = gitTree(bare, s.bump.value.newCommit, w => {
113 mkdirSync(join(w, 'docs'), { recursive: true });
114 writeFileSync(join(w, 'docs/index.md'), '# Intro\n');
115 writeFileSync(join(w, 'README.md'), '# site\n\nHello.\n');
116 writeFileSync(join(w, 'src/config.ts'), 'export const VERSION = "1.3.0";\n');
117 git(w, ['rm', '-q', 'bin/build']);
118 });
119 assert.equal(rev(bare, 'main^{tree}'), expected, 'the tree git writes for the same changes');
120 assert.deepEqual(files(bare), ['README.md', 'docs/index.md', 'src/config.ts']);
121 clean(bare);
122 },
123 'branch-merge': (bare, s) => {
124 assert.equal(s.feature.value.oid, s.change.value.oid, 'feature created at main');
125 assert.equal(rev(bare, 'refs/heads/feature'), s.work.value.oid);
126 assert.deepEqual(parentsOf(bare, 'feature'), [s.change.value.oid]);
127 assert.equal(s.merged.value.outcome, 'merge');
128 assert.equal(rev(bare, 'main'), s.merged.value.oid);
129 assert.deepEqual(parentsOf(bare, 'main'), [s.hotfix.value.newCommit, s.work.value.oid]);
130 const mergeTree = git(bare, ['merge-tree', '--write-tree', s.hotfix.value.newCommit, s.work.value.oid]).trim().split('\n')[0];
131 assert.equal(rev(bare, 'main^{tree}'), mergeTree, 'git merge-tree --write-tree');
132 assert.equal(show(bare, 'main:README.md'), '# site\n\nHello, world.\n');
133 assert.equal(show(bare, 'main:src/feature.ts'), 'export const feature = true;\n');
134 clean(bare);
135 },
136 tag: (bare, s) => {
137 assert.equal(git(bare, ['cat-file', '-t', 'refs/tags/v1.3.0']).trim(), 'commit');
138 assert.equal(rev(bare, 'refs/tags/v1.3.0'), rev(bare, 'main'));
139 assert.equal(s.release.value.annotated, false);
140 assert.equal(git(bare, ['cat-file', '-t', 'refs/tags/v1.3.0-notes']).trim(), 'tag');
141 assert.equal(rev(bare, 'refs/tags/v1.3.0-notes'), s.notes.value.oid);
142 assert.equal(rev(bare, 'refs/tags/v1.3.0-notes^{commit}'), rev(bare, 'main'));
143 const tag = git(bare, ['cat-file', 'tag', 'refs/tags/v1.3.0-notes']);
144 assert.match(tag, /^object [0-9a-f]{40}\ntype commit\ntag v1\.3\.0-notes\ntagger Release Bot <bot@example\.com> \d+ \+0000\n\nRelease 1\.3\.0\n$/);
145 clean(bare);
146 },
147 'rebase-pick-revert': (bare, s) => {
148 assert.equal(s.rebased.value.outcome, 'rebase');
149 assert.equal(rev(bare, 'refs/heads/topic'), s.rebased.value.oid);
150 assert.deepEqual(parentsOf(bare, 'topic'), [s.onMain.value.oid], 'topic replayed onto main');
151 assert.equal(git(bare, ['diff', '--name-only', 'topic^', 'topic']).trim(), 'src/topic.ts');
152 assert.equal(git(bare, ['log', '-1', '--format=%an|%s', 'topic']).trim(), 'Release Bot|Add topic');
153 assert.equal(s.picked.value.outcome, 'ok');
154 assert.deepEqual(parentsOf(bare, s.picked.value.oid), [s.onMain.value.oid]);
155 assert.equal(rev(bare, `${s.picked.value.oid}^{tree}`), rev(bare, 'topic^{tree}'), 'the pick applies the same change');
156 assert.equal(s.reverted.value.outcome, 'ok');
157 assert.equal(rev(bare, 'main'), s.reverted.value.oid);
158 assert.deepEqual(parentsOf(bare, 'main'), [s.picked.value.oid]);
159 assert.equal(rev(bare, 'main^{tree}'), rev(bare, `${s.onMain.value.oid}^{tree}`), 'the revert undoes the pick');
160 assert.equal(subject(bare, 'main'), 'Revert "Add topic"');
161 clean(bare);
162 },
163 history: (bare, s) => {
164 const want = git(bare, ['rev-list', '--first-parent', '-n', '10', 'main']).trim().split('\n');
165 assert.deepEqual(s.log.value.commits.map(c => c.oid), want);
166 assert.equal(s.log.value.commits[0].message, git(bare, ['cat-file', 'commit', 'main']).split('\n\n').slice(1).join('\n\n'));
167 },
168 checkout: (bare, s) => {
169 assert.equal(s.tree.value.commit, rev(bare, 'v1.3.0^{commit}'));
170 assert.deepEqual(s.tree.value.entries.map(e => e.path), git(bare, ['ls-tree', '-r', '--name-only', 'v1.3.0']).trim().split('\n'));
171 const clone = `${bare}-clone-${Math.random().toString(36).slice(2)}`;
172 git(join(bare, '..'), ['clone', '-q', '-b', 'main', bare, clone]);
173 const diff = spawnSync('diff', ['-r', '--no-dereference', '-x', '.git', clone, s.outDir], { encoding: 'utf8' });
174 assert.equal(diff.status, 0, `checkoutDir equals git clone: ${diff.stdout}${diff.stderr}`);
175 assert.equal(s.written.value.written.files, files(bare).length);
176 },
177 refs: (bare, s) => {
178 // listRefs ran before the two deletes: git's refs now, plus the two it deleted, in git's (byte) order
179 const now = git(bare, ['for-each-ref', '--format=%(refname) %(objectname)', 'refs/heads/', 'refs/tags/']).trim().split('\n');
180 const want = [...now, `refs/heads/feature ${s.gone.value.oid}`, `refs/tags/v1.3.0-notes ${s.untagged.value.oid}`].sort((a, b) => (a < b ? -1 : 1));
181 assert.deepEqual(s.refs.value.refs.map(r => `${r.name} ${r.oid}`), want, 'listRefs is for-each-ref, before the deletes');
182 assert.equal(s.refs.value.head, git(bare, ['symbolic-ref', 'HEAD']).trim());
183 const notes = s.refs.value.refs.find(r => r.name === 'refs/tags/v1.3.0-notes');
184 assert.equal(notes.peeled, s.notes.value.commit, 'an annotated tag is peeled to its commit');
185 assert.equal(has(bare, 'refs/tags/v1.3.0-notes'), false);
186 assert.equal(s.untagged.value.ref, 'refs/tags/v1.3.0-notes');
187 assert.equal(has(bare, 'refs/tags/v1.3.0'), true);
188 assert.equal(has(bare, 'refs/heads/feature'), false);
189 assert.equal(s.gone.value.oid, s.work.value.oid);
190 assert.equal(has(bare, 'refs/heads/topic'), true);
191 clean(bare);
192 },
193 errors: (bare, s) => {
194 assert.equal(s.stale.ok, false);
195 assert.equal(s.stale.error.code, 'match_count');
196 assert.equal(s.stale.error.matches, 0);
197 assert.deepEqual(s.console.lines.at(-1), ['matches', 0]);
198 assert.equal(rev(bare, 'main'), s.reverted.value.oid, 'nothing pushed');
199 },
200};
202let root, cleanup, srv;
203let n = 0;
204const author = { name: 'Release Bot', email: 'bot@example.com' };
205// The setup block's names, bound to this server instead of the README's placeholders.
206const setupScope = name => ({ url: `${srv.url}/${name}.git`, opts: {}, author, outDir: join(root, `${name}-out`), console: quietConsole() });
208// A repository as the default fixture has it, or with upload-pack at git's defaults.
209const defaultRepo = name => makeBareRepo(root, name);
210const stockRepo = name => makeBareRepo(root, name, { stock: true });
211// A copy of `bare` reconfigured as makeBareRepo's stock: the upload-pack keys unset again.
212function stockCopy(bare, name) {
213 const dir = join(root, `${name}.git`);
214 cpSync(bare, dir, { recursive: true });
215 for (const k of ['uploadpack.allowFilter', 'uploadpack.allowAnySHA1InWant', 'protocol.version']) spawnSync('git', ['config', '--unset', k], { cwd: dir });
216 const left = spawnSync('git', ['config', '--get-regexp', '^(uploadpack|protocol)\\.'], { cwd: dir, encoding: 'utf8' });
217 assert.equal(left.stdout, '', 'stock: no upload-pack or protocol keys');
218 return dir;
219}
221before(async () => {
222 ({ root, cleanup } = tmpRoot());
223 srv = await startGitServer(root);
224});
225after(async () => { await srv?.close(); cleanup?.(); });
227describe('README quick start', () => {
228 test('the blocks: setup names what the test binds, every import is a real export', () => {
229 assert.deepEqual(BLOCKS.map(b => b.step), ['setup', 'first-commit', 'read', 'edit', 'commit-changes', 'branch-merge', 'tag', 'rebase-pick-revert', 'history', 'checkout', 'refs', 'errors']);
230 assert.deepEqual(BLOCKS[0].declared, ['url', 'opts', 'author', 'outDir']);
231 for (const b of BLOCKS) for (const { names, from } of b.imports) for (const name of names) assert.equal(typeof MODULES[from]?.[name], 'function', `${b.step}: ${name} from '${from}'`);
232 for (const step of STEPS) assert.equal(typeof CHECKS[step], 'function', `a git check for ${step}`);
233 });
234 test('opts.tracer is optional: no tracer works (spans dropped); a value that is not a Tracer is bad_request', async () => {
235 defaultRepo('no-tracer');
236 const url = `${srv.url}/no-tracer.git`;
237 const first = await ply.pushTree(url, { ref: 'refs/heads/main', create: true, files: { 'a.txt': 'a\n' }, author, message: 'first' });
238 assert.equal(first.ok, true, first.ok ? '' : first.error.message);
239 const read = await ply.readCommit(url, { ref: 'main' });
240 assert.equal(read.ok && 'oid' in read.value ? read.value.oid : null, first.value.newCommit);
241 const listed = await ply.listRefs(url);
242 assert.deepEqual(listed.ok ? listed.value : listed.error.message, { head: 'refs/heads/main', refs: [{ name: 'refs/heads/main', oid: first.value.newCommit, peeled: null }] });
243 for (const r of [await ply.deleteTag(url, { name: '' }), await ply.listRefs(url, { prefixes: [''] }), await ply.listRefs(url, { prefixes: 'refs/' })]) {
244 assert.equal(r.ok ? 'ok' : r.error.code, 'bad_request');
245 }
246 for (const tracer of [{}, 7, 'x']) {
247 const r = await ply.readCommit(url, { ref: 'main' }, { tracer });
248 assert.equal(r.ok, false);
249 assert.equal(r.error.code, 'bad_request');
250 assert.match(r.error.message, /opts\.tracer must be a Tracer/);
251 }
252 });
253 test('#186: the low-level calls work on a transport made without a tracer; parseTag and TYPE_ID are exported', async () => {
254 defaultRepo('low-level');
255 const url = `${srv.url}/low-level.git`;
256 const first = await ply.pushTree(url, { ref: 'refs/heads/main', files: { 'a.txt': 'a\n' }, author, message: 'first' });
257 assert.equal(first.ok, true);
258 const t = ply.createTransport(url, {});
259 assert.equal(t.ok, true);
260 const listed = await ply.lsRefs(t.value, ['refs/heads/']);
261 assert.equal(listed.ok ? listed.value.refs.get('refs/heads/main').oid : listed.error.message, first.value.newCommit);
262 const pushed = await ply.push(t.value, { ref: 'refs/heads/copy', oldOid: ply.ZERO_OID, newOid: first.value.newCommit, objects: [] });
263 assert.equal(pushed.ok, true, pushed.ok ? '' : pushed.error.message);
264 assert.equal(rev(join(root, 'low-level.git'), 'refs/heads/copy'), first.value.newCommit);
265 assert.equal(typeof ply.parseTag, 'function');
266 assert.deepEqual([ply.TYPE_ID.commit, ply.TYPE_ID.tree, ply.TYPE_ID.blob, ply.TYPE_ID.tag], [1, 2, 3, 4]);
267 const tag = ply.encodeTag({ object: first.value.newCommit, type: 'commit', tag: 'v1', tagger: ply.ident(ply.validateIdent({ ...author, time: 1, tz: '+0000' }).value).value, message: 'm\n' });
268 const parsed = ply.parseTag(tag.value);
269 assert.equal(parsed.ok ? parsed.value.object : parsed.error.message, first.value.newCommit);
270 });
271 // README "Your own code failing": a function the caller passes that throws and reaches the end of an operation is
272 // what: 'callback' with the thrown value as cause; before the push request was handed to the transport it is
273 // definite (bad_request), once it was it is ambiguous. The body stands in for such a function (ply.operation is the
274 // public edge every operation runs through). Expected values are the README's, not ply's output; git holds the ref.
275 test('a caller callback that throws at operation()\'s edge: bad_request \'callback\' before the push, ambiguous after', async () => {
276 defaultRepo('callback-edge');
277 const bare = join(root, 'callback-edge.git');
278 const url = `${srv.url}/callback-edge.git`;
279 const first = await ply.pushTree(url, { ref: 'refs/heads/main', files: { 'a.txt': 'a\n' }, author, message: 'first' });
280 assert.equal(first.ok, true, first.ok ? '' : first.error.message);
281 const before = first.value.newCommit;
282 const thrown = new Error('caller boom');
283 const definite = await ply.operation('probe', url, {}, async () => { await null; throw thrown; });
284 assert.equal(definite.ok, false);
285 assert.deepEqual([definite.error.code, definite.error.what, definite.error.cause === thrown, definite.error.message], ['bad_request', 'callback', true, 'caller-supplied callback threw: caller boom']);
286 const thrown2 = new Error('caller boom after');
287 const handed = await ply.operation('probe', url, {}, async ({ t, root: span }) => { await null; t.frames('git-receive-pack', new Uint8Array(0), span, {}); throw thrown2; });
288 assert.equal(handed.ok, false);
289 assert.deepEqual([handed.error.code, handed.error.what, handed.error.cause === thrown2], ['ambiguous', 'callback', true]);
290 // the message leads with the operation's name (its span, git.<name>), then says the outcome is unknown and why
291 assert.match(handed.error.message, /^git\.probe: a caller-supplied callback threw after the push request was handed to the transport, push outcome unknown: caller boom after$/);
292 assert.equal(rev(bare, 'refs/heads/main'), before, 'git: the ref did not move');
293 });
294 test('test/types/readme.typetest.ts is the README blocks (UPDATE_README_TYPETEST=1 regenerates it)', () => {
295 const want = typetestOf(BLOCKS);
296 if (process.env.UPDATE_README_TYPETEST) writeFileSync(TYPETEST_PATH, want);
297 assert.equal(existsSync(TYPETEST_PATH) ? readFileSync(TYPETEST_PATH, 'utf8') : '', want);
298 });
299});
301// The default run: one repository through every step. Before each step its state (repository and variables) is kept
302// for the stock run.
303const before_ = new Map();
304describe('lifecycle, default server (allowFilter on)', () => {
305 let bare, scope;
306 test.each(STEPS)('%s', async step => {
307 if (step === STEPS[0]) { bare = defaultRepo('main-default'); scope = setupScope('main-default'); }
308 const snap = join(root, `snap-${step}`);
309 cpSync(bare, snap, { recursive: true });
310 before_.set(step, { snap, scope });
311 scope = await runBlock(BLOCKS.find(b => b.step === step), scope);
312 CHECKS[step](bare, scope);
313 });
314});
316// Each step on a stock server, from the default run's state just before it.
317describe('lifecycle, stock server (upload-pack defaults), step by step', () => {
318 for (const step of STEPS) {
319 test(step, async () => {
320 const from = before_.get(step);
321 assert.ok(from, `the default run reached ${step}`);
322 const name = `stock-${step}-${n++}`;
323 const bare = stockCopy(from.snap, name);
324 const scope = { ...from.scope, ...setupScope(name), console: quietConsole() };
325 const after_ = await runBlock(BLOCKS.find(b => b.step === step), scope);
326 CHECKS[step](bare, after_);
327 });
328 }
329});
331// The whole lifecycle on one stock repository.
332describe('lifecycle, stock server (upload-pack defaults), continuous', () => {
333 let bare, scope;
334 test.each(STEPS)('%s', async step => {
335 if (step === STEPS[0]) { bare = stockRepo('main-stock'); scope = setupScope('main-stock'); }
336 scope = await runBlock(BLOCKS.find(b => b.step === step), scope);
337 CHECKS[step](bare, scope);
338 });
339});
341// createBranch / deleteBranch / createTag beyond the happy path, on both servers: git says what the ref is after each.
342const opts = () => ({ tracer: new ply.Tracer() });
343const errOf = r => { assert.equal(r.ok, false, 'an Err'); return r.error; };
344for (const kind of ['default', 'stock']) {
345 describe(`ref operations, ${kind} server`, () => {
346 let bare, url, c1, c2;
347 before(() => {
348 const name = `refs-${kind}`;
349 bare = kind === 'default' ? defaultRepo(name) : stockRepo(name);
350 url = `${srv.url}/${name}.git`;
351 const work = join(root, `${name}-seed`);
352 initRepo(work);
353 c1 = commitFiles(work, bare, { 'a.txt': 'one\n' }, 'one');
354 c2 = commitFiles(work, bare, { 'a.txt': 'two\n' }, 'two');
355 git(bare, ['tag', '-a', '-m', 'annotated', 'v-ann', c1]);
356 });
358 test('createBranch from a branch name, a short name, a peeled annotated tag', async () => {
359 for (const [ref, from, want] of [['refs/heads/b-full', 'refs/heads/main', () => c2], ['refs/heads/b-short', 'main', () => c2], ['refs/heads/b-tag', 'v-ann', () => c1]]) {
360 const r = await ply.createBranch(url, { ref, from }, { ...opts(), verify: true });
361 assert.ok(r.ok, `${ref}: ${r.ok || r.error.message}`);
362 assert.equal(r.value.oid, want());
363 assert.equal(rev(bare, ref), want());
364 assert.equal(r.value.pushBytes > 0, true, 'an empty pack, still framed');
365 }
366 clean(bare);
367 });
368 test('createBranch from a 40-hex commit id that is not a tip', async () => {
369 const r = await ply.createBranch(url, { ref: 'refs/heads/b-oid', from: c1 }, opts());
370 assert.ok(r.ok, r.ok || r.error.message);
371 assert.equal(rev(bare, 'refs/heads/b-oid'), c1);
372 });
373 test('createBranch refuses: an existing branch (cas_conflict, actual its tip), a missing from, a bad ref, the zero id', async () => {
374 const exists = errOf(await ply.createBranch(url, { ref: 'refs/heads/main', from: c1 }, opts()));
375 assert.equal(exists.code, 'cas_conflict');
376 assert.equal(exists.expected, ZERO);
377 assert.equal(exists.actual, c2);
378 assert.equal(rev(bare, 'main'), c2, 'untouched');
379 const missing = errOf(await ply.createBranch(url, { ref: 'refs/heads/x', from: 'refs/heads/nope' }, opts()));
380 assert.equal(missing.code, 'not_found');
381 assert.equal(missing.miss.kind, 'ref');
382 assert.equal(errOf(await ply.createBranch(url, { ref: 'heads/x', from: 'main' }, opts())).code, 'bad_request');
383 assert.equal(errOf(await ply.createBranch(url, { ref: 'refs/heads/x', from: '' }, opts())).code, 'bad_request');
384 assert.equal(errOf(await ply.createBranch(url, { ref: 'refs/heads/x', from: ZERO }, opts())).code, 'bad_request');
385 assert.equal(has(bare, 'refs/heads/x'), false);
386 });
387 test('createBranch and createTag lose a race to a ref made between ls-refs and receive-pack: cas_conflict naming the winner', async () => {
388 const racing = ref => async (input, init) => {
389 if (String(input).endsWith('/git-receive-pack')) git(bare, ['update-ref', ref, c1]);
390 return fetch(input, init);
391 };
392 const branch = errOf(await ply.createBranch(url, { ref: 'refs/heads/race', from: 'main' }, { ...opts(), fetchImpl: racing('refs/heads/race') }));
393 assert.equal(branch.code, 'cas_conflict', branch.message);
394 assert.equal(branch.expected, ZERO);
395 assert.equal(branch.actual, c1);
396 const tag = errOf(await ply.createTag(url, { name: 'race', target: 'main' }, { ...opts(), fetchImpl: racing('refs/tags/race') }));
397 assert.equal(tag.code, 'cas_conflict', tag.message);
398 assert.equal(tag.actual, c1);
399 assert.equal(rev(bare, 'refs/heads/race'), c1);
400 clean(bare);
401 });
402 test('deleteBranch: stale expected (cas_conflict, nothing sent), absent (not_found), HEAD\'s branch (the server\'s push_rejected), then a delete', async () => {
403 git(bare, ['update-ref', 'refs/heads/gone', c2]);
404 const stale = errOf(await ply.deleteBranch(url, { ref: 'refs/heads/gone', expected: c1 }, opts()));
405 assert.equal(stale.code, 'cas_conflict');
406 assert.equal(stale.expected, c1);
407 assert.equal(stale.actual, c2);
408 assert.equal(rev(bare, 'refs/heads/gone'), c2);
409 assert.equal(errOf(await ply.deleteBranch(url, { ref: 'refs/heads/gone', expected: 'abc' }, opts())).code, 'bad_request');
410 const head = errOf(await ply.deleteBranch(url, { ref: 'refs/heads/main' }, opts()));
411 assert.equal(head.code, 'push_rejected');
412 assert.match(head.message, /current branch/);
413 assert.equal(rev(bare, 'main'), c2);
414 const r = await ply.deleteBranch(url, { ref: 'refs/heads/gone', expected: c2 }, opts());
415 assert.ok(r.ok, r.ok || r.error.message);
416 assert.equal(r.value.oid, c2);
417 assert.equal(has(bare, 'refs/heads/gone'), false);
418 const absent = errOf(await ply.deleteBranch(url, { ref: 'refs/heads/gone' }, opts()));
419 assert.equal(absent.code, 'not_found');
420 assert.equal(absent.miss.kind, 'ref');
421 clean(bare);
422 });
423 test('#116: deleteBranch loses a race between ls-refs and receive-pack: cas_conflict naming the winner\'s tip, or null when it was deleted', async () => {
424 const racing = (...args) => async (input, init) => {
425 if (String(input).endsWith('/git-receive-pack')) git(bare, args);
426 return fetch(input, init);
427 };
428 git(bare, ['update-ref', 'refs/heads/del-race', c2]);
429 const moved = errOf(await ply.deleteBranch(url, { ref: 'refs/heads/del-race' }, { ...opts(), fetchImpl: racing('update-ref', 'refs/heads/del-race', c1) }));
430 assert.equal(moved.code, 'cas_conflict', moved.message);
431 assert.equal(moved.expected, c2, 'the tip ls-refs reported');
432 assert.equal(moved.actual, c1, 'the tip the winner left, read back');
433 assert.equal(rev(bare, 'refs/heads/del-race'), c1, 'untouched');
434 const gone = errOf(await ply.deleteBranch(url, { ref: 'refs/heads/del-race' }, { ...opts(), fetchImpl: racing('update-ref', '-d', 'refs/heads/del-race') }));
435 assert.equal(gone.code, 'cas_conflict', gone.message);
436 assert.equal(gone.expected, c1);
437 assert.equal(gone.actual, null, 'deleted by the winner: absent');
438 assert.equal(has(bare, 'refs/heads/del-race'), false);
439 clean(bare);
440 });
441 test('createTag: lightweight and annotated (as git tag -a writes it), refusals', async () => {
442 const light = await ply.createTag(url, { name: 'refs/tags/l1', target: 'main' }, { ...opts(), verify: true });
443 assert.ok(light.ok, light.ok || light.error.message);
444 assert.equal(git(bare, ['cat-file', '-t', 'refs/tags/l1']).trim(), 'commit');
445 assert.equal(rev(bare, 'refs/tags/l1'), c2);
446 const tagger = { name: 'T', email: 't@x', time: 1700000000, tz: '+0100' };
447 const ann = await ply.createTag(url, { name: 'a1', target: 'refs/heads/main', message: 'Release one', tagger }, { ...opts(), verify: true });
448 assert.ok(ann.ok, ann.ok || ann.error.message);
449 assert.equal(ann.value.annotated, true);
450 assert.equal(ann.value.commit, c2);
451 assert.equal(rev(bare, 'refs/tags/a1'), ann.value.oid);
452 // git tag -a in a clone with the same tagger and time writes the same object
453 const work = join(root, `tag-${kind}`);
454 git(root, ['clone', '-q', bare, work]);
455 git(work, ['tag', '-a', '-m', 'Release one', 'a1-git', c2], { env: { ...process.env, GIT_COMMITTER_NAME: 'T', GIT_COMMITTER_EMAIL: 't@x', GIT_COMMITTER_DATE: '1700000000 +0100' } });
456 assert.equal(git(work, ['cat-file', 'tag', 'a1-git']).replace('tag a1-git', 'tag a1'), git(bare, ['cat-file', 'tag', 'refs/tags/a1']));
457 const exists = errOf(await ply.createTag(url, { name: 'a1', target: c1 }, opts()));
458 assert.equal(exists.code, 'cas_conflict');
459 assert.equal(exists.actual, ann.value.oid);
460 assert.equal(errOf(await ply.createTag(url, { name: 'n1', target: 'main', message: 'no tagger' }, opts())).code, 'bad_request');
461 assert.equal(errOf(await ply.createTag(url, { name: '', target: 'main' }, opts())).code, 'bad_request');
462 assert.equal(errOf(await ply.createTag(url, { name: 'n2', target: '' }, opts())).code, 'bad_request');
463 assert.equal(errOf(await ply.createTag(url, { name: 'bad..name', target: 'main' }, opts())).code, 'bad_request');
464 assert.equal(errOf(await ply.createTag(url, { name: 'n3', target: 'refs/heads/nope' }, opts())).code, 'not_found');
465 assert.equal(has(bare, 'refs/tags/n1') || has(bare, 'refs/tags/n3'), false);
466 clean(bare);
467 });
468 });
469}
Diagnostics8 git calls · 176 ms
CallStatusSizeTime0176 ms
discover200191 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=191 git.server.agent=git/github-9922ec520325-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=191 git.pkt.payload.max=36
ls-refs20012 KiB · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=11990 git.response.cache=HIT git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=152 git.pkt.data=151 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=11990 git.pkt.payload.max=122 git.ls_refs.count=151 git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 1200347 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=347 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=347 git.pkt.payload.max=247 git.sideband.band1.bytes=247 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=247 git.pack.trailer=4b72f39b5ea57c5ae3009f90b53e3a6a155093e7Open pack map
fetchtree:0 · deepen 102004.2 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=78 git.response.bytes=4347 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 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=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4347 git.pkt.payload.max=4247 git.sideband.band1.bytes=4247 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=10 git.pack.bytes=4247 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=a6caf8e129bea82c9bae4cbc7c130c9205add400 git.pack.full=10Open pack map
fetchcombine:blob:none+tree:2 · deepen 1200—78 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.cache=BYPASS git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 error.type=remote_error error=remote: filter 'combine' not supported
fetchtree:0200919 B · hit1 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=1 git.response.bytes=919 git.response.cache=HIT git.response.duration_ms=1 git.fetch.filter=tree:0 git.fetch.wants=800d30ba8923860bfc460ca884b7f9ba22083588 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=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=919 git.pkt.payload.max=892 git.sideband.band1.bytes=892 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=892 git.pack.trailer=5323b9266eea5ded637285d1c5320699f12be76eOpen pack map
fetchtree:02005.6 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=5724 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=58fabb6768b3f737ee9cd8bac647bdc27405fb4d 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=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=5724 git.pkt.payload.max=5697 git.sideband.band1.bytes=5697 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=5697 git.pack.trailer=be7e0453974a5fe832f9065a33bb7e3434c10e9bOpen pack map
fetch2008.3 KiB91 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=91 git.response.bytes=8522 git.response.cache=MISS git.response.duration_ms=91 git.fetch.wants=ed86f264b317df556edd2584cb05d1e6551fd8e7 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=5 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=8522 git.pkt.payload.max=8192 git.sideband.band1.bytes=8490 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://github.com/ivarvong/ply
- Ref
- refs/heads/main
- Commit
- 19912563f540228593df0c489082e5e2508e21e4
- cf-ray
- a5e2bfb39e5889da
- Request
- 2dab232d…
- Protocol
- v2 · sha1
- Agent
- git/github-9922ec520325-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format