import assert from 'node:assert/strict' import { execFileSync, spawnSync } from 'node:child_process' import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { test } from 'node:test' const SCRIPT = new URL('../scripts/check-sending-policy.mjs', import.meta.url) function config(value) { return `export const SENDING = ${JSON.stringify(value)}\n` } function runGate({ main, branch, baseRef = 'main' }) { const dir = mkdtempSync(join(tmpdir(), 'sending-gate-')) const git = (...args) => execFileSync('git', args, { cwd: dir, stdio: 'pipe' }) try { mkdirSync(join(dir, 'scripts')) mkdirSync(join(dir, 'src')) copyFileSync(SCRIPT, join(dir, 'scripts/check-sending-policy.mjs')) git('init', '-q', '-b', 'main') git('config', 'user.email', 'gate@example.com') git('config', 'user.name', 'gate') if (main !== undefined) writeFileSync(join(dir, 'src/config.js'), config(main)) git('add', '.') git('commit', '-q', '-m', 'main') git('switch', '-q', '-c', 'feature') writeFileSync(join(dir, 'src/config.js'), config(branch)) const result = spawnSync(process.execPath, ['scripts/check-sending-policy.mjs'], { cwd: dir, encoding: 'utf8', env: { ...process.env, SENDING_BASE_REF: baseRef }, }) return { status: result.status, output: result.stdout + result.stderr } } finally { rmSync(dir, { recursive: true, force: true }) } } test('sending gate fails a branch that turns sending on while main is barred', () => { const { status, output } = runGate({ main: 'barred', branch: 'allowed' }) assert.equal(status, 1, output) assert.match(output, /this branch turns sending on/) }) test('sending gate fails a branch that sets allowed when main has no config', () => { assert.equal(runGate({ main: undefined, branch: 'allowed' }).status, 1) }) test('sending gate passes a branch that inherits allowed from main', () => { const { status, output } = runGate({ main: 'allowed', branch: 'allowed' }) assert.equal(status, 0, output) }) test('sending gate passes barred branches, and a branch that bars sending again', () => { assert.equal(runGate({ main: 'barred', branch: 'barred' }).status, 0) assert.equal(runGate({ main: 'allowed', branch: 'barred' }).status, 0) }) test('sending gate fails closed when it cannot read the base ref', () => { const { status, output } = runGate({ main: 'allowed', branch: 'allowed', baseRef: 'origin/missing' }) assert.equal(status, 1, output) assert.match(output, /cannot read src\/config\.js at origin\/missing/) })