mirror of
https://github.com/smogon/sprites.git
synced 2026-12-04 22:18:12 -06:00
`publish <file> --tree <dir> --meta <dir>` places the outputs itself: the tree is add-only (a name already there is touched, another size is refused), CAS objects are hardlinked in, __meta/ goes to its own directory with the links pointed into the tree, and __files/__digest record the publish. The deploy verb, deploy.json5, the manifest/tar negotiation with `smogonctl assets upload`, the progress bar and `run --tar` go with it; smogon.com's sprites-sync service runs build and publish on the server now. The output root is the served tree, no sprites/ prefix. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TNa8LzaaMo3QbEVuFUtFGU
473 lines
17 KiB
TypeScript
473 lines
17 KiB
TypeScript
|
|
import * as crypto from 'node:crypto';
|
|
import * as fs from 'node:fs/promises';
|
|
import * as os from 'node:os';
|
|
import * as nodePath from 'node:path';
|
|
import {fileURLToPath, pathToFileURL} from 'node:url';
|
|
import {parseArgs} from 'node:util';
|
|
|
|
import * as artifact from '../build/artifact.ts';
|
|
import {casPath} from '../build/cas.ts';
|
|
import {hashFile} from '../build/hash.ts';
|
|
import {loadConfig} from '../build/config.ts';
|
|
import {build} from '../build/driver.ts';
|
|
import {BuildError} from '../build/errors.ts';
|
|
import {killAllProcessGroups} from '../build/exec.ts';
|
|
import {setConfig} from '../build/helpers.ts';
|
|
import * as db from '../build/store.ts';
|
|
import * as api from './api.ts';
|
|
import {ActionQueue} from './queue.ts';
|
|
|
|
let root = nodePath.resolve(fileURLToPath(import.meta.url), '../../..');
|
|
let invocationCwd = process.cwd();
|
|
process.chdir(root);
|
|
|
|
let DB_PATH = '.build/db.sqlite';
|
|
let LOCK_PATH = '.build/lock.sqlite';
|
|
let CAS_DIR = '.build/cas';
|
|
let TMP_DIR = '.build/tmp';
|
|
let BASELINE_PATH = '.build/outputs.json';
|
|
|
|
type CommonOpts = {
|
|
jobs: string,
|
|
dryRun?: boolean,
|
|
failFast?: boolean,
|
|
config: string,
|
|
verbose?: boolean,
|
|
};
|
|
|
|
type VerbOpts = CommonOpts & {
|
|
output?: string,
|
|
link?: boolean,
|
|
record?: boolean,
|
|
tree?: string,
|
|
meta?: string,
|
|
};
|
|
|
|
let USAGE = `usage: node tools/deploy/index.ts <command> [options]
|
|
|
|
commands:
|
|
build [files...] build the rules of the given deploys (default: all *.build.ts)
|
|
run <file> -o <dir> build, finish, and materialize to a directory
|
|
publish <file> --tree <dir> --meta <dir>
|
|
build, finish, and place the outputs: the served tree gets
|
|
what it hasn't got, __meta/ is written whole to the meta
|
|
directory with its links pointing into the tree
|
|
inspect <paths...> -o <dir> build every rule touching the given source paths and copy
|
|
the outputs out
|
|
refactor [files...] report how the published files differ from the last
|
|
--record (default: all *.build.ts)
|
|
|
|
options:
|
|
-j, --jobs <n> number of parallel jobs (default: all cores)
|
|
-n, --dry-run print what would run without changing anything
|
|
--fail-fast stop scheduling new rules after the first failure
|
|
--config <file> config file (default: build.config)
|
|
-o, --output <dir> run/inspect: output directory
|
|
--tree <dir> publish: the served tree (add-only)
|
|
--meta <dir> publish: where __meta/ goes
|
|
--record refactor: overwrite the baseline instead of checking it
|
|
--link run: hardlink instead of copying
|
|
-v, --verbose print more detail
|
|
-h, --help show this help`;
|
|
|
|
let COMMON_OPTIONS = {
|
|
jobs: {type: 'string', short: 'j', default: String(os.availableParallelism())},
|
|
'dry-run': {type: 'boolean', short: 'n'},
|
|
'fail-fast': {type: 'boolean'},
|
|
config: {type: 'string', default: 'build.config'},
|
|
verbose: {type: 'boolean', short: 'v'},
|
|
help: {type: 'boolean', short: 'h'},
|
|
} as const;
|
|
|
|
let VERB_OPTIONS = {
|
|
build: {},
|
|
run: {
|
|
output: {type: 'string', short: 'o'},
|
|
link: {type: 'boolean'},
|
|
},
|
|
publish: {
|
|
tree: {type: 'string'},
|
|
meta: {type: 'string'},
|
|
},
|
|
inspect: {
|
|
output: {type: 'string', short: 'o'},
|
|
},
|
|
refactor: {
|
|
record: {type: 'boolean'},
|
|
},
|
|
} as const;
|
|
|
|
function requireOutput(opts: VerbOpts): string {
|
|
if (opts.output === undefined) {
|
|
throw new BuildError('missing -o/--output');
|
|
}
|
|
return opts.output;
|
|
}
|
|
|
|
async function discoverDeployFiles(): Promise<string[]> {
|
|
let files = (await fs.readdir('.')).filter(f => f.endsWith('.build.ts')).sort();
|
|
if (files.length === 0) {
|
|
throw new BuildError('No *.build.ts files at the repo root');
|
|
}
|
|
return files;
|
|
}
|
|
|
|
// Importing a deploy module declares its rules and registers its deploy
|
|
// blocks; the registry delta over each sequential import is that file's
|
|
// blocks.
|
|
async function importDeploys(files: string[]): Promise<Map<string, readonly api.DeployFn[]>> {
|
|
let specs = new Map<string, readonly api.DeployFn[]>();
|
|
for (let file of files) {
|
|
let before = api.getDeploys().length;
|
|
await import(pathToFileURL(nodePath.resolve(file)).href);
|
|
specs.set(file, api.getDeploys().slice(before));
|
|
}
|
|
return specs;
|
|
}
|
|
|
|
// Build `decls` and, on success, run `then` while still holding the lock (a
|
|
// concurrent GC must not sweep CAS objects out from under a finish). Returns
|
|
// the process exit code.
|
|
async function buildThen(decls: readonly artifact.RuleDecl[], opts: CommonOpts, gc: boolean,
|
|
then?: () => Promise<number>): Promise<number> {
|
|
let jobs = Number(opts.jobs);
|
|
if (!Number.isInteger(jobs) || jobs < 1) {
|
|
throw new BuildError(`Invalid --jobs value: ${opts.jobs}`);
|
|
}
|
|
let dryRun = Boolean(opts.dryRun);
|
|
let release = dryRun ? null : db.acquireLock(LOCK_PATH);
|
|
try {
|
|
// A dry run must not create state (opening a db migrates it);
|
|
// without a current-version db it reads from an empty in-memory one.
|
|
let dbPath = dryRun && db.dbVersion(DB_PATH) !== 2 ? ':memory:' : DB_PATH;
|
|
let store = new db.Store(dbPath);
|
|
if (!dryRun) {
|
|
await fs.rm(TMP_DIR, {recursive: true, force: true});
|
|
}
|
|
|
|
let ac = new AbortController();
|
|
let interrupted = false;
|
|
let onSignal = () => {
|
|
if (interrupted) {
|
|
killAllProcessGroups();
|
|
process.exit(130);
|
|
}
|
|
interrupted = true;
|
|
console.error('\nInterrupted; waiting for running rules to stop...');
|
|
ac.abort();
|
|
};
|
|
process.on('SIGINT', onSignal);
|
|
process.on('SIGTERM', onSignal);
|
|
let ok: boolean;
|
|
try {
|
|
let result = await build(decls, {
|
|
root,
|
|
store,
|
|
casDir: CAS_DIR,
|
|
tmpDir: TMP_DIR,
|
|
jobs,
|
|
dryRun,
|
|
failFast: Boolean(opts.failFast),
|
|
verbose: Boolean(opts.verbose),
|
|
gc,
|
|
signal: ac.signal,
|
|
});
|
|
ok = result.ok;
|
|
} finally {
|
|
process.off('SIGINT', onSignal);
|
|
process.off('SIGTERM', onSignal);
|
|
store.close();
|
|
}
|
|
if (interrupted) {
|
|
return 130;
|
|
}
|
|
if (dryRun) {
|
|
return 0;
|
|
}
|
|
if (!ok) {
|
|
return 1;
|
|
}
|
|
return then === undefined ? 0 : await then();
|
|
} finally {
|
|
release?.();
|
|
}
|
|
}
|
|
|
|
function finishOf(specs: Map<string, readonly api.DeployFn[]>, file: string): readonly api.DeployFn[] {
|
|
let fns = specs.get(file);
|
|
if (fns === undefined || fns.length === 0) {
|
|
throw new BuildError(`${file} registers no deploy blocks (use deploy())`);
|
|
}
|
|
return fns;
|
|
}
|
|
|
|
async function runFinish(fns: readonly api.DeployFn[], verbose: boolean): Promise<ActionQueue | null> {
|
|
let aq = new ActionQueue();
|
|
let ctx = api.makeCtx(CAS_DIR, aq);
|
|
for (let fn of fns) {
|
|
await fn(ctx);
|
|
}
|
|
if (!aq.valid) {
|
|
aq.print(verbose ? 'all' : 'errors');
|
|
return null;
|
|
}
|
|
return aq;
|
|
}
|
|
|
|
async function cmdBuild(files: string[], opts: CommonOpts): Promise<void> {
|
|
setConfig(await loadConfig(opts.config));
|
|
// GC needs the full rule universe: only an unfiltered union build
|
|
// can know which keys are no longer declared anywhere.
|
|
let gc = files.length === 0 && !Boolean(opts.dryRun);
|
|
await importDeploys(files.length > 0 ? files : await discoverDeployFiles());
|
|
process.exitCode = await buildThen(artifact.getDecls(), opts, gc);
|
|
}
|
|
|
|
async function cmdRun(file: string, opts: VerbOpts): Promise<void> {
|
|
let output = requireOutput(opts);
|
|
setConfig(await loadConfig(opts.config));
|
|
let specs = await importDeploys([file]);
|
|
process.exitCode = await buildThen(artifact.getDecls(), opts, false, async () => {
|
|
let aq = await runFinish(finishOf(specs, file), Boolean(opts.verbose));
|
|
if (aq === null) {
|
|
return 1;
|
|
}
|
|
await aq.run(output, opts.link ? 'link' : 'copy');
|
|
return 0;
|
|
});
|
|
}
|
|
|
|
// What the publish stands for as one string: the sorted name -> digest map,
|
|
// so two publishes of the same bytes under the same names compare equal
|
|
// whatever built them.
|
|
function digestOf(outputs: Map<string, string>): string {
|
|
let h = crypto.createHash('sha256');
|
|
for (let [dst, digest] of [...outputs].sort((a, b) => a[0] < b[0] ? -1 : 1)) {
|
|
h.update(`${dst}\0${digest}\n`);
|
|
}
|
|
return h.digest('hex');
|
|
}
|
|
|
|
async function cmdPublish(file: string, opts: VerbOpts): Promise<void> {
|
|
let {tree, meta} = opts;
|
|
if (tree === undefined || meta === undefined) {
|
|
throw new BuildError('publish needs --tree and --meta');
|
|
}
|
|
setConfig(await loadConfig(opts.config));
|
|
let specs = await importDeploys([file]);
|
|
process.exitCode = await buildThen(artifact.getDecls(), opts, false, async () => {
|
|
let aq = await runFinish(finishOf(specs, file), Boolean(opts.verbose));
|
|
if (aq === null) {
|
|
return 1;
|
|
}
|
|
let {files, placed, kept} = await aq.publish(tree, meta, digestOf(await outputs(aq)));
|
|
console.log(`published ${files} files: ${placed} new, ${kept} already there`);
|
|
return 0;
|
|
});
|
|
}
|
|
|
|
// What a deploy publishes: the digest of the bytes landing at each name.
|
|
// tup's `refactor` checked that a Tupfile edit left the build graph alone;
|
|
// this checks the same thing one layer out, over the names and bytes the
|
|
// deploy blocks decide, which is where a rename or a lost alias shows up.
|
|
//
|
|
// node tools/deploy/index.ts refactor --record # before the change
|
|
// node tools/deploy/index.ts refactor # after it
|
|
//
|
|
// The baseline lives in .build/ beside the rest of the build state, so it is
|
|
// per-checkout and never committed.
|
|
async function outputs(aq: ActionQueue): Promise<Map<string, string>> {
|
|
let out = new Map<string, string>();
|
|
for (let e of aq.log) {
|
|
if (e.type !== 'Op') continue;
|
|
if (e.op.type === 'Write') {
|
|
out.set(e.dst, crypto.createHash('sha256').update(e.op.data).digest('hex'));
|
|
continue;
|
|
}
|
|
// A link has no bytes; what it publishes is the name it points at, so
|
|
// that is what a retarget has to show up as.
|
|
if (e.op.type === 'Symlink') {
|
|
out.set(e.dst, `symlink:${e.op.target}`);
|
|
continue;
|
|
}
|
|
// A CAS path spells its own digest, so only raw sources are read.
|
|
let cas = new RegExp(`^${CAS_DIR}/[0-9a-f]{2}/([0-9a-f]{64})\\.`).exec(e.op.src);
|
|
out.set(e.dst, cas ? cas[1]! : (await hashFile(e.op.src)).toString('hex'));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function diffOutputs(was: Record<string, string>, now: Map<string, string>): string[] {
|
|
let lines = [];
|
|
for (let [dst, digest] of now) {
|
|
let before = was[dst];
|
|
if (before === undefined) {
|
|
lines.push(`+ ${dst}`);
|
|
} else if (before !== digest) {
|
|
lines.push(`M ${dst}`);
|
|
}
|
|
}
|
|
for (let dst of Object.keys(was)) {
|
|
if (!now.has(dst)) {
|
|
lines.push(`- ${dst}`);
|
|
}
|
|
}
|
|
return lines.sort((a, b) => a.slice(2) < b.slice(2) ? -1 : 1);
|
|
}
|
|
|
|
async function cmdRefactor(files: string[], opts: VerbOpts): Promise<void> {
|
|
setConfig(await loadConfig(opts.config));
|
|
let deployFiles = files.length > 0 ? files : await discoverDeployFiles();
|
|
let specs = await importDeploys(deployFiles);
|
|
let baseline: Record<string, Record<string, string>> = {};
|
|
try {
|
|
baseline = JSON.parse(await fs.readFile(BASELINE_PATH, 'utf8')) as typeof baseline;
|
|
} catch {
|
|
// No baseline yet; every file below records one.
|
|
}
|
|
process.exitCode = await buildThen(artifact.getDecls(), opts, false, async () => {
|
|
let changed = false;
|
|
for (let file of deployFiles) {
|
|
let aq = await runFinish(finishOf(specs, file), Boolean(opts.verbose));
|
|
if (aq === null) {
|
|
return 1;
|
|
}
|
|
let now = await outputs(aq);
|
|
let was = baseline[file];
|
|
if (opts.record || was === undefined) {
|
|
console.log(`${file}: recorded ${now.size} files${was === undefined && !opts.record ? ' (no baseline)' : ''}`);
|
|
} else {
|
|
let lines = diffOutputs(was, now);
|
|
console.log(`${file}: ${now.size} files, ${lines.length} changed`);
|
|
for (let line of lines) {
|
|
console.log(` ${line}`);
|
|
}
|
|
changed ||= lines.length > 0;
|
|
continue;
|
|
}
|
|
baseline[file] = Object.fromEntries([...now].sort((a, b) => a[0] < b[0] ? -1 : 1));
|
|
}
|
|
if (opts.record || Object.keys(baseline).length > 0) {
|
|
await fs.mkdir(nodePath.dirname(BASELINE_PATH), {recursive: true});
|
|
await fs.writeFile(BASELINE_PATH, JSON.stringify(baseline, null, 4) + '\n');
|
|
}
|
|
return changed ? 1 : 0;
|
|
});
|
|
}
|
|
|
|
function slugOf(decl: artifact.RuleDecl): string {
|
|
let template = decl.displayTemplate ?? decl.cmds[0] ?? '';
|
|
let slug = template.replace(/%[a-zA-Z0-9]+/g, ' ')
|
|
.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
return slug === '' ? 'rule' : slug;
|
|
}
|
|
|
|
async function cmdInspect(paths: string[], opts: VerbOpts): Promise<void> {
|
|
let output = requireOutput(opts);
|
|
setConfig(await loadConfig(opts.config));
|
|
await importDeploys(await discoverDeployFiles());
|
|
// Accept absolute paths and paths relative to where the user ran the
|
|
// command; rules declare repo-root-relative paths.
|
|
let targets = paths.map(p => {
|
|
let target = nodePath.relative(root, nodePath.resolve(invocationCwd, p));
|
|
if (target.startsWith('..')) {
|
|
throw new BuildError(`Not under the repo root: ${p}`);
|
|
}
|
|
return target;
|
|
});
|
|
|
|
let decls = artifact.getDecls().filter(decl =>
|
|
[...decl.inputs, ...decl.deps].some(i => targets.some(t => i === t || i.startsWith(t + '/'))));
|
|
if (decls.length === 0) {
|
|
throw new BuildError(`No rules consume: ${targets.join(' ')}`);
|
|
}
|
|
console.log(`inspect: ${decls.length} rules`);
|
|
let exists = (p: string) => fs.access(p).then(() => true, () => false);
|
|
process.exitCode = await buildThen(decls, opts, false, async () => {
|
|
for (let decl of decls) {
|
|
let dir = nodePath.join(output, slugOf(decl));
|
|
await fs.mkdir(dir, {recursive: true});
|
|
for (let artifact of decl.outputs) {
|
|
let dst = nodePath.join(dir, artifact.filename);
|
|
for (let n = 2; await exists(dst); n++) {
|
|
dst = nodePath.join(dir, `${artifact.name}-${n}.${artifact.ext}`);
|
|
}
|
|
await fs.copyFile(casPath(CAS_DIR, artifact.hash, artifact.ext), dst);
|
|
await fs.chmod(dst, 0o644);
|
|
console.log(`${nodePath.relative(output, dst)}`);
|
|
}
|
|
}
|
|
return 0;
|
|
});
|
|
}
|
|
|
|
async function main(argv: string[]): Promise<void> {
|
|
let [verb, ...rest] = argv;
|
|
if (verb === undefined || verb === '-h' || verb === '--help') {
|
|
console.log(USAGE);
|
|
return;
|
|
}
|
|
if (!(verb in VERB_OPTIONS)) {
|
|
throw new BuildError(`Unknown command: ${verb} (-h for usage)`);
|
|
}
|
|
let parsed;
|
|
try {
|
|
parsed = parseArgs({
|
|
args: rest,
|
|
options: {...COMMON_OPTIONS, ...VERB_OPTIONS[verb as keyof typeof VERB_OPTIONS]},
|
|
allowPositionals: true,
|
|
});
|
|
} catch (err) {
|
|
throw new BuildError(`${(err as Error).message.split('\n')[0]} (-h for usage)`);
|
|
}
|
|
let v = parsed.values as {[k: string]: string | boolean | undefined};
|
|
let positionals = parsed.positionals;
|
|
if (v.help) {
|
|
console.log(USAGE);
|
|
return;
|
|
}
|
|
let opts: VerbOpts = {
|
|
jobs: v.jobs as string,
|
|
dryRun: Boolean(v['dry-run']),
|
|
failFast: Boolean(v['fail-fast']),
|
|
config: v.config as string,
|
|
verbose: Boolean(v.verbose),
|
|
output: v.output as string | undefined,
|
|
link: Boolean(v.link),
|
|
record: Boolean(v.record),
|
|
tree: v.tree as string | undefined,
|
|
meta: v.meta as string | undefined,
|
|
};
|
|
switch (verb) {
|
|
case 'build':
|
|
return cmdBuild(positionals, opts);
|
|
case 'run':
|
|
case 'publish': {
|
|
let [file, ...extra] = positionals;
|
|
if (file === undefined || extra.length > 0) {
|
|
throw new BuildError(`${verb} takes exactly one deploy file`);
|
|
}
|
|
return verb === 'run' ? cmdRun(file, opts) : cmdPublish(file, opts);
|
|
}
|
|
case 'inspect':
|
|
if (positionals.length === 0) {
|
|
throw new BuildError('inspect takes at least one source path');
|
|
}
|
|
return cmdInspect(positionals, opts);
|
|
case 'refactor':
|
|
return cmdRefactor(positionals, opts);
|
|
}
|
|
}
|
|
|
|
try {
|
|
await main(process.argv.slice(2));
|
|
} catch (err) {
|
|
if (err instanceof BuildError) {
|
|
console.error(err.message);
|
|
process.exitCode = 1;
|
|
} else {
|
|
throw err;
|
|
}
|
|
}
|