gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitfeeaa701feeaa701|||PR gates: explicit ports only, deploy.sh passes themmrefeeaa701/tests/pull-numbers.mjs

16.1 KB

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

Branches

Latest commits

  • feeaa701|||PR gates: explicit ports only, deploy.sh passes themmre
  • 6cc1f943Merge branch 'records-1112' into mainGitoria
  • 9448c438|||PR records: LOG, missions and reports since 11-09mre
  • 6dc08a8eMerge branch 'p51-public-pr-reads' into mainGitoria
  • 7b88cfe0Type publicReaderOfRequest parameters (L10)Gitoria
  • 2a4b3dc1|||PR Anonymous reads of public repos' pulls and statusesmre
  • 21b2c141Merge branch 's25-no-session-on-login-error' into mainGitoria
  • 698458e2|||PR No session for cookieless login errors: READMEmre
  • cce7b785|||PR No session for cookieless login errorsmre
  • 678d6303Merge branch 'v59' into mainGitoria
  • 5803cf4f|||PR vendor: Hybriel set-day59 and GC budget 32 MiBmre
  • 9eff6627Merge branch 'f2-api-bugs' into mainGitoria
  • 26117255|||PR apps API: review comments on files with spaces in their namemre
  • b8796cecMerge branch 'f1-broken-json' into mainGitoria
  • 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre
  • f7c6ca07Merge branch 'ident-chooser-selector' into mainGitoria
  • 691abb8e|||PR tests: find ident identity choice without the removed .choose classmre
  • 16a3530fMerge branch 'heap-revert' into mainGitoria
  • 220a80e0|||PR Remove temporary /__heap route and heap helper; logmre
  • 13f0c342Merge branch 'hl25-records' into mainGitoria