138 lines
8.1 KiB
JavaScript
138 lines
8.1 KiB
JavaScript
// Copyright (C) 2026 Zaher Salman
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { execFileSync } = require('child_process');
|
|
|
|
const versionPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;
|
|
|
|
function prepareRelease(root, env = process.env) {
|
|
const version = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version;
|
|
if (!versionPattern.test(version)) throw new Error('package.json must contain a valid release version');
|
|
if (!/^[1-9][0-9]*$/.test(env.PACKAGE_RUN_ID || '')) throw new Error('A packaging run ID is required');
|
|
let tag = null;
|
|
// Manual builds keep build-specific versions, even when dispatched on a tag.
|
|
if (env.GITEA_EVENT_NAME === 'push') {
|
|
if (env.GITEA_REF !== `refs/tags/v${version}`) {
|
|
throw new Error(`Release tag must match package.json: expected refs/tags/v${version}, got ${env.GITEA_REF}`);
|
|
}
|
|
tag = `v${version}`;
|
|
} else if (env.GITEA_EVENT_NAME !== 'workflow_dispatch') {
|
|
throw new Error('Only version-tag pushes and manual builds are supported');
|
|
}
|
|
const commit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();
|
|
if (tag) {
|
|
const taggedCommit = execFileSync('git', ['rev-parse', `refs/tags/${tag}^{commit}`], { cwd: root, encoding: 'utf8' }).trim();
|
|
if (taggedCommit !== commit) throw new Error('The checked-out commit does not match the release tag');
|
|
}
|
|
return { schema: 1, version, tag, commit, runId: env.PACKAGE_RUN_ID };
|
|
}
|
|
|
|
function readReleaseContext(directory, runId) {
|
|
const file = path.join(directory, 'release-context.json');
|
|
// Artifacts from before tag automation remain publishable as manual builds.
|
|
if (!fs.existsSync(file)) return null;
|
|
const context = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
if (!context || context.schema !== 1 || typeof context.version !== 'string' || !versionPattern.test(context.version)
|
|
|| !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(context.commit || '') || !/^[1-9][0-9]*$/.test(context.runId || '')
|
|
|| context.runId !== runId || (context.tag !== null && context.tag !== `v${context.version}`)) {
|
|
throw new Error('Invalid release context or packaging run ID mismatch');
|
|
}
|
|
const source = fs.readFileSync(path.join(directory, 'build-source.txt'), 'utf8');
|
|
if (!source.split(/\r?\n/).includes(`muSRFlow=${context.commit}`)) throw new Error('Release context does not match the artifact source commit');
|
|
return context;
|
|
}
|
|
|
|
async function createDraftRelease(directory, env = process.env, request = fetch) {
|
|
const context = readReleaseContext(directory, env.PACKAGE_RUN_ID);
|
|
if (!context || !context.tag) {
|
|
console.log('Manual build: no Release page will be created');
|
|
return null;
|
|
}
|
|
const { GITEA_SERVER_URL, GITEA_REPOSITORY, RELEASES_TOKEN } = env;
|
|
if (!RELEASES_TOKEN) throw new Error('A release write token is required');
|
|
if (!/^[\w.-]+\/[\w.-]+$/.test(GITEA_REPOSITORY || '')) throw new Error('Expected owner/repository');
|
|
const server = new URL(GITEA_SERVER_URL);
|
|
if (server.protocol !== 'https:' || server.username || server.password || server.search || server.hash) {
|
|
throw new Error('Expected an HTTPS Gitea server URL without credentials, query, or fragment');
|
|
}
|
|
const base = server.href.replace(/\/$/, '');
|
|
const api = `${base}/api/v1/repos/${GITEA_REPOSITORY}`;
|
|
const headers = { Authorization: `token ${RELEASES_TOKEN}` };
|
|
// Never let the release API silently create a missing tag or use a moved one.
|
|
const tagResponse = await request(`${api}/tags/${encodeURIComponent(context.tag)}`, {
|
|
headers, redirect: 'error', signal: AbortSignal.timeout(60000)
|
|
});
|
|
if (tagResponse.status !== 200) throw new Error(`Cannot verify release tag: HTTP ${tagResponse.status}`);
|
|
const tag = await tagResponse.json();
|
|
if (tag.commit?.sha !== context.commit) throw new Error('Release tag moved since this artifact was built; refusing to create a Release');
|
|
|
|
const marker = `<!-- musrflow-release:${context.tag}:${context.commit} -->`;
|
|
const existing = await request(`${api}/releases/tags/${encodeURIComponent(context.tag)}`, {
|
|
headers, redirect: 'error', signal: AbortSignal.timeout(60000)
|
|
});
|
|
if (existing.status === 200) {
|
|
const release = await existing.json();
|
|
if (release.tag_name !== context.tag || !String(release.body || '').includes(marker)) {
|
|
throw new Error('A Release already exists for this tag without matching build provenance; it was not changed');
|
|
}
|
|
console.log(`Release already exists; preserving its notes and publication status: ${release.html_url}`);
|
|
return release;
|
|
}
|
|
if (existing.body) await existing.body.cancel();
|
|
if (existing.status !== 404) throw new Error(`Cannot inspect existing Release: HTTP ${existing.status}`);
|
|
|
|
const owner = GITEA_REPOSITORY.split('/')[0];
|
|
const downloads = [
|
|
['musrflow', `musrflow-${context.version}-x86_64.rpm`],
|
|
['musrflow', `muSRFlow-${context.version}-x86_64.AppImage`],
|
|
['musrflow-runtime', `musrflow-runtime-${context.version}-x86_64.rpm`],
|
|
['musrflow-runtime', `musrflow-runtime-${context.version}-x86_64.AppImage`]
|
|
];
|
|
const lines = [marker, '', `# muSRFlow ${context.version}`, '',
|
|
'Linux x86_64 packages. Install the application; install the separate runtime only if you need ROOT/musrfit.', '',
|
|
'Review and smoke-test these downloads before publishing this draft.', '',
|
|
'| Download | SHA-256 |', '| --- | --- |'];
|
|
for (const [name, file] of downloads) {
|
|
const checksum = fs.readFileSync(path.join(directory, `${file}.sha256`), 'utf8').trim();
|
|
if (!/^[a-f0-9]{64} /.test(checksum) || checksum.slice(66) !== file) throw new Error(`Invalid checksum sidecar for ${file}`);
|
|
const url = `${base}/api/packages/${owner}/generic/${name}/${encodeURIComponent(context.version)}/${encodeURIComponent(file)}`;
|
|
lines.push(`| [${file}](${url}) | \`${checksum.slice(0, 64)}\` ([checksum](${url}.sha256)) |`);
|
|
}
|
|
lines.push('', `Source commit: [${context.commit}](${base}/${GITEA_REPOSITORY}/commit/${context.commit})`,
|
|
'', `Packaging workflow run ID: ${context.runId}.`, '',
|
|
`[Runtime manifest](${base}/api/packages/${owner}/generic/musrflow-runtime/${encodeURIComponent(context.version)}/runtime-manifest.json)`,
|
|
'', 'Windows/macOS installers are not produced by this workflow.');
|
|
const response = await request(`${api}/releases`, {
|
|
method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' },
|
|
redirect: 'error', signal: AbortSignal.timeout(60000),
|
|
body: JSON.stringify({ tag_name: context.tag, target_commitish: context.commit,
|
|
name: `muSRFlow ${context.version}`, body: lines.join('\n'), draft: true,
|
|
prerelease: context.version.split('+')[0].includes('-') })
|
|
});
|
|
if (response.status !== 201) throw new Error(`Create draft Release: HTTP ${response.status}. Check release write permission; retry Publish packages without rebuilding`);
|
|
const release = await response.json();
|
|
console.log(`Draft Release created: ${release.html_url}`);
|
|
return release;
|
|
}
|
|
|
|
module.exports = { prepareRelease, readReleaseContext, createDraftRelease };
|
|
|
|
if (require.main === module) {
|
|
(async () => {
|
|
if (process.argv[2] === 'prepare') {
|
|
const context = prepareRelease(process.cwd());
|
|
fs.writeFileSync('.ci-release-context.json', JSON.stringify(context, null, 2) + '\n');
|
|
console.log(context.tag ? `Validated release ${context.tag} at ${context.commit}` : 'Manual build: using build-specific package versions');
|
|
} else if (process.argv[2] === 'draft') {
|
|
await createDraftRelease(process.argv[3] || 'artifacts');
|
|
} else {
|
|
throw new Error('Usage: ci-release.js prepare | draft [artifacts-directory]');
|
|
}
|
|
})().catch(error => {
|
|
console.error(error.message);
|
|
process.exitCode = 1;
|
|
});
|
|
}
|