gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitfc36fa2efc36fa2elog: W51b pull source bugmrefc36fa2e/tests/pull-numbers.mjs

16.1 KB

  1. // tests/pull-numbers.mjs — THE GATE OF PULL REQUEST NUMBERS (gitoria#40). Its own gitoria server and storage, the REAL git binary over HTTP:
  2. // numbers per repo (never reused, in commit-time order for the old ones), the changes syncPulls finds (opened, synchronize with forced,
  3. // closed, reopened, merged with mergeCommit), refs/pull/N/head fetchable and NOT pushable, the contract's pull object, wasHeadOf, "#N" on /pulls.
  4. // node tests/pull-numbers.mjs (GITORIA_PULLS_PORT default 8720)
  5. import { spawn, execFileSync, spawnSync } from 'node:child_process';
  6. import { request as httpRequest } from 'node:http';
  7. import { rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
  8. import { dirname, join, resolve } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. const HERE = dirname(fileURLToPath(import.meta.url));
  11. const APP = resolve(HERE, '..');
  12. const PORT = Number(process.env.GITORIA_PULLS_PORT || 8720);
  13. const STORE = join(APP, '.scratch', 'pulls-store');
  14. const DB = join(STORE, 'db'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work');
  15. const LOG = join(DB, 'pull-changes.log');
  16. const HOST = (slug) => `${slug}.gitoria.test`;
  17. let failures = 0, passes = 0;
  18. function check(label, ok, detail = '') { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 400)}`); if (ok) passes++; else failures++; }
  19. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  20. const env = { ...process.env, GITORIA_STORAGE: DB, GITORIA_GIT: GIT, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: `http://gitoria.test:${PORT}`, GITORIA_TICKETS_URL: 'http://127.0.0.1:1' };
  21. const BIN = join(APP, 'bin/hybriel');
  22. function raw(path, host) {
  23. return new Promise((res, rej) => {
  24. const r = httpRequest({ host: '127.0.0.1', port: PORT, path, headers: { host } }, (x) => { let b = ''; x.setEncoding('utf8'); x.on('data', d => b += d); x.on('end', () => res({ status: x.statusCode, body: b })); });
  25. r.on('error', rej); r.end();
  26. });
  27. }
  28. const gitEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_AUTHOR_NAME: 'Dev', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Dev', GIT_COMMITTER_EMAIL: '[email protected]' };
  29. function git(cwd, args, extra = {}) {
  30. const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: { ...gitEnv, ...extra } });
  31. return { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() };
  32. }
  33. const must = (cwd, args, extra) => { const r = git(cwd, args, extra); if (!r.ok) throw new Error('git ' + args.join(' ') + ': ' + r.err); return r.out; };
  34. const bare = (slug) => join(GIT, slug + '.git');
  35. const refOf = (slug, ref) => git(bare(slug), ['rev-parse', '--verify', '-q', ref]).out;
  36. const changes = () => existsSync(LOG) ? readFileSync(LOG, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)) : [];
  37. let seen = 0;
  38. const newChanges = () => { const all = changes(); const out = all.slice(seen); seen = all.length; return out; };
  39. let server = null, slog = '';
  40. const cleanup = () => { try { server && server.kill('SIGTERM'); } catch {} };
  41. process.on('exit', cleanup);
  42. try {
  43. if (!existsSync(BIN)) throw new Error('bin/hybriel missing');
  44. rmSync(STORE, { recursive: true, force: true }); mkdirSync(DB, { recursive: true }); mkdirSync(GIT, { recursive: true }); mkdirSync(WORK, { recursive: true });
  45. // ---- seed: a user, two repos, a token (cold compile: a minute)
  46. const seed = (slug) => spawnSync(BIN, ['tests/pulls-seed.hl', slug], { cwd: APP, env, encoding: 'utf8' });
  47. const s1 = seed('pr-test');
  48. const TOKEN = (/TOKEN (gtr_[0-9a-f]{40})/.exec(s1.stdout) || [])[1];
  49. check('seed made a token', !!TOKEN, s1.stdout + s1.stderr);
  50. if (!TOKEN) throw new Error('no seed');
  51. const s2 = seed('old-prs');
  52. check('seed made the second repo', s2.status === 0, s2.stdout + s2.stderr);
  53. // ---- old-prs: PRs that exist BEFORE gitoria numbers them (pushed to the bare repo directly), with distinct commit times
  54. const OLD = join(WORK, 'old');
  55. mkdirSync(OLD);
  56. must(OLD, ['init', '-q', '-b', 'main']);
  57. const at = (d) => ({ GIT_AUTHOR_DATE: d, GIT_COMMITTER_DATE: d });
  58. writeFileSync(join(OLD, 'a.txt'), 'a\n'); must(OLD, ['add', '.']); must(OLD, ['commit', '-q', '-m', 'base'], at('2026-01-01T10:00:00Z'));
  59. // the NEWER PR branch is created first: numbers must follow the commit time, not the creation order
  60. must(OLD, ['checkout', '-q', '-b', 'newer', 'main']); writeFileSync(join(OLD, 'n.txt'), 'n\n'); must(OLD, ['add', '.']); must(OLD, ['commit', '-q', '-m', '|||PR newer one'], at('2026-03-01T10:00:00Z'));
  61. must(OLD, ['checkout', '-q', '-b', 'older', 'main']); writeFileSync(join(OLD, 'o.txt'), 'o\n'); must(OLD, ['add', '.']); must(OLD, ['commit', '-q', '-m', '|||PR older one'], at('2026-02-01T10:00:00Z'));
  62. must(OLD, ['push', '-q', bare('old-prs'), 'main', 'newer', 'older']);
  63. // ---- start the server
  64. server = spawn(BIN, ['project.hl'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] });
  65. server.stdout.on('data', d => slog += d); server.stderr.on('data', d => slog += d);
  66. for (let i = 0; i < 960; i++) { try { if ((await raw('/api/repos', 'gitoria.test')).status === 200) break; } catch {} await sleep(250); if (i === 959) throw new Error('server did not come up\n' + slog); }
  67. const URL = (slug) => `http://app:${TOKEN}@${HOST(slug)}:${PORT}/${slug}.git`;
  68. const RES = (slug) => ['-c', `http.curloptResolve=${HOST(slug)}:${PORT}:127.0.0.1`];
  69. const push = (cwd, slug, refs, extra = []) => { const t0 = Date.now(); const r = git(cwd, [...RES(slug), 'push', ...extra, URL(slug), ...refs]); return { ...r, ms: Date.now() - t0 }; };
  70. // ---- backfill: /pulls numbers the old ones, oldest commit first, and logs no change
  71. const page = await raw('/pulls', HOST('old-prs'));
  72. const numOf = (html, word) => { const m = new RegExp('class="number"[^>]*>#(\\d+)</span>[\\s\\S]{0,600}?' + word).exec(html); return m ? Number(m[1]) : null; };
  73. check('/pulls of old PRs: the older commit is #1', numOf(page.body, 'older one') === 1, String(numOf(page.body, 'older one')));
  74. check('/pulls of old PRs: the newer commit is #2', numOf(page.body, 'newer one') === 2, String(numOf(page.body, 'newer one')));
  75. check('backfill logs no change', changes().length === 0);
  76. check('backfill made refs/pull/1/head and /2/head', refOf('old-prs', 'refs/pull/1/head') === refOf('old-prs', 'refs/heads/older') && refOf('old-prs', 'refs/pull/2/head') === refOf('old-prs', 'refs/heads/newer'));
  77. // ---- pr-test: first push (main only), then PRs
  78. const W = join(WORK, 'w');
  79. mkdirSync(W);
  80. must(W, ['init', '-q', '-b', 'main']);
  81. writeFileSync(join(W, 'a.txt'), 'a\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'base']);
  82. let r = push(W, 'pr-test', ['main']);
  83. check('first push (no PR) works', r.ok, r.err);
  84. check('no PR → no change', newChanges().length === 0);
  85. must(W, ['checkout', '-q', '-b', 'f1']); writeFileSync(join(W, 'f1.txt'), '1\n'); must(W, ['add', '.']);
  86. must(W, ['commit', '-q', '-m', '|||PR first thing', '-m', 'Body line one.\n\nFixes other-proj#7 and bare #12.']);
  87. const f1a = must(W, ['rev-parse', 'HEAD']);
  88. r = push(W, 'pr-test', ['f1']);
  89. check('push of a |||PR branch works', r.ok, r.err);
  90. let ch = newChanges();
  91. check('opened #1', ch.length === 1 && ch[0].action === 'opened' && ch[0].number === 1 && ch[0].after === f1a && ch[0].before === null && ch[0].repoId, JSON.stringify(ch));
  92. check('sender is the pusher', ch.length === 1 && ch[0].sender && ch[0].sender.name === 'Gate Pusher', JSON.stringify(ch));
  93. check('refs/pull/1/head = the head when the change is logged', refOf('pr-test', 'refs/pull/1/head') === f1a);
  94. must(W, ['checkout', '-q', 'main']); must(W, ['checkout', '-q', '-b', 'f2']); writeFileSync(join(W, 'f2.txt'), '2\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR|main] second thing']);
  95. const f2a = must(W, ['rev-parse', 'HEAD']);
  96. push(W, 'pr-test', ['f2']);
  97. ch = newChanges();
  98. check('second PR is #2', ch.length === 1 && ch[0].action === 'opened' && ch[0].number === 2, JSON.stringify(ch));
  99. // synchronize (new commit, not forced)
  100. must(W, ['checkout', '-q', 'f1']); writeFileSync(join(W, 'f1b.txt'), 'b\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'more']);
  101. const f1b = must(W, ['rev-parse', 'HEAD']);
  102. push(W, 'pr-test', ['f1']);
  103. ch = newChanges();
  104. check('synchronize: before/after, forced false', ch.length === 1 && ch[0].action === 'synchronize' && ch[0].number === 1 && ch[0].before === f1a && ch[0].after === f1b && ch[0].forced === false, JSON.stringify(ch));
  105. check('ref follows the new head', refOf('pr-test', 'refs/pull/1/head') === f1b);
  106. // force push (amend the second commit)
  107. must(W, ['commit', '-q', '--amend', '-m', 'more, amended']);
  108. const f1c = must(W, ['rev-parse', 'HEAD']);
  109. r = push(W, 'pr-test', ['f1'], ['--force']);
  110. check('force push works', r.ok, r.err);
  111. ch = newChanges();
  112. check('synchronize forced true', ch.length === 1 && ch[0].action === 'synchronize' && ch[0].forced === true && ch[0].before === f1b && ch[0].after === f1c, JSON.stringify(ch));
  113. // every earlier head stays referenced (refs/pull/N/heads/<sha>): git gc --prune=now must not drop the heads f1a and f1b (both replaced, f1b by a force-push)
  114. const gc = git(bare('pr-test'), ['gc', '-q', '--prune=now']);
  115. check('git gc --prune=now ran', gc.ok, gc.err);
  116. check('after gc the replaced heads still resolve (f1a, f1b)', git(bare('pr-test'), ['cat-file', '-e', f1a + '^{commit}']).ok && git(bare('pr-test'), ['cat-file', '-e', f1b + '^{commit}']).ok);
  117. check('refs/pull/1/heads/<sha> exist for every head', [f1a, f1b, f1c].every(h => refOf('pr-test', `refs/pull/1/heads/${h}`) === h));
  118. r = push(W, 'pr-test', [`main:refs/pull/1/heads/${'a'.repeat(40)}`]);
  119. check('a push to refs/pull/N/heads/* is refused too', !r.ok, r.err);
  120. // refs/pull/* cannot be pushed (create, update, delete), and the ref stays
  121. const before1 = refOf('pr-test', 'refs/pull/1/head');
  122. for (const [what, refspec] of [['update', 'main:refs/pull/1/head'], ['create', 'main:refs/pull/99/head'], ['create (+force)', '+main:refs/pull/98/head'], ['delete', ':refs/pull/1/head']]) {
  123. r = push(W, 'pr-test', [refspec]);
  124. check(`push refused: ${what} ${refspec}`, !r.ok && /refs\/pull|hidden|deny|refus|rejected/i.test(r.err), r.err);
  125. }
  126. check('refs/pull/1/head unchanged after the attempts', refOf('pr-test', 'refs/pull/1/head') === before1 && refOf('pr-test', 'refs/pull/99/head') === '' && refOf('pr-test', 'refs/pull/98/head') === '');
  127. check('refused pushes made no change', newChanges().length === 0);
  128. // fetch of the head over HTTPS works, and clone does not make branches of it
  129. const F = join(WORK, 'f'); mkdirSync(F); must(F, ['init', '-q']);
  130. r = git(F, [...RES('pr-test'), 'fetch', '-q', URL('pr-test'), 'refs/pull/1/head']);
  131. check('fetch refs/pull/1/head over HTTPS', r.ok && must(F, ['rev-parse', 'FETCH_HEAD']) === f1c, r.err);
  132. // close: delete the branch; reopen: push it again; the number stays
  133. r = push(W, 'pr-test', [':f2']);
  134. ch = newChanges();
  135. check('branch deleted → closed #2', ch.length === 1 && ch[0].action === 'closed' && ch[0].number === 2, JSON.stringify(ch));
  136. push(W, 'pr-test', ['f2']);
  137. ch = newChanges();
  138. check('branch back → reopened #2 (same number)', ch.length === 1 && ch[0].action === 'reopened' && ch[0].number === 2 && ch[0].after === f2a, JSON.stringify(ch));
  139. // the |||PR commit gone from the branch (force-push of f2 to main's commit)
  140. push(W, 'pr-test', ['+main:f2']);
  141. ch = newChanges();
  142. check('|||PR commit gone from the branch → closed #2', ch.length === 1 && ch[0].action === 'closed' && ch[0].number === 2, JSON.stringify(ch));
  143. // merged: main takes f1 with a merge commit
  144. must(W, ['checkout', '-q', 'main']); must(W, ['merge', '-q', '--no-ff', 'f1', '-m', 'merge f1']);
  145. const mc = must(W, ['rev-parse', 'HEAD']);
  146. push(W, 'pr-test', ['main']);
  147. ch = newChanges();
  148. check('push into the target → merged #1 with mergeCommit', ch.length === 1 && ch[0].action === 'merged' && ch[0].number === 1 && ch[0].mergeCommit === mc, JSON.stringify(ch));
  149. push(W, 'pr-test', ['main']);
  150. check('merged is final: a second push changes nothing', newChanges().length === 0);
  151. // a new PR gets #3, never a reused number
  152. must(W, ['checkout', '-q', '-b', 'f3']); writeFileSync(join(W, 'f3.txt'), '3\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR third']);
  153. const f3a = must(W, ['rev-parse', 'HEAD']);
  154. const t3 = push(W, 'pr-test', ['f3']);
  155. ch = newChanges();
  156. check('next PR is #3 (numbers are never reused)', ch.length === 1 && ch[0].action === 'opened' && ch[0].number === 3, JSON.stringify(ch));
  157. console.log(` (a push that opens a PR took ${t3.ms} ms)`);
  158. // old-prs: a live PR after the backfill is #3
  159. const O2 = join(WORK, 'o2'); must(WORK, ['clone', '-q', bare('old-prs'), O2]);
  160. must(O2, ['checkout', '-q', '-b', 'live', 'main']); writeFileSync(join(O2, 'l.txt'), 'l\n'); must(O2, ['add', '.']); must(O2, ['commit', '-q', '-m', '|||PR live']);
  161. push(O2, 'old-prs', ['live']);
  162. ch = newChanges();
  163. check('old-prs: a new PR after the backfill is #3 and opened', ch.length === 1 && ch[0].number === 3 && ch[0].action === 'opened', JSON.stringify(ch));
  164. // ---- the page: "#N" on every row, no refs/pull anywhere as a branch
  165. const pg = await raw('/pulls', HOST('pr-test'));
  166. check('/pulls shows #1 (merged) and #3 next to their titles (a closed PR is no longer found in git: not listed)', numOf(pg.body, 'first thing') === 1 && numOf(pg.body, 'third') === 3, `${numOf(pg.body, 'first thing')} ${numOf(pg.body, 'third')}`);
  167. const code = await raw('/code', HOST('pr-test'));
  168. const br = await raw('/branch/f1', HOST('pr-test'));
  169. check('no refs/pull in the code and branch pages', !/refs\/pull|pull\/\d+\/head/.test(code.body + br.body + pg.body));
  170. check('the branch list has no pull entries', !/>\s*pull\/|href="[^"]*\/branch\/pull/.test(code.body));
  171. check('git branch -a of the bare repo has no pull ref', !/pull/.test(must(bare('pr-test'), ['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes'])));
  172. // ---- the contract's pull object + wasHeadOf (a second process on the same tables)
  173. const pr = spawnSync(BIN, ['tests/pulls-probe.hl', 'pr-test', '3', `1:${f1a}`, `1:${f1b}`, `1:${f1c}`, `1:${'0'.repeat(40)}`, `2:${f2a}`, `3:${f1a}`], { cwd: APP, env, encoding: 'utf8' });
  174. const pulls = (pr.stdout.match(/^PULL .*$/gm) || []).map(l => JSON.parse(l.slice(5)));
  175. const was = Object.fromEntries((pr.stdout.match(/^WAS .*$/gm) || []).map(l => { const p = l.split(' '); return [p[1], p[2]]; }));
  176. check('pullObject: 3 pulls and none for number 4', pulls.length === 4 && pulls[3] === null, pr.stdout + pr.stderr);
  177. const p1 = pulls[0] || {}, p3 = pulls[2] || {};
  178. check('pull #1 title/body/state', p1.number === 1 && p1.title === 'first thing' && /Body line one\./.test(p1.body) && p1.state === 'merged' && p1.draft === false, JSON.stringify(p1));
  179. check('pull #1 refs and shas', p1.source === 'f1' && p1.target === 'main' && p1.head === f1c && p1.ref === 'refs/pull/1/head' && p1.baseRef === 'refs/heads/main' && p1.base === mc && /^[0-9a-f]{40}$/.test(p1.mergeBase), JSON.stringify(p1));
  180. check('pull #1 author, url, times', p1.author && p1.author.name === 'Gate Pusher' && /^[0-9a-z]{12}$/.test(p1.author.id || '') && p1.url === `http://pr-test.gitoria.test:${PORT}/pulls/1` && /^\d{4}-\d\d-\d\dT/.test(p1.created) && /^\d{4}-\d\d-\d\dT/.test(p1.updated), JSON.stringify(p1));
  181. check('pull #1 tickets: explicit project#n only (repo not connected)', JSON.stringify(p1.tickets) === JSON.stringify(['other-proj#7']), JSON.stringify(p1.tickets));
  182. check('pull #3 open, source f3, head', p3.state === 'open' && p3.source === 'f3' && p3.head === f3a && p3.title === 'third', JSON.stringify(p3));
  183. check('wasHeadOf: every head #1 had is true', was[`1:${f1a}`] === 'true' && was[`1:${f1b}`] === 'true' && was[`1:${f1c}`] === 'true', JSON.stringify(was));
  184. check('wasHeadOf: a sha that never was one is false (also another PR\'s head)', was[`1:${'0'.repeat(40)}`] === 'false' && was[`3:${f1a}`] === 'false', JSON.stringify(was));
  185. check('wasHeadOf: #2 knows its head', was[`2:${f2a}`] === 'true', JSON.stringify(was));
  186. } catch (e) {
  187. check('gate ran to the end', false, String(e && e.stack || e));
  188. } finally {
  189. cleanup();
  190. }
  191. if (failures) console.log('--- server log (tail) ---\n' + slog.split('\n').slice(-40).join('\n'));
  192. console.log(`\n${passes} passed, ${failures} failed`);
  193. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • fc36fa2elog: W51b pull source bugmre
  • 56bc1220log: v1.5.1 livemre
  • 845fc0aareport: W51mre
  • 83127391fix: return v1.5.1 app and merge error detailsmre
  • b07d0e97log: W51 v1.5.1 startedmre
  • 0b417d06docs: apps-api v1.5 user tokens (#48, W49)mre
  • d046940alog: vinzenz contract note sentmre
  • db443456log: vinzenz note retry 2mre
  • 802f229alog: kunibert repo ping provenmre
  • 2d2eaa92log: Kunibert connected to kunibert repomre
  • 65d5f80alogmre
  • dab74b0dW49 report, logmre
  • fd4fc028Exercise member status reads with a populated check statemre
  • 536ca6f9Allow repository members to read pull workflow APIs with user tokensmre
  • 705dd834W49 missionmre
  • b554cd5flogmre
  • f4c9440ddeploy.sh: tar --hard-dereference for the live data backupmre
  • 1a687b15Merge branch 'w48-member-merge'mre
  • 166c775fW48 report, logmre
  • 1b4623f0Members merge pull requests: API route, button on /pulls and /pulls/N, one shared merge pathmre