mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-26 20:55:48 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d928dd288 | ||
|
|
6f8182db41 |
@@ -4,6 +4,8 @@ on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: ['main', 'codex/**']
|
||||
# GitHub tag filters are globs, not SemVer validators. Validate before building.
|
||||
tags: ['**']
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -11,10 +13,42 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
cancel-in-progress: ${{ github.ref_type != 'tag' }}
|
||||
|
||||
jobs:
|
||||
release-validation:
|
||||
name: Validate release tag and version metadata
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
if: github.ref_type == 'tag'
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
if: github.ref_type == 'tag'
|
||||
with:
|
||||
node-version: '24.18.0'
|
||||
package-manager-cache: false
|
||||
- name: Require a tag commit already included in main
|
||||
if: github.ref_type == 'tag'
|
||||
run: |
|
||||
if ! git merge-base --is-ancestor HEAD origin/main; then
|
||||
echo '::error::Release tags must point to a commit already merged into main.'
|
||||
exit 1
|
||||
fi
|
||||
- name: Validate strict SemVer and matching plugin metadata
|
||||
id: version
|
||||
if: github.ref_type == 'tag'
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: node scripts/release-version.mjs
|
||||
|
||||
php-compatibility:
|
||||
needs: release-validation
|
||||
name: PHP ${{ matrix.php }} syntax and regression tests
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
@@ -34,6 +68,7 @@ jobs:
|
||||
# Only this job publishes the installable package. No WordPress containers or
|
||||
# downloaded plugins run here, and the artifact is immutable once uploaded.
|
||||
build:
|
||||
needs: release-validation
|
||||
name: Build and publish pristine package
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
@@ -189,3 +224,33 @@ jobs:
|
||||
- name: Stop WordPress
|
||||
if: always()
|
||||
run: npx --no-install wp-env stop
|
||||
|
||||
release-draft:
|
||||
name: Create release draft from the pristine package
|
||||
if: github.event_name == 'push' && github.ref_type == 'tag'
|
||||
needs: [release-validation, build, php-compatibility, wordpress, plugin-check]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version: '24.18.0'
|
||||
package-manager-cache: false
|
||||
- name: Download only the original build artifact
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
|
||||
with:
|
||||
artifact-ids: ${{ needs.build.outputs.package-artifact-id }}
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
- name: Generate notes and prepare an unpublished release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
RELEASE_VERSION: ${{ needs.release-validation.outputs.version }}
|
||||
run: |
|
||||
node scripts/release-draft.mjs --tag "$RELEASE_TAG" --version "$RELEASE_VERSION" --commit "$(git rev-parse HEAD)" --zip dist/wp-asciiplayer.zip
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Preparing a GitHub release
|
||||
|
||||
Push a SemVer tag after the release commit has been merged into `main`. The CI workflow validates the tag, builds the installable ZIP, and runs the PHP and WordPress/browser test matrices. Only then does it create an **unpublished GitHub Release draft**, with generated release notes, the ZIP, and its SHA-256 checksum. Review and publish the draft yourself.
|
||||
|
||||
No WordPress.org upload or deployment is performed.
|
||||
|
||||
## Before tagging
|
||||
|
||||
Use one exact version in these places:
|
||||
|
||||
- `package.json`: `version`
|
||||
- `package-lock.json`: top-level `version` and `packages[""].version`
|
||||
- `block.json`: `version`
|
||||
- `asciicast-player.php`: plugin `Version` header and `VERSION` constant
|
||||
- `readme.txt`: `Stable tag`
|
||||
|
||||
Then run `npm run build`, `npm test`, and `npm run package`. Commit the metadata and regenerated translation artifacts, and merge the changes into `main` before creating the tag. The workflow never bumps versions, rewrites a tag, or commits generated files for you.
|
||||
|
||||
For example, a tag `v1.2.3` requires `1.2.3` in every metadata field. Both `v1.2.3` and bare `1.2.3` are accepted; choose one convention and use it consistently. Leading zeroes such as `v01.2.3` are invalid. Prerelease and build identifiers are supported, for example `v1.2.3-rc.1+build.5`, with that exact version (without the `v`) in the metadata.
|
||||
|
||||
A prerelease tag creates a draft marked as a GitHub prerelease. Build metadata alone does not mark a prerelease. `readme.txt` is checked for consistency inside the ZIP; this workflow does not change WordPress.org's Stable Tag or its distribution rules. Do not treat a GitHub prerelease draft as a WordPress.org stable release.
|
||||
|
||||
## What the workflow checks
|
||||
|
||||
- Tags are checked against the full SemVer grammar, not just GitHub's tag glob.
|
||||
- The tagged commit must already be included in `main`.
|
||||
- Tag and plugin metadata must agree exactly. A stable tag cannot release files that still contain a development version.
|
||||
- Both PHP compatibility jobs and both WordPress integration jobs must pass. Plugin Check keeps its existing advisory treatment for directory-review findings.
|
||||
- The release job downloads the immutable artifact ID from the build job. It never uses a copy mounted into WordPress or Plugin Check.
|
||||
- Only the final draft job has repository write permission. It installs no npm dependencies and never publishes a release.
|
||||
|
||||
## Notes and reruns
|
||||
|
||||
Release notes are generated by GitHub from the previous suitable published SemVer release. Stable releases exclude prerelease predecessors; prereleases may use an earlier prerelease. The predecessor must also be an existing tag reachable from the release commit. With no suitable predecessor, the workflow lists commits reachable from the tagged commit instead of letting GitHub choose an unrelated comparison base. Review the generated text before publishing.
|
||||
|
||||
Rerunning the tag workflow resumes its matching draft rather than creating another one. An already published release is left untouched. Existing assets must match the expected bytes; conflicting assets or an unrelated draft cause a clear failure instead of being overwritten. If you edit the draft manually, keep its provenance marker so a rerun can recognize it.
|
||||
|
||||
Use a new version/tag for different source code. Do not move an existing release tag to repair a failed run. Normal branch and pull-request CI never creates a release draft.
|
||||
@@ -0,0 +1,218 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { basename, resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { parseTag, compareVersions } from './release-version.mjs';
|
||||
|
||||
const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
||||
|
||||
export function previousRelease(releases, tag) {
|
||||
const current = parseTag(tag);
|
||||
if (!current) throw new Error('Invalid release tag.');
|
||||
return releases.filter((release) => {
|
||||
const parsed = parseTag(release.tag_name);
|
||||
return !release.draft && parsed && compareVersions(parsed, current) < 0 &&
|
||||
(current.prerelease || (!release.prerelease && !parsed.prerelease));
|
||||
}).sort((a, b) => compareVersions(b.tag_name, a.tag_name))[0];
|
||||
}
|
||||
|
||||
export function prepareAssets(zip, zipName = 'wp-asciiplayer.zip') {
|
||||
if (!Buffer.isBuffer(zip) || zip.length < 4 || !zip.subarray(0, 4).equals(Buffer.from([0x50, 0x4b, 3, 4]))) {
|
||||
throw new Error('Expected a nonempty ZIP archive.');
|
||||
}
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.zip$/.test(zipName)) throw new Error('Unsafe ZIP filename.');
|
||||
const checksum = Buffer.from(`${digest(zip)} ${zipName}\n`);
|
||||
return [
|
||||
{ name: zipName, bytes: zip, type: 'application/zip', sha256: digest(zip) },
|
||||
{ name: `${zipName}.sha256`, bytes: checksum, type: 'text/plain', sha256: digest(checksum) },
|
||||
];
|
||||
}
|
||||
|
||||
// All writes are confined to drafts for an already-existing, verified tag.
|
||||
// No module-level API calls: importing this file is safe in tests and tooling.
|
||||
export async function createReleaseDraft({ repository, tag, version, commit, token, zip,
|
||||
zipName = 'wp-asciiplayer.zip', fetchImpl = globalThis.fetch }) {
|
||||
const parsed = parseTag(tag);
|
||||
if (!parsed || parsed.version !== version) throw new Error('Tag and validated version disagree.');
|
||||
if (!/^[a-f0-9]{40}$/i.test(commit ?? '')) throw new Error('Expected a full commit SHA.');
|
||||
commit = commit.toLowerCase();
|
||||
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository ?? '')) throw new Error('Invalid repository.');
|
||||
if (!token) throw new Error('GH_TOKEN is required.');
|
||||
const assets = prepareAssets(zip, zipName);
|
||||
const base = `https://api.github.com/repos/${repository}`;
|
||||
async function request(url, { method = 'GET', body, binary = false, type } = {}) {
|
||||
const result = await fetchImpl(url, {
|
||||
method, redirect: 'error', headers: {
|
||||
Authorization: `Bearer ${token}`, Accept: binary ? 'application/octet-stream' : 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
...(body === undefined ? {} : { 'Content-Type': type ?? 'application/json' }),
|
||||
}, ...(body === undefined ? {} : { body: type ? body : JSON.stringify(body) }),
|
||||
});
|
||||
if (!result.ok) {
|
||||
const error = new Error(`GitHub API ${method} failed (${result.status}).`);
|
||||
error.status = result.status;
|
||||
throw error;
|
||||
}
|
||||
return binary ? Buffer.from(await result.arrayBuffer()) : result.json();
|
||||
}
|
||||
async function pages(path, query = {}) {
|
||||
const result = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const params = new URLSearchParams({ ...query, per_page: '100', page: String(page) });
|
||||
const batch = await request(`${base}${path}?${params}`);
|
||||
if (!Array.isArray(batch)) throw new Error('Invalid paginated GitHub response.');
|
||||
result.push(...batch);
|
||||
if (batch.length < 100) return result;
|
||||
}
|
||||
}
|
||||
async function resolveTag(tagName) {
|
||||
const ref = await request(`${base}/git/ref/tags/${encodeURIComponent(tagName)}`);
|
||||
if (ref.ref !== `refs/tags/${tagName}`) throw new Error('Tag reference does not match.');
|
||||
let object = ref.object;
|
||||
const seen = new Set();
|
||||
while (object?.type === 'tag') {
|
||||
if (!/^[a-f0-9]{40}$/i.test(object.sha) || seen.has(object.sha) || seen.size >= 20) {
|
||||
throw new Error('Invalid annotated tag chain.');
|
||||
}
|
||||
seen.add(object.sha);
|
||||
object = (await request(`${base}/git/tags/${object.sha}`)).object;
|
||||
}
|
||||
if (object?.type !== 'commit' || !/^[a-f0-9]{40}$/i.test(object.sha)) {
|
||||
throw new Error('Tag does not resolve to a valid commit.');
|
||||
}
|
||||
return object.sha.toLowerCase();
|
||||
}
|
||||
async function verifyTag() {
|
||||
if (await resolveTag(tag) !== commit) {
|
||||
throw new Error('Tag no longer resolves to the validated commit.');
|
||||
}
|
||||
}
|
||||
const marker = `<!-- wp-asciiplayer-release ${JSON.stringify({ tag, version, commit,
|
||||
assets: assets.map(({ name, sha256 }) => ({ name, sha256 })) })} -->`;
|
||||
function validateDraft(release) {
|
||||
if (!release.draft) throw new Error('Refusing to modify a published release.');
|
||||
if (release.tag_name !== tag || release.target_commitish !== commit ||
|
||||
release.prerelease !== Boolean(parsed.prerelease) || !release.body?.split('\n').includes(marker)) {
|
||||
throw new Error('Existing draft has different or missing provenance.');
|
||||
}
|
||||
}
|
||||
function matchingDraft(releases) {
|
||||
const matches = releases.filter((r) => r.tag_name === tag);
|
||||
if (matches.length > 1) throw new Error('Multiple releases exist for this tag.');
|
||||
if (matches.length) validateDraft(matches[0]);
|
||||
return matches[0];
|
||||
}
|
||||
await verifyTag();
|
||||
let releases = await pages('/releases');
|
||||
let release = matchingDraft(releases);
|
||||
if (!release) {
|
||||
let previous;
|
||||
// A released version can live on another maintenance branch, or its tag can
|
||||
// have been deleted. Only use an extant ancestor as a notes comparison base.
|
||||
const candidates = [...releases];
|
||||
while ((previous = previousRelease(candidates, tag))) {
|
||||
try {
|
||||
const previousCommit = await resolveTag(previous.tag_name);
|
||||
const comparison = await request(`${base}/compare/${previousCommit}...${commit}`);
|
||||
if (comparison.status === 'ahead' || comparison.status === 'identical') break;
|
||||
} catch (error) {
|
||||
if (error.status !== 404) throw error;
|
||||
}
|
||||
candidates.splice(candidates.indexOf(previous), 1);
|
||||
}
|
||||
let notes;
|
||||
if (previous) {
|
||||
notes = await request(`${base}/releases/generate-notes`, { method: 'POST', body: {
|
||||
tag_name: tag, target_commitish: commit, previous_tag_name: previous.tag_name,
|
||||
} });
|
||||
} else {
|
||||
// Omitting previous_tag_name would let GitHub choose an unsuitable base.
|
||||
// First-release notes instead enumerate commits reachable from this SHA.
|
||||
const commits = await pages('/commits', { sha: commit });
|
||||
if (!commits.length || commits[0].sha !== commit) throw new Error('Invalid first-release commit history.');
|
||||
const entries = commits.map((entry) => {
|
||||
if (!/^[a-f0-9]{40}$/i.test(entry.sha) || typeof entry.commit?.message !== 'string') {
|
||||
throw new Error('Invalid first-release commit entry.');
|
||||
}
|
||||
const subject = entry.commit.message.split(/\r?\n/)[0].replace(/[<>]/g, '').trim();
|
||||
return `- ${subject} (${entry.sha.slice(0, 12)})`;
|
||||
});
|
||||
notes = { body: `## Changes\n\nNo earlier eligible published release was found. Commits reachable from ${commit}:\n\n${entries.join('\n')}` };
|
||||
}
|
||||
if (typeof notes.body !== 'string') throw new Error('Invalid generated release notes.');
|
||||
await verifyTag();
|
||||
// Recheck after notes generation in case another run created the draft.
|
||||
release = matchingDraft(await pages('/releases'));
|
||||
if (!release) {
|
||||
try {
|
||||
release = await request(`${base}/releases`, { method: 'POST', body: {
|
||||
tag_name: tag, target_commitish: commit, name: tag, body: `${notes.body}\n\n${marker}`,
|
||||
draft: true, prerelease: Boolean(parsed.prerelease), make_latest: 'false',
|
||||
} });
|
||||
} catch (error) {
|
||||
if (error.status !== 422) throw error;
|
||||
release = matchingDraft(await pages('/releases'));
|
||||
if (!release) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
validateDraft(release);
|
||||
const releaseId = release.id;
|
||||
if (!Number.isSafeInteger(releaseId) || releaseId <= 0) throw new Error('Invalid release ID.');
|
||||
async function verifyAsset(existing, expected) {
|
||||
if (existing.state !== 'uploaded' || existing.size !== expected.bytes.length) {
|
||||
throw new Error(`Existing asset differs: ${expected.name}`);
|
||||
}
|
||||
// GitHub supplies a server-computed digest on current assets. Older assets
|
||||
// without a digest fail closed rather than trusting a user-editable label.
|
||||
if (existing.digest !== `sha256:${expected.sha256}`) {
|
||||
throw new Error(`Existing asset digest differs or is unavailable: ${expected.name}`);
|
||||
}
|
||||
}
|
||||
for (const asset of assets) {
|
||||
await verifyTag();
|
||||
validateDraft(await request(`${base}/releases/${releaseId}`));
|
||||
let listed = await pages(`/releases/${releaseId}/assets`);
|
||||
let matches = listed.filter((a) => a.name === asset.name);
|
||||
if (matches.length > 1) throw new Error(`Duplicate asset: ${asset.name}`);
|
||||
if (matches.length) { await verifyAsset(matches[0], asset); continue; }
|
||||
const upload = new URL(`https://uploads.github.com/repos/${repository}/releases/${releaseId}/assets`);
|
||||
upload.searchParams.set('name', asset.name);
|
||||
try {
|
||||
const uploaded = await request(upload.href, { method: 'POST', body: asset.bytes, type: asset.type });
|
||||
await verifyAsset(uploaded, asset);
|
||||
} catch (error) {
|
||||
if (error.status !== 422) throw error;
|
||||
listed = await pages(`/releases/${releaseId}/assets`);
|
||||
matches = listed.filter((a) => a.name === asset.name);
|
||||
if (matches.length !== 1) throw error;
|
||||
await verifyAsset(matches[0], asset);
|
||||
}
|
||||
}
|
||||
await verifyTag();
|
||||
validateDraft(await request(`${base}/releases/${releaseId}`));
|
||||
return { id: releaseId, tag, draft: true, assets: assets.map(({ name, sha256 }) => ({ name, sha256 })) };
|
||||
}
|
||||
|
||||
export async function main(args = process.argv.slice(2), env = process.env) {
|
||||
const options = {};
|
||||
const allowed = new Set(['tag', 'version', 'commit', 'zip']);
|
||||
for (let i = 0; i < args.length; i += 2) {
|
||||
const key = args[i].replace(/^--/, '');
|
||||
if (!args[i].startsWith('--') || !allowed.has(key) || !args[i + 1] || key in options) {
|
||||
throw new Error('Usage: release-draft.mjs [--tag TAG --version VERSION --commit SHA --zip PATH]');
|
||||
}
|
||||
options[key] = args[i + 1];
|
||||
}
|
||||
const zipPath = options.zip ?? 'dist/wp-asciiplayer.zip';
|
||||
const result = await createReleaseDraft({ repository: env.GITHUB_REPOSITORY,
|
||||
tag: options.tag ?? env.RELEASE_TAG, version: options.version ?? env.RELEASE_VERSION,
|
||||
commit: options.commit ?? env.RELEASE_COMMIT, token: env.GH_TOKEN,
|
||||
zip: await readFile(zipPath), zipName: basename(zipPath) });
|
||||
console.log(`Verified draft ${result.id} for ${result.tag} with ${result.assets.length} assets.`);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
||||
main().catch((error) => { console.error(error.message); process.exitCode = 1; });
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { appendFile, readFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// SemVer 2.0.0: numeric prerelease identifiers cannot have leading zeroes.
|
||||
const numeric = '(?:0|[1-9][0-9]*)';
|
||||
const identifier = `(?:${numeric}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;
|
||||
const semver = new RegExp(`^v?(${numeric})\\.(${numeric})\\.(${numeric})(?:-(${identifier}(?:\\.${identifier})*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$`);
|
||||
|
||||
/** Parse a bare SemVer or lowercase-v tag. Numeric fields remain lossless strings. */
|
||||
export function parseTag(tag) {
|
||||
if (typeof tag !== 'string' || /[\r\n]/.test(tag)) return null;
|
||||
const match = semver.exec(tag);
|
||||
if (!match) return null;
|
||||
const [, major, minor, patch, prerelease = '', build = ''] = match;
|
||||
return { version: `${major}.${minor}.${patch}${prerelease ? `-${prerelease}` : ''}${build ? `+${build}` : ''}`, major, minor, patch, prerelease, build };
|
||||
}
|
||||
|
||||
function compareNumeric(a, b) {
|
||||
return a.length !== b.length ? Math.sign(a.length - b.length) : a === b ? 0 : a < b ? -1 : 1;
|
||||
}
|
||||
|
||||
/** Compare SemVer precedence (build metadata does not affect ordering). */
|
||||
export function compareVersions(left, right) {
|
||||
const a = parseTag(typeof left === 'string' ? left : left?.version);
|
||||
const b = parseTag(typeof right === 'string' ? right : right?.version);
|
||||
if (!a || !b) throw new Error('Cannot compare invalid semantic versions.');
|
||||
for (const field of ['major', 'minor', 'patch']) {
|
||||
const difference = compareNumeric(a[field], b[field]);
|
||||
if (difference) return difference;
|
||||
}
|
||||
if (!a.prerelease || !b.prerelease) return a.prerelease === b.prerelease ? 0 : a.prerelease ? -1 : 1;
|
||||
const aa = a.prerelease.split('.');
|
||||
const bb = b.prerelease.split('.');
|
||||
for (let i = 0; i < Math.max(aa.length, bb.length); i++) {
|
||||
if (aa[i] === undefined) return -1;
|
||||
if (bb[i] === undefined) return 1;
|
||||
if (aa[i] === bb[i]) continue;
|
||||
const an = /^[0-9]+$/.test(aa[i]);
|
||||
const bn = /^[0-9]+$/.test(bb[i]);
|
||||
if (an && bn) return compareNumeric(aa[i], bb[i]);
|
||||
if (an !== bn) return an ? -1 : 1;
|
||||
return aa[i] < bb[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function uniqueValue(text, pattern, label) {
|
||||
const matches = [...text.matchAll(pattern)];
|
||||
if (matches.length !== 1) throw new Error(`Expected exactly one ${label}; found ${matches.length}.`);
|
||||
return matches[0][1].trim();
|
||||
}
|
||||
|
||||
/** Verify the tagged checkout without changing any metadata. */
|
||||
export async function validateReleaseVersion(tag, root = path.resolve(fileURLToPath(new URL('..', import.meta.url)))) {
|
||||
const parsed = parseTag(tag);
|
||||
if (!parsed) throw new Error('RELEASE_TAG must be a full SemVer tag, optionally prefixed with lowercase v.');
|
||||
const read = (file) => readFile(path.join(root, file), 'utf8');
|
||||
const [pkg, lock, block, php, readme] = await Promise.all([
|
||||
read('package.json').then(JSON.parse), read('package-lock.json').then(JSON.parse),
|
||||
read('block.json').then(JSON.parse), read('asciicast-player.php'), read('readme.txt'),
|
||||
]);
|
||||
const versions = [
|
||||
['package.json version', pkg.version],
|
||||
['package-lock.json version', lock.version],
|
||||
['package-lock.json packages[""] version', lock.packages?.['']?.version],
|
||||
['block.json version', block.version],
|
||||
['asciicast-player.php Version header', uniqueValue(php, /^[ \t]*\*[ \t]*Version:[ \t]*([^\r\n]*)\r?$/gm, 'PHP Version header')],
|
||||
['asciicast-player.php VERSION constant', uniqueValue(php, /^[ \t]*const[ \t]+VERSION[ \t]*=[ \t]*['"]([^'"\r\n]*)['"][ \t]*;[ \t]*\r?$/gm, 'PHP VERSION constant')],
|
||||
['readme.txt Stable tag', uniqueValue(readme, /^Stable tag:[ \t]*([^\r\n]*)\r?$/gm, 'readme Stable tag')],
|
||||
];
|
||||
const mismatches = versions.filter(([, version]) => version !== parsed.version);
|
||||
if (mismatches.length) {
|
||||
throw new Error(`Release metadata must exactly match ${parsed.version}:\n${mismatches.map(([label, version]) => `- ${label}: ${JSON.stringify(version) ?? 'missing'}`).join('\n')}\nUpdate the metadata before creating the tag; this validator never rewrites it.`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
const release = await validateReleaseVersion(process.env.RELEASE_TAG);
|
||||
// Only validated SemVer and literal booleans enter GitHub's line-oriented output.
|
||||
if (process.env.GITHUB_OUTPUT) await appendFile(process.env.GITHUB_OUTPUT, `valid=true\nversion=${release.version}\nprerelease=${Boolean(release.prerelease)}\n`);
|
||||
console.log(`Validated release version ${release.version}.`);
|
||||
} catch (error) {
|
||||
console.error(`Release validation failed: ${error.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createReleaseDraft, prepareAssets, previousRelease, main } from '../../scripts/release-draft.mjs';
|
||||
|
||||
const commit = 'a'.repeat(40);
|
||||
const zip = Buffer.from('504b0304000102030405', 'hex');
|
||||
const options = { repository: 'owner/repo', tag: 'v1.2.0', version: '1.2.0', commit, token: 'test-only', zip };
|
||||
const release = (tag, extra = {}) => ({ tag_name: tag, draft: false, prerelease: false, ...extra });
|
||||
|
||||
function fixture({ releases = [], annotated = false, moveAt = Infinity, uploadConflict = false, comparisons = {} } = {}) {
|
||||
const calls = [];
|
||||
const assets = [];
|
||||
let refs = 0;
|
||||
let created;
|
||||
let failedUpload = false;
|
||||
const predecessorShas = new Map();
|
||||
const fetchImpl = async (input, init) => {
|
||||
const url = new URL(input);
|
||||
const body = init.headers['Content-Type'] === 'application/json' ? JSON.parse(init.body) : init.body;
|
||||
calls.push({ url, ...init, body });
|
||||
const response = (value, status = 200) => ({ ok: status < 400, status, json: async () => value });
|
||||
if (url.pathname.endsWith('/git/ref/tags/v1.2.0')) {
|
||||
refs++;
|
||||
return response({ ref: 'refs/tags/v1.2.0', object: { type: annotated ? 'tag' : 'commit',
|
||||
sha: refs >= moveAt ? 'b'.repeat(40) : commit } });
|
||||
}
|
||||
if (url.pathname.includes('/git/ref/tags/')) {
|
||||
const tag = decodeURIComponent(url.pathname.split('/git/ref/tags/')[1]);
|
||||
if (comparisons[tag] === 'missing') return response({}, 404);
|
||||
const sha = String(predecessorShas.size + 1).padStart(40, '0');
|
||||
predecessorShas.set(sha, tag);
|
||||
return response({ ref: `refs/tags/${tag}`, object: { type: 'commit', sha } });
|
||||
}
|
||||
if (url.pathname.includes('/git/tags/')) return response({ object: { type: 'commit', sha: commit } });
|
||||
if (url.pathname.endsWith('/commits')) return response([{ sha: commit, commit: { message: 'Initial implementation' } }]);
|
||||
if (url.pathname.includes('/compare/')) {
|
||||
const sha = url.pathname.split('/compare/')[1].split('...')[0];
|
||||
assert.match(sha, /^[a-f0-9]{40}$/);
|
||||
const tag = predecessorShas.get(sha);
|
||||
assert.ok(tag, 'comparison must use an explicitly resolved predecessor tag SHA');
|
||||
const status = comparisons[tag] ?? 'ahead';
|
||||
return status === 'missing' ? response({}, 404) : response({ status });
|
||||
}
|
||||
if (url.pathname.endsWith('/releases/generate-notes')) return response({ body: 'Generated notes' });
|
||||
if (url.pathname.endsWith('/releases') && init.method === 'GET') return response(releases);
|
||||
if (url.pathname.endsWith('/releases') && init.method === 'POST') {
|
||||
created = { id: 123, ...body };
|
||||
releases.push(created);
|
||||
return response(created, 201);
|
||||
}
|
||||
if (url.pathname.endsWith('/releases/123')) return response(created ?? releases.find((r) => r.id === 123));
|
||||
if (url.pathname.endsWith('/releases/123/assets') && init.method === 'GET') return response(assets);
|
||||
if (url.hostname === 'uploads.github.com') {
|
||||
const name = url.searchParams.get('name');
|
||||
const expected = prepareAssets(zip).find((a) => a.name === name);
|
||||
const uploaded = { name, state: 'uploaded', size: body.length, digest: `sha256:${expected.sha256}` };
|
||||
assets.push(uploaded);
|
||||
if (uploadConflict && !failedUpload) { failedUpload = true; return response({}, 422); }
|
||||
return response(uploaded, 201);
|
||||
}
|
||||
throw new Error(`Unexpected mock request: ${init.method} ${input}`);
|
||||
};
|
||||
return { fetchImpl, calls, assets, releases, get created() { return created; } };
|
||||
}
|
||||
|
||||
test('stable notes select highest lower published stable SemVer, never drafts or prereleases', () => {
|
||||
const releases = [release('v1.1.0'), release('v1.1.9-rc.1', { prerelease: true }), release('v1.2.0'),
|
||||
release('v1.1.5', { draft: true }), release('v1.1.3'), release('bad'), release('v2.0.0')];
|
||||
assert.equal(previousRelease(releases, 'v1.2.0').tag_name, 'v1.1.3');
|
||||
});
|
||||
|
||||
test('prerelease notes can use lower published prereleases with numeric SemVer ordering', () => {
|
||||
const releases = ['v1.2.0-rc.2', 'v1.2.0-rc.10', 'v1.1.0', 'v1.2.0'].map((tag) => release(tag));
|
||||
assert.equal(previousRelease(releases, 'v1.2.0-rc.11').tag_name, 'v1.2.0-rc.10');
|
||||
assert.equal(previousRelease([], 'v1.0.0'), undefined);
|
||||
});
|
||||
|
||||
test('creates draft only with generated notes, provenance, ZIP and checksum', async () => {
|
||||
const f = fixture({ releases: [release('v1.1.0')] });
|
||||
const result = await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
assert.equal(result.draft, true);
|
||||
assert.equal(f.created.draft, true);
|
||||
assert.equal(f.created.prerelease, false);
|
||||
assert.equal(f.created.make_latest, 'false');
|
||||
assert.equal(f.created.target_commitish, commit);
|
||||
assert.match(f.created.body, /Generated notes\n\n<!-- wp-asciiplayer-release/);
|
||||
const notes = f.calls.find((c) => c.url.pathname.endsWith('generate-notes'));
|
||||
assert.equal(notes.body.previous_tag_name, 'v1.1.0');
|
||||
assert.deepEqual(f.assets.map((a) => a.name), ['wp-asciiplayer.zip', 'wp-asciiplayer.zip.sha256']);
|
||||
assert.equal(f.calls.filter((c) => c.method === 'POST').length, 4);
|
||||
assert.ok(f.calls.every((c) => c.headers.Authorization === 'Bearer test-only'));
|
||||
assert.ok(f.calls.every((c) => c.redirect === 'error'));
|
||||
assert.ok(!f.calls.some((c) => /\/git\/(refs|tags)$/.test(c.url.pathname) && c.method === 'POST'));
|
||||
});
|
||||
|
||||
test('rerun verifies provenance and bytes without changing draft or duplicating assets', async () => {
|
||||
const f = fixture();
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
const writes = f.calls.filter((c) => c.method === 'POST').length;
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
assert.equal(f.calls.filter((c) => c.method === 'POST').length, writes);
|
||||
assert.equal(f.releases.length, 1);
|
||||
assert.equal(f.assets.length, 2);
|
||||
});
|
||||
|
||||
test('rerun recovers missing asset after interrupted upload', async () => {
|
||||
const f = fixture();
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
f.assets.pop();
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
assert.equal(f.assets.length, 2);
|
||||
assert.equal(f.releases.length, 1);
|
||||
});
|
||||
|
||||
test('never modifies a published release', async () => {
|
||||
const f = fixture({ releases: [release('v1.2.0')] });
|
||||
await assert.rejects(createReleaseDraft({ ...options, fetchImpl: f.fetchImpl }), /published release/);
|
||||
assert.ok(f.calls.every((c) => c.method === 'GET'));
|
||||
});
|
||||
|
||||
test('refuses unrelated existing draft or duplicate releases', async () => {
|
||||
for (const releases of [[release('v1.2.0', { draft: true })], [release('v1.2.0'), release('v1.2.0')]]) {
|
||||
const f = fixture({ releases });
|
||||
await assert.rejects(createReleaseDraft({ ...options, fetchImpl: f.fetchImpl }), /provenance|Multiple releases/);
|
||||
assert.ok(f.calls.every((c) => c.method === 'GET'));
|
||||
}
|
||||
});
|
||||
|
||||
test('fails closed on missing, wrong or changed asset digest without replacing anything', async () => {
|
||||
for (const digest of [undefined, `sha256:${'0'.repeat(64)}`]) {
|
||||
const f = fixture();
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
f.assets[0].digest = digest;
|
||||
const count = f.calls.length;
|
||||
await assert.rejects(createReleaseDraft({ ...options, fetchImpl: f.fetchImpl }), /digest/);
|
||||
assert.ok(f.calls.slice(count).every((c) => c.method === 'GET'));
|
||||
}
|
||||
});
|
||||
|
||||
test('refuses changed local bytes before uploading or editing draft', async () => {
|
||||
const f = fixture();
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
await assert.rejects(createReleaseDraft({ ...options, zip: Buffer.concat([zip, Buffer.from('changed')]),
|
||||
fetchImpl: f.fetchImpl }), /provenance/);
|
||||
assert.equal(f.assets.length, 2);
|
||||
});
|
||||
|
||||
test('peels annotated tags to commit', async () => {
|
||||
const f = fixture({ annotated: true });
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
assert.ok(f.calls.some((c) => c.url.pathname.includes('/git/tags/')));
|
||||
});
|
||||
|
||||
test('moved tag fails before creation or upload', async () => {
|
||||
for (const moveAt of [1, 2, 3]) {
|
||||
const f = fixture({ moveAt });
|
||||
await assert.rejects(createReleaseDraft({ ...options, fetchImpl: f.fetchImpl }), /no longer resolves/);
|
||||
assert.equal(f.assets.length, 0);
|
||||
if (moveAt < 3) assert.equal(f.created, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test('upload conflict only succeeds when concurrently uploaded asset has matching digest', async () => {
|
||||
const f = fixture({ uploadConflict: true });
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
assert.equal(f.assets.length, 2);
|
||||
});
|
||||
|
||||
test('validates every input before API access', async () => {
|
||||
const fetchImpl = () => { throw new Error('Unexpected network access'); };
|
||||
for (const patch of [{ tag: 'main' }, { version: '9.9.9' }, { commit: 'short' },
|
||||
{ repository: '../owner/repo' }, { token: '' }, { zip: Buffer.from('not zip') }, { zipName: '../bad.zip' }]) {
|
||||
await assert.rejects(createReleaseDraft({ ...options, ...patch, fetchImpl }),
|
||||
(error) => !error.message.includes('Unexpected network'));
|
||||
}
|
||||
});
|
||||
|
||||
test('checksum is deterministic and CLI rejects unknown and duplicate flags', async () => {
|
||||
const assets = prepareAssets(zip);
|
||||
assert.equal(assets[1].bytes.toString(), `${assets[0].sha256} wp-asciiplayer.zip\n`);
|
||||
await assert.rejects(main(['--publish', 'true'], {}), /Usage/);
|
||||
await assert.rejects(main(['--tag', 'a', '--tag', 'b'], {}), /Usage/);
|
||||
});
|
||||
|
||||
test('notes skip missing tags and unrelated branches in favor of a lower released ancestor', async () => {
|
||||
const f = fixture({ releases: ['v1.1.9', 'v1.1.8', 'v1.1.7'].map((tag) => release(tag)),
|
||||
comparisons: { 'v1.1.9': 'missing', 'v1.1.8': 'diverged' } });
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
assert.equal(f.calls.find((c) => c.url.pathname.endsWith('generate-notes')).body.previous_tag_name, 'v1.1.7');
|
||||
});
|
||||
|
||||
test('no eligible predecessor uses explicit commit history instead of GitHub auto-selection', async () => {
|
||||
const f = fixture({ releases: [release('v1.1.0-rc.1', { prerelease: true })] });
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
assert.ok(!f.calls.some((c) => c.url.pathname.endsWith('generate-notes')));
|
||||
assert.match(f.created.body, /Initial implementation/);
|
||||
assert.match(f.created.body, /No earlier eligible published release/);
|
||||
assert.equal(f.calls.find((c) => c.url.pathname.endsWith('/commits')).url.searchParams.get('sha'), commit);
|
||||
});
|
||||
|
||||
test('prerelease drafts set prerelease flag while remaining unpublished', async () => {
|
||||
const f = fixture();
|
||||
const tag = 'v1.2.0-rc.1';
|
||||
const fetchImpl = (input, init) => {
|
||||
if (input.includes('/git/ref/tags/')) {
|
||||
return Promise.resolve({ ok: true, status: 200,
|
||||
json: async () => ({ ref: `refs/tags/${tag}`, object: { type: 'commit', sha: commit } }) });
|
||||
}
|
||||
return f.fetchImpl(input, init);
|
||||
};
|
||||
await createReleaseDraft({ ...options, tag, version: '1.2.0-rc.1', fetchImpl });
|
||||
assert.equal(f.created.draft, true);
|
||||
assert.equal(f.created.prerelease, true);
|
||||
});
|
||||
|
||||
test('release and first-release history pagination includes later pages', async () => {
|
||||
const f = fixture();
|
||||
const fetchImpl = (input, init) => {
|
||||
const url = new URL(input);
|
||||
if (init.method === 'GET' && url.pathname.endsWith('/releases')) {
|
||||
const filler = Array.from({ length: 100 }, (_, i) => release(`v0.0.${i}`, { draft: true }));
|
||||
const page = url.searchParams.get('page');
|
||||
return Promise.resolve({ ok: true, status: 200,
|
||||
json: async () => page === '1' ? filler : f.releases });
|
||||
}
|
||||
if (url.pathname.endsWith('/commits')) {
|
||||
const page = url.searchParams.get('page');
|
||||
return Promise.resolve({ ok: true, status: 200, json: async () => page === '1'
|
||||
? Array.from({ length: 100 }, () => ({ sha: commit, commit: { message: 'Earlier change' } }))
|
||||
: [{ sha: 'b'.repeat(40), commit: { message: 'Oldest change on second page' } }] });
|
||||
}
|
||||
return f.fetchImpl(input, init);
|
||||
};
|
||||
await createReleaseDraft({ ...options, fetchImpl });
|
||||
assert.match(f.created.body, /Oldest change on second page/);
|
||||
await createReleaseDraft({ ...options, fetchImpl });
|
||||
assert.equal(f.releases.length, 1);
|
||||
});
|
||||
|
||||
test('deleted predecessor tag cannot resolve a same-named branch through compare API', async () => {
|
||||
const f = fixture({ releases: [release('v1.1.0')], comparisons: { 'v1.1.0': 'missing' } });
|
||||
await createReleaseDraft({ ...options, fetchImpl: f.fetchImpl });
|
||||
assert.ok(f.calls.some((c) => c.url.pathname.endsWith('/git/ref/tags/v1.1.0')));
|
||||
assert.ok(!f.calls.some((c) => c.url.pathname.includes('/compare/')));
|
||||
assert.ok(!f.calls.some((c) => c.url.pathname.endsWith('generate-notes')));
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, mkdir, writeFile, readFile, copyFile, rm } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parseTag, compareVersions, validateReleaseVersion } from '../../scripts/release-version.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
|
||||
test('strict SemVer accepts complete versions, optional v, prereleases and builds', () => {
|
||||
assert.deepEqual(parseTag('v1.2.3-rc.1+build.001'), {
|
||||
version: '1.2.3-rc.1+build.001', major: '1', minor: '2', patch: '3', prerelease: 'rc.1', build: 'build.001',
|
||||
});
|
||||
for (const version of ['0.0.0', '1.2.3', '1.2.3-dev', '1.2.3-0', '1.2.3-01a', '1.2.3--', '1.2.3+001', '999999999999999999999.0.0']) {
|
||||
assert.equal(parseTag(version)?.version, version);
|
||||
assert.equal(parseTag(`v${version}`)?.version, version);
|
||||
}
|
||||
});
|
||||
|
||||
test('strict SemVer rejects malformed and output-injection tags', () => {
|
||||
for (const version of [undefined, null, 123, '', '1', '1.2', 'V1.2.3', 'vv1.2.3', '01.2.3', '1.02.3', '1.2.03',
|
||||
'1.2.3-01', '1.2.3-a.01', '1.2.3-', '1.2.3+', '1.2.3-a..b', '1.2.3+abc..def', '1.2.3+abc+def',
|
||||
'1.2.3-a_b', '1.2.3+ä', ' 1.2.3', '1.2.3 ', '1.2.3\n', '1.2.3\r', '1.2.3\nvalid=true', 'refs/tags/v1.2.3']) {
|
||||
assert.equal(parseTag(version), null, JSON.stringify(version));
|
||||
}
|
||||
});
|
||||
|
||||
test('SemVer precedence handles numeric identifiers, releases, and large integers', () => {
|
||||
const ordered = ['1.0.0-alpha', '1.0.0-alpha.1', '1.0.0-alpha.beta', '1.0.0-beta', '1.0.0-beta.2', '1.0.0-beta.11', '1.0.0-rc.1', '1.0.0', '1.0.1', '1.1.0', '2.0.0'];
|
||||
for (let i = 1; i < ordered.length; i++) {
|
||||
assert.equal(compareVersions(ordered[i - 1], ordered[i]), -1);
|
||||
assert.equal(compareVersions(parseTag(ordered[i]), parseTag(ordered[i - 1])), 1);
|
||||
}
|
||||
assert.equal(compareVersions('1.2.3+aaa', 'v1.2.3+bbb'), 0);
|
||||
assert.equal(compareVersions('1.2.3-rc.1+aaa', '1.2.3-rc.1+bbb'), 0);
|
||||
assert.equal(compareVersions('9007199254740992.0.0', '9007199254740993.0.0'), -1);
|
||||
assert.equal(compareVersions('1.0.0-9007199254740992', '1.0.0-9007199254740993'), -1);
|
||||
assert.throws(() => compareVersions('nope', '1.0.0'), /invalid/);
|
||||
});
|
||||
|
||||
async function fixture(t, version = '1.2.3') {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), 'release-version-test-'));
|
||||
t.after(() => rm(dir, { recursive: true, force: true }));
|
||||
await mkdir(path.join(dir, 'scripts'));
|
||||
await copyFile(path.join(root, 'scripts/release-version.mjs'), path.join(dir, 'scripts/release-version.mjs'));
|
||||
await Promise.all([
|
||||
writeFile(path.join(dir, 'package.json'), JSON.stringify({ version })),
|
||||
writeFile(path.join(dir, 'package-lock.json'), JSON.stringify({ version, packages: { '': { version } } })),
|
||||
writeFile(path.join(dir, 'block.json'), JSON.stringify({ version })),
|
||||
writeFile(path.join(dir, 'asciicast-player.php'), `<?php\n/**\n * Version: ${version}\n */\nconst VERSION = '${version}';\n`),
|
||||
writeFile(path.join(dir, 'readme.txt'), `=== Plugin ===\nStable tag: ${version}\n`),
|
||||
]);
|
||||
return dir;
|
||||
}
|
||||
|
||||
test('metadata validation accepts exact stable and prerelease/build metadata', async (t) => {
|
||||
for (const version of ['1.2.3', '1.2.3-rc.1+build.001']) {
|
||||
const dir = await fixture(t, version);
|
||||
assert.equal((await validateReleaseVersion(`v${version}`, dir)).version, version);
|
||||
}
|
||||
});
|
||||
|
||||
test('metadata validation accepts CRLF text files', async (t) => {
|
||||
const dir = await fixture(t);
|
||||
for (const file of ['asciicast-player.php', 'readme.txt']) {
|
||||
const source = await readFile(path.join(dir, file), 'utf8');
|
||||
await writeFile(path.join(dir, file), source.replaceAll('\n', '\r\n'));
|
||||
}
|
||||
assert.equal((await validateReleaseVersion('1.2.3', dir)).version, '1.2.3');
|
||||
});
|
||||
|
||||
test('every release metadata surface is required and compared exactly', async (t) => {
|
||||
const mutations = [
|
||||
['package.json', '{"version":"1.2.4"}', 'package.json version'],
|
||||
['package-lock.json', '{"version":"1.2.4","packages":{"":{"version":"1.2.3"}}}', 'package-lock.json version'],
|
||||
['package-lock.json', '{"version":"1.2.3","packages":{"":{"version":"1.2.4"}}}', 'packages[""] version'],
|
||||
['package-lock.json', '{"version":"1.2.3"}', 'missing'],
|
||||
['block.json', '{"version":"1.2.4"}', 'block.json version'],
|
||||
['asciicast-player.php', " * Version: 1.2.4\nconst VERSION = '1.2.3';\n", 'Version header'],
|
||||
['asciicast-player.php', " * Version: 1.2.3\nconst VERSION = '1.2.4';\n", 'VERSION constant'],
|
||||
['readme.txt', 'Stable tag: trunk\n', 'readme.txt Stable tag'],
|
||||
['readme.txt', 'Stable tag: v1.2.3\n', 'readme.txt Stable tag'],
|
||||
['readme.txt', 'Stable tag: 1.2.3\nStable tag: 1.2.3\n', 'exactly one'],
|
||||
['asciicast-player.php', ' * Version: 1.2.3\n', 'exactly one'],
|
||||
];
|
||||
for (const [file, content, error] of mutations) {
|
||||
const dir = await fixture(t);
|
||||
await writeFile(path.join(dir, file), content);
|
||||
await assert.rejects(validateReleaseVersion('v1.2.3', dir), (e) => e.message.includes(error));
|
||||
assert.equal(await readFile(path.join(dir, file), 'utf8'), content, 'validator must not rewrite files');
|
||||
}
|
||||
});
|
||||
|
||||
test('current development metadata cannot accidentally become a stable release', async (t) => {
|
||||
const dir = await fixture(t, '1.1.0-dev');
|
||||
await assert.rejects(validateReleaseVersion('v1.1.0', dir), /must exactly match 1.1.0/);
|
||||
assert.equal((await validateReleaseVersion('v1.1.0-dev', dir)).prerelease, 'dev');
|
||||
});
|
||||
|
||||
test('CLI writes trusted outputs only after successful validation', async (t) => {
|
||||
const dir = await fixture(t, '1.2.3-rc.1+001');
|
||||
const output = path.join(dir, 'output');
|
||||
const run = (tag) => spawnSync(process.execPath, ['scripts/release-version.mjs'], {
|
||||
cwd: dir, encoding: 'utf8', env: { ...process.env, RELEASE_TAG: tag, GITHUB_OUTPUT: output },
|
||||
});
|
||||
const success = run('v1.2.3-rc.1+001');
|
||||
assert.equal(success.status, 0, success.stderr);
|
||||
const expected = 'valid=true\nversion=1.2.3-rc.1+001\nprerelease=true\n';
|
||||
assert.equal(await readFile(output, 'utf8'), expected);
|
||||
for (const tag of ['v1.2.3', '', 'v1.2.3\nvalid=true']) {
|
||||
const failure = run(tag);
|
||||
assert.equal(failure.status, 1);
|
||||
assert.match(failure.stderr, /Release validation failed:/);
|
||||
assert.equal(await readFile(output, 'utf8'), expected);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const workflow = readFileSync(new URL('../../.github/workflows/ci.yml', import.meta.url), 'utf8');
|
||||
const job = (name) => workflow.match(new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [a-z][a-z-]*:|$(?![\\s\\S]))`, 'm'))?.[1];
|
||||
|
||||
test('release writes are confined to a tag-only job after the full test graph', () => {
|
||||
assert.match(workflow, /permissions:\n contents: read/);
|
||||
assert.equal((workflow.match(/contents: write/g) || []).length, 1);
|
||||
assert.match(job('release-draft'), /if: github.event_name == 'push' && github.ref_type == 'tag'/);
|
||||
assert.match(job('release-draft'), /needs: \[release-validation, build, php-compatibility, wordpress, plugin-check\]/);
|
||||
assert.match(job('release-validation'), /git merge-base --is-ancestor HEAD origin\/main/);
|
||||
assert.match(job('release-validation'), /run: node scripts\/release-version.mjs/);
|
||||
for (const name of ['build', 'php-compatibility']) assert.match(job(name), /needs: release-validation/);
|
||||
assert.doesNotMatch(job('release-draft'), /npm (?:ci|install)|continue-on-error|pull_request_target/);
|
||||
});
|
||||
|
||||
test('release downloads the pristine producer ID and never a consumer artifact', () => {
|
||||
const release = job('release-draft');
|
||||
assert.match(release, /artifact-ids: \$\{\{ needs.build.outputs.package-artifact-id \}\}/);
|
||||
assert.doesNotMatch(release, /pattern:|run-id:|overwrite:/);
|
||||
assert.match(job('build'), /path: dist\/wp-asciiplayer.zip/);
|
||||
for (const name of ['wordpress', 'plugin-check']) {
|
||||
const upload = job(name).split('actions/upload-artifact@')[1];
|
||||
assert.ok(upload);
|
||||
assert.doesNotMatch(upload, /dist\/|\.zip/);
|
||||
}
|
||||
assert.match(release, /persist-credentials: false/);
|
||||
assert.match(release, /--tag "\$RELEASE_TAG" --version "\$RELEASE_VERSION"/);
|
||||
});
|
||||
|
||||
test('tag reruns serialize without cancelling an in-progress draft upload', () => {
|
||||
assert.match(workflow, /group: \$\{\{ github.workflow \}\}-\$\{\{ github.ref \}\}/);
|
||||
assert.match(workflow, /cancel-in-progress: \$\{\{ github.ref_type != 'tag' \}\}/);
|
||||
assert.match(workflow, /tags: \['\*\*'\]/);
|
||||
});
|
||||
Reference in New Issue
Block a user