Build and publish Windows installers on version tags using the tested WSL packaging path. Keep Windows metadata in its own package and support publication recovery from saved Linux or Windows artifacts. Create one draft Release only after matching Linux and Windows provenance is published. Preserve reviewed release notes and handle concurrent creation safely. Cover publishing, recovery, and coordination with regression tests and update deployment and installation guides.
187 lines
11 KiB
JavaScript
187 lines
11 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];
|
|
if (!env.PACKAGES_TOKEN) throw new Error('A package read token is required to assemble the cross-platform Release');
|
|
const packageHeaders = { Authorization: `token ${env.PACKAGES_TOKEN}` };
|
|
const registry = `${base}/api/packages/${owner}/generic`;
|
|
const contexts = {};
|
|
// Either build may finish first. Only assemble a draft after all three
|
|
// package groups have published their final provenance file.
|
|
for (const name of ['musrflow', 'musrflow-runtime', 'musrflow-windows']) {
|
|
const response = await request(`${registry}/${name}/${encodeURIComponent(context.version)}/release-context.json`, {
|
|
headers: packageHeaders, redirect: 'error', signal: AbortSignal.timeout(60000)
|
|
});
|
|
if (response.status === 404) {
|
|
if (response.body) await response.body.cancel();
|
|
console.log(`Release pending: ${name}/${context.version} is not published yet. The other build will finish the draft; retry Publish packages if needed.`);
|
|
return null;
|
|
}
|
|
if (response.status !== 200) throw new Error(`Cannot inspect ${name} release context: HTTP ${response.status}`);
|
|
const remote = await response.json();
|
|
if (remote.schema !== 1 || remote.tag !== context.tag || remote.version !== context.version
|
|
|| remote.commit !== context.commit || !/^[1-9][0-9]*$/.test(remote.runId || '')) {
|
|
throw new Error(`${name} does not match the release tag and source commit`);
|
|
}
|
|
contexts[name] = remote;
|
|
}
|
|
if (contexts.musrflow.runId !== contexts['musrflow-runtime'].runId) {
|
|
throw new Error('Linux application and runtime came from different packaging runs');
|
|
}
|
|
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`],
|
|
['musrflow-windows', `muSRFlow-${context.version}-x64.exe`]
|
|
];
|
|
const lines = [marker, '', `# muSRFlow ${context.version}`, '',
|
|
'Linux x86_64 packages. Install the application; install the separate runtime only if you need ROOT/musrfit.', '',
|
|
'Windows x64: the unsigned installer includes the WSL2 runtime. WSL2/virtualization and WSLg must be available.', '',
|
|
'Review and smoke-test these downloads before publishing this draft.', '',
|
|
'| Download | SHA-256 |', '| --- | --- |'];
|
|
for (const [name, file] of downloads) {
|
|
const url = `${registry}/${name}/${encodeURIComponent(context.version)}/${encodeURIComponent(file)}`;
|
|
const checksumResponse = await request(`${url}.sha256`, {
|
|
headers: packageHeaders, redirect: 'error', signal: AbortSignal.timeout(60000)
|
|
});
|
|
if (checksumResponse.status !== 200) throw new Error(`Cannot read checksum for ${file}: HTTP ${checksumResponse.status}`);
|
|
const checksum = (await checksumResponse.text()).trim();
|
|
if (!/^[a-f0-9]{64} /.test(checksum) || checksum.slice(66) !== file) throw new Error(`Invalid checksum sidecar for ${file}`);
|
|
lines.push(`| [${file}](${url}) | \`${checksum.slice(0, 64)}\` ([checksum](${url}.sha256)) |`);
|
|
}
|
|
lines.push('', `Source commit: [${context.commit}](${base}/${GITEA_REPOSITORY}/commit/${context.commit})`,
|
|
'', `Linux packaging workflow run ID: ${contexts.musrflow.runId}.`,
|
|
`Windows packaging workflow run ID: ${contexts['musrflow-windows'].runId}.`, '',
|
|
`[Runtime manifest](${base}/api/packages/${owner}/generic/musrflow-runtime/${encodeURIComponent(context.version)}/runtime-manifest.json)`,
|
|
'', 'macOS installers are not produced by these workflows.');
|
|
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('-') })
|
|
});
|
|
// Both platforms may observe a missing draft at the same time. The loser
|
|
// of that create race may only accept a Release with matching provenance.
|
|
if ([409, 422].includes(response.status)) {
|
|
if (response.body) await response.body.cancel();
|
|
const concurrent = await request(`${api}/releases/tags/${encodeURIComponent(context.tag)}`, {
|
|
headers, redirect: 'error', signal: AbortSignal.timeout(60000)
|
|
});
|
|
if (concurrent.status === 200) {
|
|
const release = await concurrent.json();
|
|
if (release.tag_name === context.tag && String(release.body || '').includes(marker)) {
|
|
console.log(`Release created by the other workflow; preserving it: ${release.html_url}`);
|
|
return release;
|
|
}
|
|
}
|
|
throw new Error('Concurrent Release could not be verified; retry Publish packages without rebuilding');
|
|
}
|
|
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;
|
|
});
|
|
}
|