// Releases the plugin SDK into a local clone of its public repository. See docs/releases.md#sdk-releases. // Usage: node scripts/releaseSdk.mjs --version [--dry-run] // The script commits and tags in the clone. It never pushes. It prints the push commands. import fs from 'node:fs/promises'; import path from 'node:path'; import { execFile } from 'node:child_process'; import { realpathSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; 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']; export function parseArguments(args) { const options = { version: 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.'); } if (!options.version) throw Error('Use --version followed by the SDK version, for example --version 0.1.0.'); return options; } // Runs git in a folder and returns its output without the final line break. Rejects when git fails. export function git(cwd, args) { return new Promise((resolve, reject) => { execFile('git', ['-C', cwd, ...args], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => { if (error) reject(Error(`git ${args.join(' ')} failed in ${cwd}: ${String(stderr || error.message).trim()}`)); else resolve(stdout.replace(/\r?\n$/, '')); }); }); } 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) { const { scripts, devDependencies, ...rest } = source; const result = { ...rest, version }; for (const field of ['types', 'exports', 'files', 'license']) if (!result[field]) throw Error(`The SDK package.json has no "${field}" field.`); 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); const packageDir = path.join(root, sdkFolder); const sourceFile = path.join(packageDir, 'package.json'); const source = JSON.parse(await fs.readFile(sourceFile, 'utf8')); if (source.name !== packageName) throw Error(`${sourceFile} is not the ${packageName} package.`); const current = releaseVersion(source.version); if (compareReleases(next.version, current.version) <= 0) throw Error(`The SDK version must be greater than the current version ${current.version}.`); for (const file of ['README.md', 'LICENSE']) { 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); 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}"`; return { root, packageDir, sourceFile, source, current, next, clone, branch, head, tag, hostCommit, copies, 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) { 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'})`, `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), ].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. export async function runSdkRelease(plan, build = buildSdk) { const before = await fs.readFile(plan.sourceFile, 'utf8'); let changedClone = false, tagged = false, 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; 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']) }; } 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.'); } } } 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); 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(`Then commit the new version in ${sdkFolder}/package.json in RuneStone.`); } if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) { try { await main(); } catch (error) { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; } }