Release the plugin SDK as a package file
pnpm release:sdk now packs runestone-plugin-sdk-<version>.tgz and sdk.json into releases/plugin-sdk/<version>/. Plugins install the SDK from the URL of that file on the RuneStone releases page. The script no longer uses a clone of a separate SDK repository. Installers, browser engine ZIPs, and SDK packages now share the RuneStone releases page.
This commit is contained in:
+105
-92
@@ -1,29 +1,33 @@
|
||||
// Releases the plugin SDK into a local clone of its public repository. See docs/releases.md#sdk-releases.
|
||||
// Usage: node scripts/releaseSdk.mjs --version <version> [--dry-run]
|
||||
// The script commits and tags in the clone. It never pushes. It prints the push commands.
|
||||
// Packs the plugin SDK into a release file that plugins install from its URL. See docs/releases.md#sdk-releases.
|
||||
// Usage: node scripts/releaseSdk.mjs --release-url <folder URL> --version <version> [--dry-run]
|
||||
// The script writes releases/plugin-sdk/<version>/. It never uploads. It prints the dependency line for plugins.
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { realpathSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { compareReleases, releaseVersion } from './releaseVersion.mjs';
|
||||
import { buildSdk, sdkFolder } from './buildSdk.mjs';
|
||||
|
||||
const exists = file => fs.access(file).then(() => true, () => false);
|
||||
export const packageName = '@runestone/plugin-sdk';
|
||||
export const repositoryName = 'RuneStone_Plugin_SDK';
|
||||
export const publicRepository = 'https://git.knottywyvern.com/kwyvern/RuneStone_Plugin_SDK.git';
|
||||
// The files that the release puts at the root of the public repository. LICENSE is required. NOTICE is optional.
|
||||
export const releaseFiles = ['dist', 'package.json', 'README.md', 'LICENSE', 'NOTICE'];
|
||||
// The files beside dist/ and package.json in the package. LICENSE and README.md are required. NOTICE is optional.
|
||||
export const packageFiles = ['README.md', 'LICENSE', 'NOTICE'];
|
||||
// The fixed file time of npm packages, 1985-10-26 08:15 UTC, in seconds.
|
||||
export const packageTime = 499162500;
|
||||
|
||||
export function parseArguments(args) {
|
||||
const options = { version: undefined, dryRun: false };
|
||||
const options = { version: undefined, releaseUrl: undefined, dryRun: false };
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--dry-run') options.dryRun = true;
|
||||
else if (args[i] === '--version' && args[i + 1] && !options.version) options.version = args[++i];
|
||||
else throw Error('Use --version followed by the SDK version, and optionally --dry-run.');
|
||||
else if (args[i] === '--release-url' && args[i + 1] && !options.releaseUrl) options.releaseUrl = args[++i];
|
||||
else throw Error('Use --release-url followed by the release folder URL, --version followed by the SDK version, and optionally --dry-run.');
|
||||
}
|
||||
if (!options.version) throw Error('Use --version followed by the SDK version, for example --version 0.1.0.');
|
||||
if (!options.releaseUrl) throw Error('Use --release-url followed by the URL of the folder that will hold the SDK package.');
|
||||
if (!options.version) throw Error('Use --version followed by the SDK version, for example --version 0.1.2.');
|
||||
return options;
|
||||
}
|
||||
|
||||
@@ -36,13 +40,6 @@ export function git(cwd, args) {
|
||||
});
|
||||
});
|
||||
}
|
||||
const gitOptional = (cwd, args) => git(cwd, args).catch(() => null);
|
||||
|
||||
// The local clone of the public repository: RUNESTONE_SDK_REPO, or RuneStone_Plugin_SDK beside the plugin checkouts.
|
||||
export function clonePath(root, env = process.env) {
|
||||
if (env.RUNESTONE_SDK_REPO) return path.resolve(env.RUNESTONE_SDK_REPO);
|
||||
return path.join(path.resolve(env.RUNESTONE_PLUGIN_REPOS || path.dirname(root)), repositoryName);
|
||||
}
|
||||
|
||||
// The package.json of the release: the source fields with the new version, without build scripts or development dependencies.
|
||||
export function releasePackageJson(source, version) {
|
||||
@@ -52,9 +49,55 @@ export function releasePackageJson(source, version) {
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The file name that `npm pack` gives a package: `@scope/name` becomes `scope-name-<version>.tgz`. */
|
||||
export function packageFileName(name, version) {
|
||||
return `${name.replace(/^@/, '').replace('/', '-')}-${version}.tgz`;
|
||||
}
|
||||
|
||||
/** A gzip tar of the entries under `package/`, in name order, with a fixed time and mode. The same entries give the same bytes. */
|
||||
export function packEntries(entries) {
|
||||
const blocks = [];
|
||||
const sorted = [...entries].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
||||
for (let i = 1; i < sorted.length; i++) if (sorted[i].name === sorted[i - 1].name) throw Error('The SDK package has two files with the name ' + sorted[i].name);
|
||||
for (const { name, data } of sorted) {
|
||||
const full = Buffer.from('package/' + name, 'utf8');
|
||||
if (full.length > 100) throw Error('The SDK has a file name that is too long for the package: ' + name);
|
||||
if (data.length >= 8 ** 11) throw Error('The SDK has a file that is too large for the package: ' + name);
|
||||
// A ustar header: name, mode, owner, group, size, time, checksum, type, and the magic value.
|
||||
const header = Buffer.alloc(512);
|
||||
full.copy(header, 0);
|
||||
const octal = (value, offset, size) => header.write(value.toString(8).padStart(size - 1, '0') + '\0', offset, size, 'ascii');
|
||||
octal(0o644, 100, 8); octal(0, 108, 8); octal(0, 116, 8); octal(data.length, 124, 12); octal(packageTime, 136, 12);
|
||||
header.write(' ', 148, 8, 'ascii');
|
||||
header.write('0', 156, 1, 'ascii');
|
||||
header.write('ustar\0' + '00', 257, 8, 'ascii');
|
||||
let sum = 0;
|
||||
for (const byte of header) sum += byte;
|
||||
header.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8, 'ascii');
|
||||
blocks.push(header, data, Buffer.alloc((512 - data.length % 512) % 512));
|
||||
}
|
||||
blocks.push(Buffer.alloc(1024));
|
||||
return zlib.gzipSync(Buffer.concat(blocks), { level: 9 });
|
||||
}
|
||||
|
||||
/** The SHA-512 value that npm and pnpm record in a lock file. */
|
||||
export const integrity = data => 'sha512-' + createHash('sha512').update(data).digest('base64');
|
||||
|
||||
async function listFiles(folder, prefix = '') {
|
||||
const result = [];
|
||||
for (const entry of await fs.readdir(path.join(folder, prefix), { withFileTypes: true })) {
|
||||
const name = prefix ? `${prefix}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) result.push(...await listFiles(folder, name));
|
||||
else if (entry.isFile()) result.push(name);
|
||||
else throw Error('The SDK build contains a link or a special file: ' + name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Checks the preconditions and returns the release plan. Changes no file.
|
||||
export async function planSdkRelease(root, requestedVersion, env = process.env) {
|
||||
const next = releaseVersion(requestedVersion);
|
||||
/** @param {string} root @param {{ version: string, releaseUrl: string }} options */
|
||||
export async function planSdkRelease(root, { version, releaseUrl }) {
|
||||
const next = releaseVersion(version);
|
||||
const packageDir = path.join(root, sdkFolder);
|
||||
const sourceFile = path.join(packageDir, 'package.json');
|
||||
const source = JSON.parse(await fs.readFile(sourceFile, 'utf8'));
|
||||
@@ -65,101 +108,71 @@ export async function planSdkRelease(root, requestedVersion, env = process.env)
|
||||
if (!(await exists(path.join(packageDir, file)))) throw Error(`The SDK package has no ${file} file. Add ${path.join(sdkFolder, file)} before a release.`);
|
||||
}
|
||||
const copies = [];
|
||||
for (const file of releaseFiles) if (file !== 'dist' && file !== 'package.json' && await exists(path.join(packageDir, file))) copies.push(file);
|
||||
for (const file of packageFiles) if (await exists(path.join(packageDir, file))) copies.push(file);
|
||||
if ((await git(root, ['status', '--porcelain', '--untracked-files=all', '--', sdkFolder])) !== '') {
|
||||
throw Error(`${sdkFolder} has changes that are not committed. Commit them first, so that the release has a source commit.`);
|
||||
}
|
||||
const hostCommit = await git(root, ['rev-parse', 'HEAD']);
|
||||
|
||||
const clone = clonePath(root, env);
|
||||
if (!(await exists(clone))) throw Error(`The SDK repository clone is missing: ${clone}. Clone ${publicRepository} there, or set RUNESTONE_SDK_REPO.`);
|
||||
const top = await gitOptional(clone, ['rev-parse', '--show-toplevel']);
|
||||
if (!top || realpathSync.native(top) !== realpathSync.native(clone)) throw Error(`${clone} is not the root of a Git repository.`);
|
||||
if ((await git(clone, ['status', '--porcelain', '--untracked-files=all'])) !== '') throw Error(`The SDK repository clone has changes: ${clone}. Commit or remove them first.`);
|
||||
const branch = await gitOptional(clone, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
||||
if (!branch) throw Error(`The SDK repository clone is not on a branch: ${clone}.`);
|
||||
const head = await gitOptional(clone, ['rev-parse', '--verify', '--quiet', 'HEAD']);
|
||||
const tag = 'v' + next.version;
|
||||
if (await gitOptional(clone, ['rev-parse', '--verify', '--quiet', 'refs/tags/' + tag])) throw Error(`The tag ${tag} exists in ${clone}. A release never replaces a tag.`);
|
||||
const published = await fs.readFile(path.join(clone, 'package.json'), 'utf8').then(text => JSON.parse(text).version, () => null);
|
||||
if (published && compareReleases(next.version, published) <= 0) throw Error(`The SDK version must be greater than the version ${published} in the clone.`);
|
||||
const remotes = (await git(clone, ['remote'])).split(/\r?\n/).filter(Boolean);
|
||||
|
||||
const quoted = `"${clone}"`;
|
||||
const folder = new URL(releaseUrl.endsWith('/') ? releaseUrl : releaseUrl + '/');
|
||||
if (folder.protocol !== 'https:' || folder.username || folder.password || folder.search || folder.hash) {
|
||||
throw Error('Use an HTTPS release URL without credentials, a query, or a fragment.');
|
||||
}
|
||||
const file = packageFileName(packageName, next.version);
|
||||
const releaseDir = path.join(root, 'releases', 'plugin-sdk', next.version);
|
||||
const artifacts = { archive: path.join(releaseDir, file), metadata: path.join(releaseDir, 'sdk.json') };
|
||||
for (const artifact of Object.values(artifacts)) if (await exists(artifact)) throw Error('The release file already exists: ' + artifact);
|
||||
return {
|
||||
root, packageDir, sourceFile, source, current, next, clone, branch, head, tag, hostCommit, copies,
|
||||
root, packageDir, sourceFile, source, current, next, copies, file, releaseDir, artifacts,
|
||||
url: new URL(file, folder).href,
|
||||
hostCommit: await git(root, ['rev-parse', 'HEAD']),
|
||||
packageJson: releasePackageJson(source, next.version),
|
||||
commitMessage: `Release ${packageName} ${next.version}\n\nBuilt from RuneStone ${hostCommit}.`,
|
||||
pushCommands: [
|
||||
...(remotes.includes('origin') ? [] : [`git -C ${quoted} remote add origin ${publicRepository}`]),
|
||||
`git -C ${quoted} push origin ${branch}`,
|
||||
`git -C ${quoted} push origin ${tag}`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function describePlan(plan) {
|
||||
const relative = file => path.relative(plan.root, file);
|
||||
return [
|
||||
`SDK version: ${plan.next.version} (current ${plan.current.version})`,
|
||||
`Source: ${path.relative(plan.root, plan.packageDir) || '.'} at RuneStone ${plan.hostCommit}`,
|
||||
`Clone: ${plan.clone} (branch ${plan.branch}${plan.head ? '' : ', no commits'})`,
|
||||
`Source: ${relative(plan.packageDir) || '.'} at RuneStone ${plan.hostCommit}`,
|
||||
`1. Build ${sdkFolder}/dist.`,
|
||||
`2. Replace ${['dist', 'package.json', ...plan.copies].join(', ')} in the clone.`,
|
||||
`3. Commit "${plan.commitMessage.split('\n')[0]}" and create the tag ${plan.tag}.`,
|
||||
`4. Write the version ${plan.next.version} to ${sdkFolder}/package.json.`,
|
||||
'The script does not push. After the release, run:',
|
||||
...plan.pushCommands.map(command => ' ' + command),
|
||||
`2. Write ${relative(plan.artifacts.archive)} with dist, package.json, ${plan.copies.join(', ')}, and ${relative(plan.artifacts.metadata)}.`,
|
||||
`3. Write the version ${plan.next.version} to ${sdkFolder}/package.json.`,
|
||||
`Plugins then use: "${packageName}": "${plan.url}"`,
|
||||
'The script does not upload the file.',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
async function copyFolder(from, to) {
|
||||
await fs.mkdir(to, { recursive: true });
|
||||
for (const entry of await fs.readdir(from, { withFileTypes: true })) {
|
||||
const source = path.join(from, entry.name), target = path.join(to, entry.name);
|
||||
if (entry.isDirectory()) await copyFolder(source, target);
|
||||
else if (entry.isFile()) await fs.copyFile(source, target);
|
||||
else throw Error('The SDK build contains a link or a special file: ' + source);
|
||||
}
|
||||
}
|
||||
|
||||
// Puts the clone back to its state before the release. The clone was clean at the start, so this removes only release changes.
|
||||
async function restoreClone(plan, tagged) {
|
||||
const { clone, head, tag } = plan;
|
||||
if (tagged) await gitOptional(clone, ['tag', '-d', tag]);
|
||||
if (head) await gitOptional(clone, ['reset', '--quiet', '--hard', head]);
|
||||
else {
|
||||
await gitOptional(clone, ['update-ref', '-d', 'HEAD']);
|
||||
await gitOptional(clone, ['rm', '-r', '-q', '--cached', '--ignore-unmatch', '.']);
|
||||
}
|
||||
await gitOptional(clone, ['clean', '-f', '-d', '-q']);
|
||||
}
|
||||
|
||||
// Runs the release. build(root) returns the dist folder. The source version changes only when the tag exists.
|
||||
// Runs the release. build(root) returns the dist folder. The source version changes only when the release files exist.
|
||||
export async function runSdkRelease(plan, build = buildSdk) {
|
||||
const before = await fs.readFile(plan.sourceFile, 'utf8');
|
||||
let changedClone = false, tagged = false, complete = false;
|
||||
const written = [];
|
||||
let complete = false;
|
||||
try {
|
||||
const dist = await build(plan.root);
|
||||
for (const file of ['index.js', 'index.d.ts']) await fs.access(path.join(dist, file));
|
||||
changedClone = true;
|
||||
await fs.rm(path.join(plan.clone, 'dist'), { recursive: true, force: true });
|
||||
await copyFolder(dist, path.join(plan.clone, 'dist'));
|
||||
await fs.writeFile(path.join(plan.clone, 'package.json'), JSON.stringify(plan.packageJson, null, 2) + '\n');
|
||||
for (const file of plan.copies) await fs.copyFile(path.join(plan.packageDir, file), path.join(plan.clone, file));
|
||||
// -f adds the files also when a .gitignore file in the clone lists dist/.
|
||||
await git(plan.clone, ['add', '-A', '-f', '--', 'dist', 'package.json', ...plan.copies]);
|
||||
await git(plan.clone, ['commit', '--quiet', '-m', plan.commitMessage]);
|
||||
await git(plan.clone, ['tag', '-a', plan.tag, '-m', `${packageName} ${plan.next.version}`]);
|
||||
tagged = true;
|
||||
const entries = [{ name: 'package.json', data: Buffer.from(JSON.stringify(plan.packageJson, null, 2) + '\n') }];
|
||||
for (const file of plan.copies) entries.push({ name: file, data: await fs.readFile(path.join(plan.packageDir, file)) });
|
||||
for (const file of await listFiles(dist)) entries.push({ name: 'dist/' + file, data: await fs.readFile(path.join(dist, ...file.split('/'))) });
|
||||
const archive = packEntries(entries);
|
||||
await fs.mkdir(plan.releaseDir, { recursive: true });
|
||||
await fs.writeFile(plan.artifacts.archive, archive, { flag: 'wx' });
|
||||
written.push(plan.artifacts.archive);
|
||||
const metadata = {
|
||||
name: packageName, version: plan.next.version, file: plan.file, url: plan.url, bytes: archive.length,
|
||||
sha256: createHash('sha256').update(archive).digest('hex'), integrity: integrity(archive), source: plan.hostCommit,
|
||||
};
|
||||
await fs.writeFile(plan.artifacts.metadata, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
||||
written.push(plan.artifacts.metadata);
|
||||
await fs.writeFile(plan.sourceFile, before.replace(/("version":\s*")[^"]+(")/, `$1${plan.next.version}$2`));
|
||||
if (JSON.parse(await fs.readFile(plan.sourceFile, 'utf8')).version !== plan.next.version) throw Error('The SDK version field did not change.');
|
||||
complete = true;
|
||||
return { tag: plan.tag, commit: await git(plan.clone, ['rev-parse', 'HEAD']) };
|
||||
return { archive: plan.artifacts.archive, ...metadata };
|
||||
} finally {
|
||||
if (!complete) {
|
||||
if ((await fs.readFile(plan.sourceFile, 'utf8').catch(() => null)) !== before) await fs.writeFile(plan.sourceFile, before);
|
||||
if (changedClone) await restoreClone(plan, tagged);
|
||||
console.error('The SDK release did not complete. The version and the clone are restored.');
|
||||
// Only the files of this attempt go. A failed attempt does not use up the version.
|
||||
for (const file of written) await fs.rm(file, { force: true });
|
||||
await fs.rmdir(plan.releaseDir).catch(() => {});
|
||||
console.error('The SDK release did not complete. The version is restored, and the files of this attempt are removed.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,16 +180,16 @@ export async function runSdkRelease(plan, build = buildSdk) {
|
||||
async function main() {
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const options = parseArguments(process.argv.slice(2));
|
||||
const plan = await planSdkRelease(root, options.version);
|
||||
const plan = await planSdkRelease(root, options);
|
||||
console.log(describePlan(plan));
|
||||
if (options.dryRun) {
|
||||
console.log('Dry run: no file changed.');
|
||||
return;
|
||||
}
|
||||
const result = await runSdkRelease(plan);
|
||||
console.log(`\n${packageName} ${plan.next.version} is committed and tagged ${result.tag} (${result.commit}) in ${plan.clone}.`);
|
||||
console.log('Push the branch and the tag:');
|
||||
for (const command of plan.pushCommands) console.log(' ' + command);
|
||||
console.log(`\nSDK package: ${result.archive}\n${result.bytes} bytes, SHA-256 ${result.sha256}\nIntegrity: ${result.integrity}`);
|
||||
console.log(`Upload it to ${result.url}`);
|
||||
console.log(`Plugins use: "${packageName}": "${result.url}"`);
|
||||
console.log(`Then commit the new version in ${sdkFolder}/package.json in RuneStone.`);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user