Files
vac-optimizer/scripts/ci-image.test.mjs
T
nessarandClaude Opus 5.5 40ee34ebd1
CI / publish (pull_request) Skipped
CI / policy (pull_request) Successful in 12s
CI / build (pull_request) Successful in 32s
CI / validate (pull_request) Successful in 40s
CI / benchmark (pull_request) Successful in 1m17s
CI / test (pull_request) Successful in 3m15s
CI / required (pull_request) Successful in 3s
ci: replace GitFlow with a single main branch, tag releases and Komodo deployment
PRs into main run the commit check (only the PR's own commits, no merge
commits), lint, format, type checks, tests, the benchmark and the build,
gated by `required`. Editing a PR no longer reruns CI. A push to main
builds one image, publishes it as sha-<commit> and beta, and redeploys the
Komodo beta stack; a vX.Y.Z tag promotes that image to vX.Y.Z and latest
and redeploys production. The deploy goes through the Komodo API and waits
for the update, so a failed deployment fails the run.

Removes the security scans, PR and branch-* images, the release/hotfix
rules and the merge-message template. compose.prod.yml now pulls the
registry image.

Closes #391

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:45:51 +01:00

178 lines
6.3 KiB
JavaScript

import assert from 'node:assert/strict';
import { execFileSync, spawn } from 'node:child_process';
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
const directory = mkdtempSync(join(tmpdir(), 'ci-image-'));
const script = fileURLToPath(new URL('./ci-image.mjs', import.meta.url));
const git = (...args) => execFileSync('git', args, { cwd: directory, encoding: 'utf8' }).trim();
const image = 'gitea.nessar.fr/nessar/vac-optimizer';
const commandsPath = join(directory, 'docker-commands.jsonl');
const bin = join(directory, 'bin');
// Fake Komodo: records each API call, reports an update in progress, then its result.
let komodoCalls = [];
let komodoAnswer = 'success';
const komodo = createServer((request, response) => {
let body = '';
request.on('data', (chunk) => (body += chunk));
request.on('end', () => {
const { type, params } = JSON.parse(body);
komodoCalls.push({
path: request.url,
key: request.headers['x-api-key'],
secret: request.headers['x-api-secret'],
type,
params,
});
const update =
type === 'DeployStack'
? { _id: { $oid: 'update-1' }, status: 'InProgress', success: false }
: {
_id: { $oid: 'update-1' },
status: 'Complete',
success: komodoAnswer === 'success',
};
response.statusCode = komodoAnswer === 'refused' ? 401 : 200;
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(update));
});
});
await new Promise((resolve) => komodo.listen(0, '127.0.0.1', resolve));
const run = async (variables = {}, expected = 0) => {
const commit = git('rev-parse', 'HEAD');
const eventName = variables.eventName ?? 'push';
const ref = variables.tag
? `refs/tags/${variables.tag}`
: eventName === 'pull_request'
? 'refs/pull/42/head'
: `refs/heads/${variables.branch ?? 'main'}`;
const event = { ref };
if (eventName === 'pull_request') event.pull_request = { head: { sha: commit } };
writeFileSync(join(directory, 'event.json'), JSON.stringify(event));
writeFileSync(commandsPath, '');
komodoCalls = [];
komodoAnswer = variables.komodo ?? 'success';
const child = spawn(process.execPath, [script], {
cwd: directory,
env: {
PATH: `${bin}:${process.env.PATH}`,
GITHUB_EVENT_NAME: eventName,
GITHUB_EVENT_PATH: join(directory, 'event.json'),
GITHUB_SHA: commit,
GITHUB_REF: ref,
GITHUB_REPOSITORY: 'nessar/vac-optimizer',
GITHUB_SERVER_URL: 'https://gitea.nessar.fr',
REGISTRY_USERNAME: 'publisher',
REGISTRY_PASSWORD: variables.registryPassword ?? 'test-token',
KOMODO_URL: `http://127.0.0.1:${komodo.address().port}/`,
KOMODO_API_KEY: 'komodo-key',
KOMODO_API_SECRET: variables.komodoSecret ?? 'komodo-secret',
KOMODO_BETA_STACK: 'beta-stack',
KOMODO_PRODUCTION_STACK: 'production-stack',
DOCKER_COMMANDS: commandsPath,
MISSING_IMAGE: variables.missingImage ? 'true' : '',
},
});
let output = '';
child.stdout.on('data', (chunk) => (output += chunk));
child.stderr.on('data', (chunk) => (output += chunk));
const status = await new Promise((resolve) => child.on('close', resolve));
assert.equal(status, expected, output);
const docker = readFileSync(commandsPath, 'utf8').trim().split('\n').filter(Boolean);
return {
docker: docker.map(JSON.parse).map(({ args }) => args.join(' ')),
komodo: komodoCalls,
};
};
const deployed = (stack) => [
{
path: '/execute',
key: 'komodo-key',
secret: 'komodo-secret',
type: 'DeployStack',
params: { stack },
},
{
path: '/read',
key: 'komodo-key',
secret: 'komodo-secret',
type: 'GetUpdate',
params: { id: 'update-1' },
},
];
const nothing = { docker: [], komodo: [] };
const login = 'login gitea.nessar.fr --username publisher --password-stdin';
try {
git('init', '--initial-branch=main');
git('config', 'user.name', 'CI image test');
git('config', 'user.email', 'ci-image@example.invalid');
git('remote', 'add', 'origin', directory);
writeFileSync(join(directory, 'package.json'), '{"version":"1.5.0"}\n');
git('add', 'package.json');
git('commit', '-m', 'chore: initial release');
mkdirSync(bin);
const docker = join(bin, 'docker');
writeFileSync(
docker,
`#!/usr/bin/env bun
import { appendFileSync, readFileSync } from 'node:fs';
const args = process.argv.slice(2);
const input = args[0] === 'login' ? readFileSync(0, 'utf8') : '';
appendFileSync(process.env.DOCKER_COMMANDS, JSON.stringify({ args, input }) + '\\n');
if (args[0] === 'login' && input !== 'test-token') process.exit(1);
if (args[0] === 'pull' && process.env.MISSING_IMAGE === 'true') process.exit(1);
`,
);
chmodSync(docker, 0o755);
const commit = git('rev-parse', 'HEAD');
assert.deepEqual(await run(), {
docker: [
login,
`build -t ${image}:sha-${commit} -t ${image}:beta .`,
`push ${image}:sha-${commit}`,
`push ${image}:beta`,
],
komodo: deployed('beta-stack'),
});
assert.equal((await run({ komodo: 'failure' }, 1)).komodo.length, 2);
assert.equal((await run({ komodo: 'refused' }, 1)).komodo.length, 1);
assert.deepEqual(await run({ eventName: 'pull_request' }, 1), nothing);
assert.deepEqual(await run({ eventName: 'workflow_dispatch' }, 1), nothing);
assert.deepEqual(await run({ branch: 'feature/calendar' }, 1), nothing);
assert.deepEqual(await run({ registryPassword: '' }, 1), nothing);
assert.deepEqual(await run({ komodoSecret: '' }, 1), nothing);
git('tag', '-a', 'v1.5.0', '-m', 'Release 1.5.0');
assert.deepEqual(await run({ tag: 'v1.5.0' }), {
docker: [
login,
`pull ${image}:sha-${commit}`,
`tag ${image}:sha-${commit} ${image}:v1.5.0`,
`push ${image}:v1.5.0`,
`tag ${image}:sha-${commit} ${image}:latest`,
`push ${image}:latest`,
],
komodo: deployed('production-stack'),
});
assert.deepEqual(await run({ tag: 'v1.5.0', missingImage: true }, 1), {
docker: [login, `pull ${image}:sha-${commit}`],
komodo: [],
});
assert.deepEqual(await run({ tag: 'v1.5.0-rc.1' }, 1), nothing);
assert.deepEqual(await run({ tag: 'v1.6.0' }, 1), nothing);
git('switch', '-c', 'feature/calendar');
git('commit', '--allow-empty', '-m', 'feat: calendar');
assert.deepEqual(await run({ tag: 'v1.5.0' }, 1), nothing);
console.log('CI image publication and deployment checks passed.');
} finally {
komodo.close();
rmSync(directory, { recursive: true, force: true });
}