gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit6e03be0a6e03be0apull state: keep the resync marker until the sync ran (#56)mre6e03be0a/tests/member-merge.mjs

44.4 KB

  1. import { requiredPort, requiredPortRange } from './gate-ports.mjs';
  2. // tests/member-merge.mjs — GATE OF THE MEMBER MERGE (gitoria#48): a member of a repo (the people who may push) merges a pull request with a gtr_ user token
  3. // — POST {api}/pulls/N/merge — once the REQUIRED checks are success; the owner too; apps (gat_) and strangers never. Blocked (422) while a required status is
  4. // pending / failure, a stale head is 409, the pull_request `merged` event carries sender = the member, the Merge button shows for owner and member only.
  5. // Real HTTP, the real `git`, its own storage under .scratch/member-merge-store.
  6. // node tests/member-merge.mjs (GITORIA_MM_PORT required = gitoria, +1 event receiver, +4 ident)
  7. import { spawn, execFileSync } from 'node:child_process';
  8. import { request, createServer } from 'node:http';
  9. import { mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, utimesSync, renameSync } from 'node:fs';
  10. import { dirname, join, resolve } from 'node:path';
  11. import { fileURLToPath } from 'node:url';
  12. import { startIdent } from './identkit.mjs';
  13. import { launchBrowser } from './cdp.mjs';
  14. const HERE = dirname(fileURLToPath(import.meta.url));
  15. const APP = resolve(HERE, '..');
  16. const CHROME = requiredPortRange('GITORIA_GATE_CHROME');
  17. const PORT = requiredPort('GITORIA_MM_PORT'), RPORT = PORT + 1, IDENT_PORT = process.env.GITORIA_MM_IDENT_PORT ? requiredPort('GITORIA_MM_IDENT_PORT') : PORT + 4;
  18. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  19. const STORE = join(APP, '.scratch/member-merge-store');
  20. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  21. let passes = 0, failures = 0;
  22. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  23. const got = [];
  24. const receiver = createServer((req, res) => { const c = []; req.on('data', d => c.push(d)); req.on('end', () => { got.push({ path: req.url, headers: req.headers, body: Buffer.concat(c).toString('utf8') }); res.statusCode = 204; res.end(); }); });
  25. await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));
  26. function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  27. return new Promise((res, rej) => {
  28. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  29. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  30. const r = request({ host: '127.0.0.1', port: PORT, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('utf8') })); });
  31. r.on('error', rej); if (body !== null) r.write(body); r.end();
  32. });
  33. }
  34. const get = (path, o = {}) => raw('GET', path, o);
  35. const errOf = (r) => { try { return JSON.parse(r.body).error; } catch { return {}; } };
  36. let server = null, log = '';
  37. async function up() { for (let i = 0; i < 960; i++) { try { if ((await get('/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + log); }
  38. const stop = async () => { if (server) { const p = server; server = null; p.kill(); await new Promise(r => p.once('exit', r)); } };
  39. let ident;
  40. try {
  41. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  42. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  43. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  44. const BASE = `http://localhost:${PORT}`;
  45. const app = await ident.registerApp(alice, 'gitoria (member-merge gate)', [BASE]);
  46. const GIT = join(STORE, 'git');
  47. const env = { GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: GIT, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret };
  48. execFileSync(join(APP, 'bin/hybriel'), ['tests/pull-close-process.hl'], {cwd:APP,env:{...process.env,...env},stdio:['ignore','pipe','pipe']});
  49. const raceDir = join(STORE, 'race'), raceBin = join(STORE, 'race-bin');
  50. mkdirSync(raceDir); mkdirSync(raceBin);
  51. writeFileSync(join(raceBin, 'git'), `#!/bin/sh
  52. if [ "$4" = for-each-ref ] && [ "$5" = '--format=%(refname:short)%09%(objectname)' ] && [ -f "$W62_RACE_DIR/fail-scan" ]; then
  53. rm "$W62_RACE_DIR/fail-scan"
  54. exit 128
  55. fi
  56. if [ "$4" = merge-base ] && [ "$5" = --is-ancestor ] && [ "\${#7}" = 40 ] && [ -f "$W62_RACE_DIR/arm" ] && [ "$6" = "$(cat "$W62_RACE_DIR/arm")" ]; then
  57. if mv "$W62_RACE_DIR/arm" "$W62_RACE_DIR/paused" 2>/dev/null; then
  58. while [ ! -f "$W62_RACE_DIR/release" ]; do sleep 0.01; done
  59. fi
  60. fi
  61. exec /usr/bin/git "$@"
  62. `, {mode:0o700});
  63. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  64. env: { ...process.env, PATH: raceBin + ':' + process.env.PATH, W62_RACE_DIR: raceDir, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: BASE, GITORIA_SSH_SECRET: 'sshsecret-mm-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1', GITORIA_APP_HOSTS: `http://127.0.0.1:${RPORT}`, GITORIA_EVENTS_TICK: '0.3', ...env } });
  65. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  66. await up();
  67. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  68. const login = async (who) => { const ck = cookieOf(await get('/')); const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(who, app, BASE) + '&next=%2F', { cookie: ck }); return { cookie: cookieOf(cb) || ck }; };
  69. let n = 0;
  70. const face = async (who, event, payload) => { const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) }); let j = null; try { j = JSON.parse(r.body); } catch {} return j && j.value; };
  71. const A = await login(alice), B = await login(bob), C = await login(carol);
  72. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  73. const tA = (await face(A, 'gitoriaMakeToken', ['a'])).token, tB = (await face(B, 'gitoriaMakeToken', ['b'])).token, tC = (await face(C, 'gitoriaMakeToken', ['c'])).token;
  74. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  75. const genv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_AUTHOR_NAME: 'a', GIT_AUTHOR_EMAIL: 'a@a', GIT_COMMITTER_NAME: 'a', GIT_COMMITTER_EMAIL: 'a@a' };
  76. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  77. const bare = (...a) => execFileSync('git', a, { cwd: join(GIT, 'mm.git'), encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] }).trim();
  78. const push = (...refs) => { try { g('push', '-q', `http://a:${tA}@mm.localhost:${PORT}/mm.git`, ...refs); return true; } catch { return false; } };
  79. const sha = () => g('rev-parse', 'HEAD').trim();
  80. const mkPr = (branch, title) => { g('checkout', '-q', 'main'); g('checkout', '-q', '-b', branch); writeFileSync(join(W, branch + '.txt'), branch + '\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR ' + title); const s = sha(); push(branch); return s; };
  81. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');
  82. check('alice creates "mm", pushes main', !!(await face(A, 'gitoriaCreate', ['mm', 'm'])).repo && push('main'));
  83. const added = await face(A, 'gitoriaChangeMember', ['mm', 'Bob', true]);
  84. check('alice adds Bob as a member (Carol is not)', added && added.members && added.members.length === 1, J(added));
  85. const kApp = await face(A, 'gitoriaAppAdd', ['mm', 'Kunibert', `http://127.0.0.1:${RPORT}/a`]);
  86. const tApp = JSON.parse((await raw('POST', '/api/apps/token', { host: `mm.localhost:${PORT}`, headers: { authorization: 'Bearer ' + kApp.key } })).body).token;
  87. const idK = (kApp.rows.find(x => x.name === 'Kunibert') || {}).id;
  88. check('an app (Kunibert) is connected to mm and has a token', /^gak_/.test(kApp.key || '') && !!tApp && !!idK);
  89. const HOST = `mm.localhost:${PORT}`;
  90. const merge = (token, num, body = null) => raw('POST', `/api/pulls/${num}/merge`, { host: HOST, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body });
  91. const put = (sha_, state) => raw('PUT', '/api/statuses/' + sha_, { host: HOST, headers: { authorization: 'Bearer ' + tApp, 'content-type': 'application/json' }, body: J({ context: 'ci', state, title: 't', summary: '', url: null }) });
  92. const prNum = async (s) => { const l = JSON.parse((await raw('GET', '/api/pulls?state=all', { host: HOST, headers: { authorization: 'Bearer ' + tApp } })).body).pulls; const p = l.find(x => x.head === s || x.sha === s); return p ? p.number : null; };
  93. // ---- 1. nothing required yet: the owner merges (API), a member merges through the button's face
  94. const s1 = mkPr('f1', 'one'), s2 = mkPr('f2', 'two'), s3 = mkPr('f3', 'three'), s4 = mkPr('f4', 'four');
  95. const n1 = await prNum(s1), n2 = await prNum(s2), n3 = await prNum(s3), n4 = await prNum(s4);
  96. check('four PRs are numbered', [n1, n2, n3, n4].every(x => x != null) && new Set([n1, n2, n3, n4]).size === 4, J([n1, n2, n3, n4]));
  97. // W49: member reads share the app body shape; only apps can write or inspect deliveries.
  98. const api = (token, method, path, body = null) => raw(method, path, { host: HOST, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body: body == null ? null : J(body) });
  99. // W62: manual close is durable, independent of the branch fingerprint cache.
  100. const stateApi = (token, num, action) => api(token, 'POST', '/api/repos/mm/pulls/' + num + '/' + action);
  101. const sc = mkPr('manual-close', 'Close and reopen'), nc = await prNum(sc);
  102. const state = async () => JSON.parse((await api(tA, 'GET', '/api/pulls/' + nc)).body).state;
  103. for (const action of ['close', 'reopen']) {
  104. const appRefusal = await stateApi(tApp, nc, action);
  105. check('W62 app cannot ' + action, appRefusal.status === 403 && errOf(appRefusal).code === 'forbidden' && errOf(appRefusal).message === 'apps cannot ' + action + ' pull requests', appRefusal.body);
  106. check('W62 stranger cannot ' + action, (await stateApi(tC, nc, action)).status === 403);
  107. check('W62 anonymous cannot ' + action, (await stateApi(null, nc, action)).status === 401);
  108. check('W62 unknown pull ' + action, (await stateApi(tA, 999, action)).status === 404);
  109. check('W62 forged page face refused ' + action, !!(await face(C, 'gitoriaPrState', ['mm', '' + nc, action === 'close']))?.error);
  110. }
  111. const scanLog = join(env.GITORIA_STORAGE, 'pull-changes.log');
  112. const beforeScan = readFileSync(scanLog, 'utf8');
  113. const eventsBeforeScan = got.length;
  114. writeFileSync(join(raceDir,'fail-scan'),'fail');
  115. const failedScan = await raw('GET','/__git/pushed?user=' + JSON.parse((await api(tA,'GET','/api/pulls/'+nc)).body).author.id + '&slug=mm&phase=after', {headers:{'X-Gitoria-Secret':'sshsecret-mm-gate'}});
  116. check('W62 failed branch scan was injected and callback returned', failedScan.status === 200 && !existsSync(join(raceDir,'fail-scan')));
  117. check('W62 failed scan writes no pull changes and leaves PR open', readFileSync(scanLog,'utf8') === beforeScan && await state() === 'open');
  118. await sleep(500);
  119. check('W62 failed scan emits no closed event', !got.slice(eventsBeforeScan).some(x => { const e=JSON.parse(x.body); return e.event === 'pull_request' && e.action === 'closed'; }));
  120. const inspectOutput = execFileSync(join(APP,'bin/hybriel'), ['tests/pull-close-process.hl','mm',''+nc,'inspect'], {cwd:APP,env:{...process.env,...env},encoding:'utf8'});
  121. const record = JSON.parse(inspectOutput.split('\n').find(l => l.startsWith('ROW ')).slice(4));
  122. const claimDir = join(env.GITORIA_STORAGE,'pull-claims',record.id);
  123. mkdirSync(claimDir,{recursive:true}); writeFileSync(join(claimDir,'owner'),'gate-holder');
  124. check('W62 manual close refuses a live row claim', (await stateApi(tA,nc,'close')).status === 409 && await state() === 'open');
  125. const expired = new Date(Date.now()-120000); utimesSync(claimDir,expired,expired);
  126. check('W62 expired claim is replaced and released after close', (await stateApi(tA,nc,'close')).status === 200 && !existsSync(claimDir));
  127. check('W62 reopen releases its row claim', (await stateApi(tA,nc,'reopen')).status === 200 && !existsSync(claimDir));
  128. const closeAt = got.length;
  129. const closeOwner = await face(A, 'gitoriaPrState', ['mm', '' + nc, true]);
  130. check('W62 owner closes from page', closeOwner?.view?.pr.state === 'closed', J(closeOwner));
  131. check('W62 closed PR cannot merge', (await merge(tA, nc)).status === 409);
  132. const closedList = (await get('/pulls', {host: HOST, cookie: B.cookie})).body;
  133. check('W62 cached list shows closed and Reopen', closedList.includes('class="closed">closed') && closedList.includes('>Reopen</button>'));
  134. g('checkout', '-q', 'manual-close'); g('commit', '-q', '--allow-empty', '-m', 'push after manual close'); push('manual-close');
  135. check('W62 closed survives a new branch push', await state() === 'closed');
  136. const reopenedMember = await face(B, 'gitoriaPullState', ['mm', nc, false]);
  137. check('W62 member reopens using list face', reopenedMember?.ok === true && await state() === 'open', J(reopenedMember));
  138. check('W62 member closes with person API', (await stateApi(tB, nc, 'close')).status === 200 && await state() === 'closed');
  139. check('W62 duplicate close conflicts', (await stateApi(tA, nc, 'close')).status === 409);
  140. check('W62 owner reopens with person API', (await stateApi(tA, nc, 'reopen')).status === 200 && await state() === 'open');
  141. check('W62 duplicate reopen conflicts', (await stateApi(tA, nc, 'reopen')).status === 409);
  142. // Pause git after sync reads the record, then close in a second process with its own DB handle.
  143. g('checkout', '-q', 'manual-close'); g('commit', '-q', '--allow-empty', '-m', 'concurrent sync head');
  144. writeFileSync(join(raceDir, 'arm'), sc);
  145. const racingPush = spawn('git', ['push', '-q', `http://a:${tA}@mm.localhost:${PORT}/mm.git`, 'manual-close'], {cwd:W,env:genv,stdio:['ignore','pipe','pipe']});
  146. const racingDone = new Promise(resolve => racingPush.once('exit', code => resolve(code)));
  147. for (let i=0;i<500 && !existsSync(join(raceDir,'paused'));i++) await sleep(10);
  148. check('W62 concurrent push reached sync after its record read', existsSync(join(raceDir,'paused')));
  149. let concurrentClose;
  150. try {
  151. const output = execFileSync(join(APP,'bin/hybriel'), ['tests/pull-close-process.hl','mm',''+nc], {cwd:APP,env:{...process.env,...env},encoding:'utf8'});
  152. const saved = JSON.parse(output.split('\n').find(l => l.startsWith('CLOSE ')).slice(6));
  153. concurrentClose = {status:saved.ok ? 200 : 409};
  154. }
  155. finally { writeFileSync(join(raceDir,'release'),'release'); }
  156. check('W62 close succeeds while push sync is in flight', concurrentClose.status === 200);
  157. check('W62 concurrent push finishes and preserves manual close', await racingDone === 0 && await state() === 'closed');
  158. check('W62 concurrent close retains its manual mark (person can reopen)', (await stateApi(tA,nc,'reopen')).status === 200);
  159. const pushHeld = () => new Promise(resolve => {
  160. const child=spawn('git',['push','-q',`http://a:${tA}@mm.localhost:${PORT}/mm.git`,'manual-close'],{cwd:W,env:genv,stdio:['ignore','pipe','pipe']});
  161. child.once('exit',resolve);
  162. });
  163. const pendingDir = join(env.GITORIA_STORAGE,'pull-resync',record.rid);
  164. const storedPull = () => {
  165. const out=execFileSync(join(APP,'bin/hybriel'),['tests/pull-close-process.hl','mm',''+nc,'inspect'],{cwd:APP,env:{...process.env,...env},encoding:'utf8'});
  166. return JSON.parse(out.split('\n').find(l=>l.startsWith('ROW ')).slice(4));
  167. };
  168. for (const trigger of ['api','page','orphan']) {
  169. g('commit','-q','--allow-empty','-m','held claim '+trigger); const heldHead=sha();
  170. mkdirSync(claimDir); writeFileSync(join(claimDir,'owner'),'gate-held');
  171. const heldAt=got.length, started=Date.now();
  172. check('W62 held claim push succeeds '+trigger, await pushHeld() === 0);
  173. check('W62 sync retries then queues pending repo '+trigger, Date.now()-started >= 2900 && existsSync(pendingDir) && storedPull().head !== heldHead);
  174. rmSync(claimDir,{recursive:true});
  175. const orphanDir = pendingDir + '.crashed';
  176. if (trigger === 'orphan') {
  177. renameSync(pendingDir,orphanDir);
  178. await api(tA,'GET','/api/pulls/'+nc);
  179. check('W62 recent taken marker is not stolen',existsSync(orphanDir) && storedPull().head !== heldHead);
  180. const abandoned=new Date(Date.now()-180000);utimesSync(orphanDir,abandoned,abandoned);
  181. }
  182. if (trigger === 'page') await get('/code',{host:HOST,cookie:A.cookie});
  183. else await api(tA,'GET','/api/pulls/'+nc);
  184. if (trigger === 'orphan') check('W62 abandoned taken marker is removed after recovery',!existsSync(orphanDir));
  185. check('W62 '+trigger+' read resyncs record and consumes marker', storedPull().head === heldHead && !existsSync(pendingDir));
  186. for(let i=0;i<100 && !got.slice(heldAt).some(x=>JSON.parse(x.body).action==='synchronize' && JSON.parse(x.body).pull?.head===heldHead);i++) await sleep(100);
  187. check('W62 '+trigger+' recovery delivers synchronized event',got.slice(heldAt).some(x=>{const e=JSON.parse(x.body);return e.event==='pull_request' && e.action==='synchronize' && e.pull?.head===heldHead;}));
  188. }
  189. g('commit','-q','--allow-empty','-m','expired sync claim'); const staleHead=sha();
  190. mkdirSync(claimDir); writeFileSync(join(claimDir,'owner'),'expired-holder');
  191. const staleTime=new Date(Date.now()-120000);utimesSync(claimDir,staleTime,staleTime);
  192. check('W62 expired claim does not block push synchronization',await pushHeld() === 0 && storedPull().head === staleHead && !existsSync(claimDir));
  193. for (let i = 0; i < 100 && !got.slice(closeAt).some(x => x.body.includes('"reopened"')); i++) await sleep(100);
  194. const closeEvents = got.slice(closeAt).map(x => JSON.parse(x.body)).filter(x => x.event === 'pull_request' && x.pull?.number === nc);
  195. check('W62 closed and reopened events delivered with actor', closeEvents.some(x => x.action === 'closed' && x.sender?.name === 'Alice' && x.pull.state === 'closed') && closeEvents.some(x => x.action === 'reopened' && x.sender?.name === 'Bob' && x.pull.state === 'open'), J(closeEvents));
  196. if (process.env.W62_REAL_CDP) {
  197. process.env.HL_CDP_URL = process.env.W62_REAL_CDP;
  198. const before = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  199. mkdirSync(join(APP, '.scratch/w62'), {recursive: true});
  200. writeFileSync(join(APP, '.scratch/w62/before.json'), J(before));
  201. const browser = await launchBrowser({debugPortRange: CHROME}); let page;
  202. try {
  203. page = await browser.newPage();
  204. await page.send('Network.enable');
  205. // Own test host only; never touch another host's cookies.
  206. const cookieValue = A.cookie.slice(A.cookie.indexOf('=') + 1);
  207. await page.send('Network.setCookie', {name: 'gitoriasid', value: cookieValue, url: 'http://mm.localhost:' + PORT});
  208. for (const [width, height] of [[390,844], [800,1280], [1280,800], [1280,900]]) {
  209. await page.send('Emulation.setDeviceMetricsOverride', {width,height,deviceScaleFactor:1,mobile:width===390});
  210. await page.goto('http://mm.localhost:' + PORT + '/pulls/' + nc);
  211. await page.waitFor('!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector("#close-pull")', {timeout:30000});
  212. await page.click('#close-pull');
  213. await page.waitFor('document.querySelector("#pullstate").textContent === "closed"');
  214. check('W62 real Chrome closed ' + width, await page.text('#pullstate') === 'closed');
  215. page._loaded = false;
  216. await page.send('Page.reload');
  217. for (let i = 0; i < 600 && !page._loaded; i++) await sleep(25);
  218. await page.waitFor('!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector("#reopen-pull")', {timeout:30000});
  219. await page.box('#reopen-pull');
  220. writeFileSync(join(APP, '.scratch/w62/closed-' + width + 'x' + height + '.png'), Buffer.from((await page.send('Page.captureScreenshot', {format:'png'})).data,'base64'));
  221. await page.focus('#reopen-pull');
  222. await page.send('Input.dispatchKeyEvent', {type:'keyDown',key:'Enter',code:'Enter',windowsVirtualKeyCode:13,text:'\r',unmodifiedText:'\r'});
  223. await page.send('Input.dispatchKeyEvent', {type:'keyUp',key:'Enter',code:'Enter',windowsVirtualKeyCode:13});
  224. await page.waitFor('document.querySelector("#pullstate").textContent === "open"');
  225. await page.goto('http://mm.localhost:' + PORT + '/pulls');
  226. const rowButton = 'button[value="' + nc + '"]';
  227. await page.waitFor('!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector(' + J(rowButton) + ')', {timeout:30000});
  228. const closeSelector = rowButton + ':not(.nomerge)';
  229. await page.click(closeSelector);
  230. await page.waitFor('Array.from(document.querySelectorAll(' + J(rowButton) + ')).some(b => b.textContent === "Reopen" && getComputedStyle(b).display !== "none")');
  231. page._loaded = false;
  232. await page.send('Page.reload');
  233. for (let i = 0; i < 600 && !page._loaded; i++) await sleep(25);
  234. await page.waitForSelector('#pulllist');
  235. writeFileSync(join(APP, '.scratch/w62/list-' + width + 'x' + height + '.png'), Buffer.from((await page.send('Page.captureScreenshot', {format:'png'})).data,'base64'));
  236. await stateApi(tA, nc, 'reopen');
  237. }
  238. } catch(e) {
  239. console.log(page ? page.dumpConsole() : 'no page');
  240. if (page) {
  241. console.log('W62 browser error: ' + await page.text('#pullerror'));
  242. writeFileSync(join(APP, '.scratch/w62/failure.png'), Buffer.from((await page.send('Page.captureScreenshot',{format:'png'})).data,'base64'));
  243. }
  244. throw e;
  245. } finally {
  246. if (page) await page.close();
  247. browser.conn.close();
  248. const after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  249. writeFileSync(join(APP, '.scratch/w62/after.json'), J(after));
  250. check('W62 real Chrome own tab closed', J(after.map(t=>t.id).sort()) === J(before.map(t=>t.id).sort()));
  251. delete process.env.HL_CDP_URL;
  252. }
  253. }
  254. const review = await api(tApp, 'POST', `/api/pulls/${n3}/reviews`, { head: s3, verdict: 'comment', body: 'first review', comments: [{ path: 'f3.txt', line: 1, body: 'inline' }] });
  255. check('W49 app still posts a review with an inline thread', review.status === 201, review.body);
  256. const threadId = JSON.parse(review.body).threads[0].id;
  257. check('W49 app still posts a conversation comment', (await api(tApp, 'POST', `/api/pulls/${n3}/comments`, { body: 'conversation' })).status === 201);
  258. await put(s4, 'pending');
  259. const paths = ['/api/pulls?state=all', `/api/pulls/${n3}`, `/api/pulls/${n3}/reviews`, `/api/pulls/${n3}/threads`, `/api/pulls/${n3}/comments`, '/api/statuses/' + s4];
  260. for (const path of paths) {
  261. const a = await api(tApp, 'GET', path), b = await api(tB, 'GET', path), owner = await api(tA, 'GET', path);
  262. check('W49 member and owner read same app body: ' + path, a.status === 200 && b.status === 200 && owner.status === 200 && a.body === b.body && a.body === owner.body, [a.status, b.status, owner.status].join());
  263. const stranger = await api(tC, 'GET', path), anon = await api(null, 'GET', path), bad = await api('gtr_' + 'a'.repeat(40), 'GET', path);
  264. const anonOpen = path === `/api/pulls/${n3}` || path === '/api/statuses/' + s4;
  265. check('W49 stranger 404, no token and unknown user token 401 (#51: no header at all reads a public pull and statuses): ' + path, stranger.status === 404 && errOf(stranger).code === 'not_found' && (anonOpen ? anon.status === 200 && anon.body === owner.body : anon.status === 401) && bad.status === 401, [stranger.status, anon.status, bad.status].join());
  266. }
  267. // ---- gitoria#51: anonymous reads of public repos (no Authorization header at all), only GET pulls/N and GET statuses/<sha>
  268. const anonPull = await api(null, 'GET', `/api/pulls/${n3}`), anonSt = await api(null, 'GET', '/api/statuses/' + s4);
  269. check('#51 public: anonymous GET pulls/N → 200 with the pull object', anonPull.status === 200 && JSON.parse(anonPull.body).number === n3 && JSON.parse(anonPull.body).head === s3, anonPull.status + anonPull.body.slice(0, 200));
  270. check('#51 public: anonymous GET statuses/<sha> → 200 { statuses }', anonSt.status === 200 && Array.isArray(JSON.parse(anonSt.body).statuses) && JSON.parse(anonSt.body).statuses.length === 1, anonSt.status + anonSt.body.slice(0, 200));
  271. const anon404 = await api(null, 'GET', '/api/pulls/999'), anonSha = await api(null, 'GET', '/api/statuses/' + 'e'.repeat(40));
  272. check('#51 public: unknown PR and unknown sha → 404 not_found', anon404.status === 404 && errOf(anon404).code === 'not_found' && anonSha.status === 404 && errOf(anonSha).code === 'not_found', anon404.status + ' ' + anonSha.status);
  273. check('#51 public: the PR list, reviews, threads, comments stay 401 without a token', (await Promise.all(['/api/pulls', `/api/pulls/${n3}/reviews`, `/api/pulls/${n3}/threads`, `/api/pulls/${n3}/comments`].map(x => api(null, 'GET', x)))).every(r => r.status === 401));
  274. check('#51 public: an invalid gtr_ is 401, a non-member gtr_ is 404 still', (await api('gtr_' + 'a'.repeat(40), 'GET', `/api/pulls/${n3}`)).status === 401 && (await api(tC, 'GET', `/api/pulls/${n3}`)).status === 404);
  275. const missing = await raw('GET', `/api/pulls/${n3}`, { host: `nosuchrepo.localhost:${PORT}` });
  276. check('#51 a missing repo → 404 not_found', missing.status === 404 && errOf(missing).code === 'not_found', missing.status + missing.body);
  277. const goPriv = await face(A, 'gitoriaSetPrivate', ['mm', true]);
  278. check('#51 the owner makes mm private', !!(goPriv && goPriv.value ? goPriv.value.repo && goPriv.value.repo.isPrivate : goPriv && goPriv.repo && goPriv.repo.isPrivate), J(goPriv).slice(0, 200));
  279. const pPull = await api(null, 'GET', `/api/pulls/${n3}`), pSt = await api(null, 'GET', '/api/statuses/' + s4), pNo = await api(null, 'GET', '/api/pulls/999');
  280. check('#51 private: both anonymous reads → 404 not_found, the same body as a missing repo', pPull.status === 404 && pSt.status === 404 && pNo.status === 404 && pPull.body === missing.body && pSt.body === missing.body && pNo.body === missing.body, [pPull.status, pSt.status, pNo.status].join() + pPull.body);
  281. check('#51 private: the members still read with a token', (await api(tB, 'GET', `/api/pulls/${n3}`)).status === 200 && (await api(tA, 'GET', '/api/statuses/' + s4)).status === 200);
  282. await face(A, 'gitoriaSetPrivate', ['mm', false]);
  283. check('#51 public again: anonymous GET pulls/N → 200', (await api(null, 'GET', `/api/pulls/${n3}`)).status === 200);
  284. if (process.env.W49_REAL_CDP) {
  285. process.env.HL_CDP_URL = process.env.W49_REAL_CDP;
  286. const before = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  287. writeFileSync(join(APP, '.scratch/w49/chrome-before.json'), J(before));
  288. const browser = await launchBrowser({ debugPortRange: CHROME }); let page;
  289. try {
  290. page = await browser.newPage();
  291. await page.goto(`http://mm.localhost:${PORT}/pulls/${n3}`);
  292. for (const [width, height] of [[390, 844], [800, 1280], [1280, 800], [1280, 900]]) {
  293. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });
  294. for (const path of paths) {
  295. const got = await page.evaluate(`(async () => { const r = await fetch(${J(path)}, { headers: { authorization: ${J('Bearer ' + tB)} } }); return { status: r.status, body: await r.text() }; })()`);
  296. check(`W49 real Chrome ${width}x${height} member reads ${path}`, got.status === 200, got.status);
  297. }
  298. await page.send('Page.reload');
  299. await page.waitForSelector('#pullpage');
  300. const shot = await page.send('Page.captureScreenshot', { format: 'png' });
  301. writeFileSync(join(APP, `.scratch/w49/chrome-${width}x${height}.png`), Buffer.from(shot.data, 'base64'));
  302. }
  303. } finally {
  304. try { if (page) await page.close(); } finally { browser.conn.close(); }
  305. const after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  306. writeFileSync(join(APP, '.scratch/w49/chrome-after.json'), J(after));
  307. check('W49 real Chrome leaves only original page targets', J(after.map(t => t.id).sort()) === J(before.map(t => t.id).sort()));
  308. delete process.env.HL_CDP_URL;
  309. }
  310. }
  311. const message = 'this route needs an app token (gat_); user tokens (gtr_) can read pulls, reviews, threads, comments and statuses and merge with POST /pulls/N/merge';
  312. for (const [method, path] of [['POST', `/api/pulls/${n3}/reviews`], ['POST', `/api/pulls/${n3}/comments`], ['POST', `/api/pulls/${n3}/threads/${threadId}/replies`], ['POST', `/api/pulls/${n3}/threads/${threadId}/resolve`], ['PUT', '/api/statuses/' + s3], ['GET', '/api/deliveries'], ['POST', '/api/deliveries/unknown/redeliver'], ['POST', '/api/apps/token']]) {
  313. const r = await api(tB, method, path, {});
  314. check('W49 app-only explains gtr_: ' + method + ' ' + path, r.status === 403 && errOf(r).code === 'app_token_required' && errOf(r).message === message, r.status + r.body);
  315. }
  316. for (const [method, path] of [['POST', `/api/pulls/${n3}/reviews`], ['PUT', '/api/statuses/' + s3]]) {
  317. for (const token of [null, 'gtr_' + 'a'.repeat(40)]) {
  318. const r = await api(token, method, path, {});
  319. check('W51 missing or unknown user token stays 401: ' + method, r.status === 401 && errOf(r).code === 'unauthorized', r.status + r.body);
  320. }
  321. }
  322. check('W49 unknown app token retains old message', /missing, unknown or expired token/.test(errOf(await api('gat_unknown', 'GET', paths[0])).message || ''));
  323. const kSecond = await face(A, 'gitoriaAppAdd', ['mm', 'Second', `http://127.0.0.1:${RPORT}/b`]);
  324. const tSecond = JSON.parse((await api(kSecond.key, 'POST', '/api/apps/token')).body).token;
  325. const review2 = await api(tSecond, 'POST', `/api/pulls/${n3}/reviews`, { head: s3, verdict: 'comment', body: 'second review', comments: [{ path: 'f3.txt', line: 1, body: 'second inline' }] });
  326. check('W49 another app posts its review and thread', review2.status === 201);
  327. for (const kind of ['reviews', 'threads']) {
  328. const path = `/api/pulls/${n3}/${kind}`;
  329. const member = JSON.parse((await api(tB, 'GET', path)).body), appOne = JSON.parse((await api(tApp, 'GET', path)).body), appTwo = JSON.parse((await api(tSecond, 'GET', path)).body);
  330. check('W49 member sees both apps; each app retains own ' + kind, member[kind].length === 2 && appOne[kind].length === 1 && appTwo[kind].length === 1 && appOne[kind][0].id !== appTwo[kind][0].id);
  331. const first = JSON.parse((await api(tB, 'GET', path + '?limit=1')).body);
  332. const next = JSON.parse((await api(tB, 'GET', path + '?limit=1&cursor=' + encodeURIComponent(first.next))).body);
  333. check('W49 member pagination has distinct stable ids: ' + kind, first[kind].length === 1 && next[kind].length === 1 && first[kind][0].id !== next[kind][0].id);
  334. }
  335. const m1 = await merge(tA, n1);
  336. const j1 = (() => { try { return JSON.parse(m1.body); } catch { return {}; } })();
  337. check('the OWNER merges PR 1 with her gtr_ token: 200 { merged, mergeCommit, pull }', m1.status === 200 && j1.merged === true && /^[0-9a-f]{40}$/.test(j1.mergeCommit || '') && j1.pull && j1.pull.number === n1 && j1.pull.state === 'merged', m1.status + m1.body.slice(0, 300));
  338. check('PR 1: mergeCommit is the tip of main, author = her display name', j1.mergeCommit === bare('rev-parse', 'refs/heads/main') && bare('log', '-1', '--format=%an', 'main') === 'Alice', bare('log', '-1', '--format=%an', 'main'));
  339. const btn = await face(B, 'gitoriaMergePull', ['mm', s2]);
  340. check('the MEMBER merges PR 2 with the button (server face)', btn && !btn.error && btn.result, J(btn).slice(0, 200));
  341. check('PR 2 is merged; author of the merge commit = Bob', bare('log', '-1', '--format=%an', 'main') === 'Bob', '');
  342. const strangerFace = await face(C, 'gitoriaMergePull', ['mm', s3]);
  343. check('the button\'s face refuses a stranger and a signed-out caller', strangerFace && /only the owner and the members/.test(strangerFace.error || '') && !!((await face(null, 'gitoriaMergePull', ['mm', s3])) || {}).error);
  344. // ---- 2. required check
  345. const rq = await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci']);
  346. check('the owner requires Kunibert · ci', rq && rq.rows && rq.rows.length === 1, J(rq));
  347. const before = bare('rev-parse', 'refs/heads/main');
  348. const checkDetails = (r, state) => J(errOf(r).details) === J([{ app: { id: idK, name: 'Kunibert' }, context: 'ci', state }]);
  349. const r0 = await merge(tB, n3);
  350. check('member, status not set → 422 checks_failed naming app and ci', r0.status === 422 && errOf(r0).code === 'checks_failed' && checkDetails(r0, 'missing') && /ci \(not set\)/.test(errOf(r0).message || ''), r0.status + r0.body.slice(0, 200));
  351. await put(s3, 'pending');
  352. const r1 = await merge(tB, n3);
  353. check('member, status pending → 422, main unchanged', r1.status === 422 && errOf(r1).code === 'checks_failed' && checkDetails(r1, 'pending') && /ci \(pending\)/.test(errOf(r1).message || '') && bare('rev-parse', 'refs/heads/main') === before, r1.status + r1.body.slice(0, 200));
  354. await put(s3, 'failure');
  355. const r2 = await merge(tB, n3);
  356. check('member, status failure → 422, main unchanged', r2.status === 422 && errOf(r2).code === 'checks_failed' && checkDetails(r2, 'failure') && /ci \(failure\)/.test(errOf(r2).message || '') && bare('rev-parse', 'refs/heads/main') === before, r2.status + r2.body.slice(0, 200));
  357. const rOwn = await merge(tA, n3);
  358. check('the owner is held by the same required check (422)', rOwn.status === 422 && errOf(rOwn).code === 'checks_failed', rOwn.status);
  359. // ---- 3. who may not
  360. await put(s3, 'success');
  361. const rApp = await merge(tApp, n3);
  362. check('an app token (gat_) → 403 forbidden "apps cannot merge", even with the status green', rApp.status === 403 && errOf(rApp).code === 'forbidden' && errOf(rApp).message === 'apps cannot merge', rApp.status + rApp.body);
  363. const rC = await merge(tC, n3);
  364. check('a signed-in non-member (gtr_) → 403', rC.status === 403 && errOf(rC).code === 'forbidden', rC.status + rC.body);
  365. const rNo = await merge(null, n3), rBad = await merge('gtr_' + 'a'.repeat(40), n3), rJunk = await merge('nonsense', n3);
  366. check('no token / an unknown gtr_ / junk → 401', rNo.status === 401 && rBad.status === 401 && rJunk.status === 401, [rNo.status, rBad.status, rJunk.status].join());
  367. check('GET on the merge route → 405', (await raw('GET', `/api/pulls/${n3}/merge`, { host: HOST, headers: { authorization: 'Bearer ' + tB } })).status === 405);
  368. const r404 = await merge(tB, 999);
  369. check('unknown PR → 404 not_found', r404.status === 404 && errOf(r404).code === 'not_found', r404.status);
  370. check('PR 3 still open after all refusals', bare('rev-parse', 'refs/heads/main') === before);
  371. // ---- 4. the button: visible for owner + member, hidden for others
  372. const listBtn = async (who) => { const b = (await get('/pulls', { host: HOST, cookie: who && who.cookie })).body; return (b.match(/<button class="([^"]*)" type="button" value="[0-9a-f]{40}">Merge/g) || []).map(x => x.match(/class="([^"]*)"/)[1]); };
  373. const pageBtn = async (who, num) => { const b = (await get('/pulls/' + num, { host: HOST, cookie: who && who.cookie })).body; return (b.match(/<button id="mergepull" class="([^"]*)"/) || [])[1]; };
  374. const lb = await listBtn(B), lc = await listBtn(C), ln = await listBtn(null), la = await listBtn(A);
  375. check('/pulls: Bob (member) and Alice see a visible Merge button on the green PR (quiet mergepr)', lb.includes('quiet mergepr') && la.includes('quiet mergepr'), J([lb, la]));
  376. check('/pulls: Carol and the signed-out viewer see no visible Merge button', !lc.includes('quiet mergepr') && !ln.includes('quiet mergepr'), J([lc, ln]));
  377. const pb = await pageBtn(B, n3), pa = await pageBtn(A, n3), pc = await pageBtn(C, n3), pn = await pageBtn(null, n3);
  378. check('/pulls/N: Bob and Alice get the Merge button (mergepr), Carol and signed-out get nomerge', pb === 'mergepr' && pa === 'mergepr' && pc === 'nomerge' && pn === 'nomerge', J([pb, pa, pc, pn]));
  379. const pageFace = await face(C, 'gitoriaPrMerge', ['mm', '' + n3]);
  380. check('the PR page\'s merge face refuses a stranger', pageFace && /only the owner and the members/.test(pageFace.error || ''), J(pageFace));
  381. // ---- 5. stale head, then the member merges (event with sender = Bob)
  382. const stale = await merge(tB, n3, J({ head: 'f'.repeat(40) }));
  383. check('a head that is not the current head → 409, nothing merged', stale.status === 409 && errOf(stale).code === 'conflict' && errOf(stale).details?.reason === 'head_mismatch' && /head/.test(errOf(stale).message || '') && bare('rev-parse', 'refs/heads/main') === before, stale.status + stale.body.slice(0, 200));
  384. check('a malformed head → 422', (await merge(tB, n3, J({ head: 'abc' }))).status === 422);
  385. check('a body that is not JSON → 400', (await merge(tB, n3, 'nope')).status === 400);
  386. const k = got.length;
  387. const ok = await merge(tB, n3, J({ head: s3 }));
  388. const jo = (() => { try { return JSON.parse(ok.body); } catch { return {}; } })();
  389. check('the MEMBER merges PR 3 (status success, the right head): 200 { merged, mergeCommit, pull }', ok.status === 200 && jo.merged === true && jo.mergeCommit === bare('rev-parse', 'refs/heads/main') && jo.pull.state === 'merged' && jo.pull.number === n3, ok.status + ok.body.slice(0, 300));
  390. check('the merge commit author = Bob', bare('log', '-1', '--format=%an', 'main') === 'Bob');
  391. for (let i = 0; i < 100 && !got.slice(k).some(x => x.body.includes('"merged"')); i++) await sleep(100);
  392. const ev = got.slice(k).map(x => { try { return JSON.parse(x.body); } catch { return {}; } }).find(x => x.event === 'pull_request' && x.action === 'merged' && x.pull && x.pull.number === n3);
  393. check('the pull_request merged event reached the app: sender = Bob, mergeCommit = the new tip', ev && ev.sender && ev.sender.name === 'Bob' && ev.mergeCommit === jo.mergeCommit, J(ev).slice(0, 300));
  394. const again = await merge(tB, n3);
  395. check('merging it again → 409 already merged', again.status === 409 && errOf(again).code === 'conflict' && errOf(again).details?.reason === 'already_merged' && /already merged/.test(errOf(again).message || ''), again.status + again.body.slice(0, 200));
  396. check('the stored PR reads as merged with GET /api/pulls/N', JSON.parse((await raw('GET', '/api/pulls/' + n3, { host: HOST, headers: { authorization: 'Bearer ' + tApp } })).body).state === 'merged');
  397. // the PR page's own Merge button (its face) merges for the owner and answers the page read again
  398. await put(s4, 'success');
  399. const pm = await face(A, 'gitoriaPrMerge', ['mm', '' + n4]);
  400. check('the PR page\'s Merge face merges PR 4 for the owner: the view says merged, the button hides', pm && pm.view && pm.view.pr.state === 'merged' && pm.view.mergeClass === 'nomerge' && bare('merge-base', '--is-ancestor', s4, 'main') === '', J(pm).slice(0, 200));
  401. // W51b: a containing branch belongs to more than one marker; never deduplicate by branch.
  402. const refreshMain = () => { g('fetch', '-q', `http://a:${tA}@mm.localhost:${PORT}/mm.git`, 'main'); g('checkout', '-q', 'main'); g('reset', '-q', '--hard', 'FETCH_HEAD'); };
  403. const pullRows = async () => ((await get('/pulls', { host: HOST, cookie: B.cookie })).body.match(/<li>[\s\S]*?<\/li>/g) || []);
  404. const rowFor = (rows, number) => rows.find(row => row.includes('href="/pulls/' + number + '"')) || '';
  405. refreshMain();
  406. const shaA = mkPr('a', 'W51b A'), numA = await prNum(shaA);
  407. await put(shaA, 'success');
  408. check('W51b PR A on a merges', (await merge(tB, numA)).status === 200);
  409. refreshMain();
  410. const shaB = mkPr('z', 'W51b B'), numB = await prNum(shaB);
  411. g('branch', '0-merged-descendant', 'z'); push('0-merged-descendant');
  412. let rows = await pullRows();
  413. check('W51b merged A remains listed with stored source a after B branches from main', /class="merged">merged/.test(rowFor(rows, numA)) && /class="source" href="\/branch\/a">a</.test(rowFor(rows, numA)), rowFor(rows, numA));
  414. check('W51b B keeps source z although an alphabetically earlier alias contains it', /class="source" href="\/branch\/z">z</.test(rowFor(rows, numB)), rowFor(rows, numB));
  415. const mergedA = await merge(tB, numA);
  416. check('W51b merging A again returns 409 conflict already_merged after B', mergedA.status === 409 && errOf(mergedA).code === 'conflict' && errOf(mergedA).details?.reason === 'already_merged', mergedA.status + mergedA.body);
  417. const shaC = mkPr('c', 'W51b C'), numC = await prNum(shaC);
  418. g('commit', '-q', '--allow-empty', '-m', 'C head after its marker'); const headC = sha(); push('c');
  419. g('checkout', '-q', '-b', '0-open-descendant'); writeFileSync(join(W, 'later.txt'), 'later\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR W51b D');
  420. const shaD = sha(); push('0-open-descendant'); const numD = await prNum(shaD);
  421. await put(headC, 'success');
  422. rows = await pullRows();
  423. check('W51b open C remains listed and mergeable with stored source c', /class="open">open/.test(rowFor(rows, numC)) && /class="source" href="\/branch\/c">c</.test(rowFor(rows, numC)) && rowFor(rows, numC).includes('class="quiet mergepr"'), rowFor(rows, numC));
  424. const cObject = JSON.parse((await api(tB, 'GET', '/api/pulls/' + numC)).body);
  425. check('W51b GET agrees on C source and updated head despite the later containing branch', cObject.source === 'c' && cObject.head === headC && cObject.state === 'open', J(cObject));
  426. const cMerge = await face(B, 'gitoriaMergePull', ['mm', shaC]);
  427. check('W51b C merges through the list button face using only its own head', cMerge && !cMerge.error && bare('merge-base', '--is-ancestor', headC, 'main') === '' && bare('rev-parse', 'main^2') === headC, J(cMerge).slice(0, 200));
  428. const dObject = JSON.parse((await api(tB, 'GET', '/api/pulls/' + numD)).body);
  429. check('W51b later PR D remains open after C merges', dObject.state === 'open' && dObject.head === shaD, J(dObject));
  430. // a member who is removed can merge no more
  431. check('W62 close before deleting its source', (await stateApi(tA, nc, 'close')).status === 200);
  432. check('W62 source deletion succeeds', push(':manual-close'));
  433. check('W62 reopening a missing branch resumes sync and closes it again', (await stateApi(tA, nc, 'reopen')).status === 200 && await state() === 'closed');
  434. check('W62 restored source uses automatic reopen after mark is cleared', push('manual-close') && await state() === 'open');
  435. const s5 = mkPr('f5', 'five'), n5 = await prNum(s5);
  436. await put(s5, 'success');
  437. await face(A, 'gitoriaChangeMember', ['mm', 'Bob', false]);
  438. check('Bob removed → his token no longer merges (403)', (await merge(tB, n5)).status === 403);
  439. check('W62 removed member cannot close', (await stateApi(tB, n5, 'close')).status === 403);
  440. for (const path of paths) check('W49 removed member loses read: ' + path, (await api(tB, 'GET', path)).status === 404);
  441. const pbGone = await pageBtn(B, n5);
  442. check('and his Merge button is gone', pbGone === 'nomerge', pbGone);
  443. // The merged record must answer even after git can no longer place its marker in the branch list.
  444. for (const branch of bare('for-each-ref', '--contains', shaA, '--format=%(refname)', 'refs/heads').split('\n').filter(Boolean)) bare('update-ref', '-d', branch);
  445. for (const action of ['close', 'reopen']) {
  446. const r = await stateApi(tA, numA, action);
  447. check('W62 merged cannot ' + action, r.status === 409 && errOf(r).details?.reason === 'already_merged', r.body);
  448. }
  449. // Delete every remaining branch while a manually closed PR still has refs/pull history.
  450. check('W62 close before removing every branch', (await stateApi(tA,nc,'close')).status === 200);
  451. for (const branch of bare('for-each-ref','--format=%(refname)','refs/heads').split('\n').filter(Boolean)) bare('update-ref','-d',branch);
  452. const emptyReopen = await stateApi(tA,nc,'reopen');
  453. check('W62 no branches: reopen ends closed again', emptyReopen.status === 200 && JSON.parse(emptyReopen.body).pull.state === 'closed', emptyReopen.body);
  454. const archivedA = await merge(tA, numA);
  455. check('W51b merged record returns already_merged even when no branch contains its marker', archivedA.status === 409 && errOf(archivedA).code === 'conflict' && errOf(archivedA).details?.reason === 'already_merged', archivedA.status + archivedA.body);
  456. } catch (e) {
  457. check('the gate ran without an exception', false, String(e && e.stack || e));
  458. } finally {
  459. await stop().catch(() => {});
  460. try { receiver.close(); } catch {}
  461. try { ident && ident.stop && await ident.stop(); } catch {}
  462. console.log(`\n${passes} passed, ${failures} failed`);
  463. process.exit(failures ? 1 : 0);
  464. }

Branches

Latest commits

  • 6e03be0apull state: keep the resync marker until the sync ran (#56)mre
  • 93bdd26cpull state: wait for a claimed row, resync when it stays busy (#56)mre
  • e53d284bpull state: stop on a failed branch scan, claim the row on writes (#56)mre
  • d8608224close and reopen: keep a manual close against sync (#56)mre
  • ffb60746|||PR close and reopen pull requests (#56)mre
  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
  • 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria