gitoria
All repositories: gitoria
16.1 KB
// tests/pull-numbers.mjs — THE GATE OF PULL REQUEST NUMBERS (gitoria#40). Its own gitoria server and storage, the REAL git binary over HTTP:// numbers per repo (never reused, in commit-time order for the old ones), the changes syncPulls finds (opened, synchronize with forced,// closed, reopened, merged with mergeCommit), refs/pull/N/head fetchable and NOT pushable, the contract's pull object, wasHeadOf, "#N" on /pulls.// node tests/pull-numbers.mjs (GITORIA_PULLS_PORT default 8720)import { spawn, execFileSync, spawnSync } from 'node:child_process';import { request as httpRequest } from 'node:http';import { rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const PORT = Number(process.env.GITORIA_PULLS_PORT || 8720);const STORE = join(APP, '.scratch', 'pulls-store');const DB = join(STORE, 'db'), GIT = join(STORE, 'git'), WORK = join(STORE, 'work');const LOG = join(DB, 'pull-changes.log');const HOST = (slug) => `${slug}.gitoria.test`;let failures = 0, passes = 0;function check(label, ok, detail = '') { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + String(detail).slice(0, 400)}`); if (ok) passes++; else failures++; }const sleep = (ms) => new Promise(r => setTimeout(r, ms));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' };const BIN = join(APP, 'bin/hybriel');function raw(path, host) {return new Promise((res, rej) => {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 })); });r.on('error', rej); r.end();});}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]' };function git(cwd, args, extra = {}) {const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: { ...gitEnv, ...extra } });return { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() };}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; };const bare = (slug) => join(GIT, slug + '.git');const refOf = (slug, ref) => git(bare(slug), ['rev-parse', '--verify', '-q', ref]).out;const changes = () => existsSync(LOG) ? readFileSync(LOG, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)) : [];let seen = 0;const newChanges = () => { const all = changes(); const out = all.slice(seen); seen = all.length; return out; };let server = null, slog = '';const cleanup = () => { try { server && server.kill('SIGTERM'); } catch {} };process.on('exit', cleanup);try {if (!existsSync(BIN)) throw new Error('bin/hybriel missing');rmSync(STORE, { recursive: true, force: true }); mkdirSync(DB, { recursive: true }); mkdirSync(GIT, { recursive: true }); mkdirSync(WORK, { recursive: true });// ---- seed: a user, two repos, a token (cold compile: a minute)const seed = (slug) => spawnSync(BIN, ['tests/pulls-seed.hl', slug], { cwd: APP, env, encoding: 'utf8' });const s1 = seed('pr-test');const TOKEN = (/TOKEN (gtr_[0-9a-f]{40})/.exec(s1.stdout) || [])[1];check('seed made a token', !!TOKEN, s1.stdout + s1.stderr);if (!TOKEN) throw new Error('no seed');const s2 = seed('old-prs');check('seed made the second repo', s2.status === 0, s2.stdout + s2.stderr);// ---- old-prs: PRs that exist BEFORE gitoria numbers them (pushed to the bare repo directly), with distinct commit timesconst OLD = join(WORK, 'old');mkdirSync(OLD);must(OLD, ['init', '-q', '-b', 'main']);const at = (d) => ({ GIT_AUTHOR_DATE: d, GIT_COMMITTER_DATE: d });writeFileSync(join(OLD, 'a.txt'), 'a\n'); must(OLD, ['add', '.']); must(OLD, ['commit', '-q', '-m', 'base'], at('2026-01-01T10:00:00Z'));// the NEWER PR branch is created first: numbers must follow the commit time, not the creation ordermust(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'));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'));must(OLD, ['push', '-q', bare('old-prs'), 'main', 'newer', 'older']);// ---- start the serverserver = spawn(BIN, ['project.hl'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] });server.stdout.on('data', d => slog += d); server.stderr.on('data', d => slog += d);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); }const URL = (slug) => `http://app:${TOKEN}@${HOST(slug)}:${PORT}/${slug}.git`;const RES = (slug) => ['-c', `http.curloptResolve=${HOST(slug)}:${PORT}:127.0.0.1`];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 }; };// ---- backfill: /pulls numbers the old ones, oldest commit first, and logs no changeconst page = await raw('/pulls', HOST('old-prs'));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; };check('/pulls of old PRs: the older commit is #1', numOf(page.body, 'older one') === 1, String(numOf(page.body, 'older one')));check('/pulls of old PRs: the newer commit is #2', numOf(page.body, 'newer one') === 2, String(numOf(page.body, 'newer one')));check('backfill logs no change', changes().length === 0);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'));// ---- pr-test: first push (main only), then PRsconst W = join(WORK, 'w');mkdirSync(W);must(W, ['init', '-q', '-b', 'main']);writeFileSync(join(W, 'a.txt'), 'a\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'base']);let r = push(W, 'pr-test', ['main']);check('first push (no PR) works', r.ok, r.err);check('no PR → no change', newChanges().length === 0);must(W, ['checkout', '-q', '-b', 'f1']); writeFileSync(join(W, 'f1.txt'), '1\n'); must(W, ['add', '.']);must(W, ['commit', '-q', '-m', '|||PR first thing', '-m', 'Body line one.\n\nFixes other-proj#7 and bare #12.']);const f1a = must(W, ['rev-parse', 'HEAD']);r = push(W, 'pr-test', ['f1']);check('push of a |||PR branch works', r.ok, r.err);let ch = newChanges();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));check('sender is the pusher', ch.length === 1 && ch[0].sender && ch[0].sender.name === 'Gate Pusher', JSON.stringify(ch));check('refs/pull/1/head = the head when the change is logged', refOf('pr-test', 'refs/pull/1/head') === f1a);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']);const f2a = must(W, ['rev-parse', 'HEAD']);push(W, 'pr-test', ['f2']);ch = newChanges();check('second PR is #2', ch.length === 1 && ch[0].action === 'opened' && ch[0].number === 2, JSON.stringify(ch));// synchronize (new commit, not forced)must(W, ['checkout', '-q', 'f1']); writeFileSync(join(W, 'f1b.txt'), 'b\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', 'more']);const f1b = must(W, ['rev-parse', 'HEAD']);push(W, 'pr-test', ['f1']);ch = newChanges();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));check('ref follows the new head', refOf('pr-test', 'refs/pull/1/head') === f1b);// force push (amend the second commit)must(W, ['commit', '-q', '--amend', '-m', 'more, amended']);const f1c = must(W, ['rev-parse', 'HEAD']);r = push(W, 'pr-test', ['f1'], ['--force']);check('force push works', r.ok, r.err);ch = newChanges();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));// 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)const gc = git(bare('pr-test'), ['gc', '-q', '--prune=now']);check('git gc --prune=now ran', gc.ok, gc.err);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);check('refs/pull/1/heads/<sha> exist for every head', [f1a, f1b, f1c].every(h => refOf('pr-test', `refs/pull/1/heads/${h}`) === h));r = push(W, 'pr-test', [`main:refs/pull/1/heads/${'a'.repeat(40)}`]);check('a push to refs/pull/N/heads/* is refused too', !r.ok, r.err);// refs/pull/* cannot be pushed (create, update, delete), and the ref staysconst before1 = refOf('pr-test', 'refs/pull/1/head');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']]) {r = push(W, 'pr-test', [refspec]);check(`push refused: ${what} ${refspec}`, !r.ok && /refs\/pull|hidden|deny|refus|rejected/i.test(r.err), r.err);}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') === '');check('refused pushes made no change', newChanges().length === 0);// fetch of the head over HTTPS works, and clone does not make branches of itconst F = join(WORK, 'f'); mkdirSync(F); must(F, ['init', '-q']);r = git(F, [...RES('pr-test'), 'fetch', '-q', URL('pr-test'), 'refs/pull/1/head']);check('fetch refs/pull/1/head over HTTPS', r.ok && must(F, ['rev-parse', 'FETCH_HEAD']) === f1c, r.err);// close: delete the branch; reopen: push it again; the number staysr = push(W, 'pr-test', [':f2']);ch = newChanges();check('branch deleted → closed #2', ch.length === 1 && ch[0].action === 'closed' && ch[0].number === 2, JSON.stringify(ch));push(W, 'pr-test', ['f2']);ch = newChanges();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));// the |||PR commit gone from the branch (force-push of f2 to main's commit)push(W, 'pr-test', ['+main:f2']);ch = newChanges();check('|||PR commit gone from the branch → closed #2', ch.length === 1 && ch[0].action === 'closed' && ch[0].number === 2, JSON.stringify(ch));// merged: main takes f1 with a merge commitmust(W, ['checkout', '-q', 'main']); must(W, ['merge', '-q', '--no-ff', 'f1', '-m', 'merge f1']);const mc = must(W, ['rev-parse', 'HEAD']);push(W, 'pr-test', ['main']);ch = newChanges();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));push(W, 'pr-test', ['main']);check('merged is final: a second push changes nothing', newChanges().length === 0);// a new PR gets #3, never a reused numbermust(W, ['checkout', '-q', '-b', 'f3']); writeFileSync(join(W, 'f3.txt'), '3\n'); must(W, ['add', '.']); must(W, ['commit', '-q', '-m', '|||PR third']);const f3a = must(W, ['rev-parse', 'HEAD']);const t3 = push(W, 'pr-test', ['f3']);ch = newChanges();check('next PR is #3 (numbers are never reused)', ch.length === 1 && ch[0].action === 'opened' && ch[0].number === 3, JSON.stringify(ch));console.log(` (a push that opens a PR took ${t3.ms} ms)`);// old-prs: a live PR after the backfill is #3const O2 = join(WORK, 'o2'); must(WORK, ['clone', '-q', bare('old-prs'), O2]);must(O2, ['checkout', '-q', '-b', 'live', 'main']); writeFileSync(join(O2, 'l.txt'), 'l\n'); must(O2, ['add', '.']); must(O2, ['commit', '-q', '-m', '|||PR live']);push(O2, 'old-prs', ['live']);ch = newChanges();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));// ---- the page: "#N" on every row, no refs/pull anywhere as a branchconst pg = await raw('/pulls', HOST('pr-test'));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')}`);const code = await raw('/code', HOST('pr-test'));const br = await raw('/branch/f1', HOST('pr-test'));check('no refs/pull in the code and branch pages', !/refs\/pull|pull\/\d+\/head/.test(code.body + br.body + pg.body));check('the branch list has no pull entries', !/>\s*pull\/|href="[^"]*\/branch\/pull/.test(code.body));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'])));// ---- the contract's pull object + wasHeadOf (a second process on the same tables)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' });const pulls = (pr.stdout.match(/^PULL .*$/gm) || []).map(l => JSON.parse(l.slice(5)));const was = Object.fromEntries((pr.stdout.match(/^WAS .*$/gm) || []).map(l => { const p = l.split(' '); return [p[1], p[2]]; }));check('pullObject: 3 pulls and none for number 4', pulls.length === 4 && pulls[3] === null, pr.stdout + pr.stderr);const p1 = pulls[0] || {}, p3 = pulls[2] || {};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));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));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));check('pull #1 tickets: explicit project#n only (repo not connected)', JSON.stringify(p1.tickets) === JSON.stringify(['other-proj#7']), JSON.stringify(p1.tickets));check('pull #3 open, source f3, head', p3.state === 'open' && p3.source === 'f3' && p3.head === f3a && p3.title === 'third', JSON.stringify(p3));check('wasHeadOf: every head #1 had is true', was[`1:${f1a}`] === 'true' && was[`1:${f1b}`] === 'true' && was[`1:${f1c}`] === 'true', JSON.stringify(was));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));check('wasHeadOf: #2 knows its head', was[`2:${f2a}`] === 'true', JSON.stringify(was));} catch (e) {check('gate ran to the end', false, String(e && e.stack || e));} finally {cleanup();}if (failures) console.log('--- server log (tail) ---\n' + slog.split('\n').slice(-40).join('\n'));console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
Latest commits
- 7bcf7bc2Nest repo navigation media rules and document selector gapsmre
- 46a76272Reference release row styles from the Viewmre
- a383f428Tie README definition and path styles to its own Viewmre
- a90812ffConsolidate add-code styles under its existing View idmre
- 89107a3eDocument the index direct-child selector remaindermre
- 07403362Scope reply form layout through the component form rulemre
- 097c52baStyle the login error through its View idmre
- c6d9c86aOwn the not-found code rule in its componentmre
- 055424c2Record W61 replacement theme gates, sidebar repro and baselinemre
- 2ed09441Use layouts theme 17e0f03 for W61 compatibilitymre
- b8609a91Merge branch 'main' into w61-stylemre
- 4639caf7Report W61 theme startup blocker and day39 Style probemre
- 81f0a0bbREADME: two caches were restored by 90b4f72; log W62mre
- 4a3f557eImport layouts theme ebd00b6 for W61 (startup blocked)mre
- ab12a257Merge W62: #25 commit page measurements and proc repromre
- 41323e49gitoria#25: measure commit request costs and reproduce blocking process waitsmre
- 53ca42b2log: W60 merged, W61 W62 startedmre
- 80870a33mission W61: style passmre
- 560fd208Merge W60: helpers, bound forms, login in topics, two form fixes (gitoria#28 #32 #33)mre
- ac5ba6a4log: W60, #25 measuredmre