Files
sprites/tools/build/subst.ts
Christopher Monsanto b8d7aa50eb Replace non-null assertions with explicit checks
Parsers use charAt or check-and-throw; the executor gets a paired()
helper for its parallel arrays; matchSubsets returns {entry, matched}
pairs so the deploy loop stops indexing two arrays; spawn stdin and
pid get real guards.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 01:13:15 -04:00

53 lines
2.0 KiB
TypeScript

import * as pathlib from 'node:path';
// A command spec entry: a shell command string, or an arbitrarily nested list
// of them (flattened, like the Lua flatten()).
export type Cmd = string | Cmd[];
export function flattenCmds(cmds: Cmd): string[] {
if (typeof cmds === 'string') {
let trimmed = cmds.trim();
return trimmed === '' ? [] : [trimmed];
}
return cmds.flatMap(flattenCmds);
}
export function basenameNoExt(path: string): string {
let base = pathlib.basename(path);
let dot = base.lastIndexOf('.');
return dot > 0 ? base.slice(0, dot) : base;
}
// Expand only the name substitutions (%b/%B). They are static per rule, so
// declarations expand them eagerly; %f/%o/%oN wait for execution, when
// concrete paths exist.
export function substituteNames(s: string, inputs: string[]): string {
return s.replace(/%([bB])/g, (_, c: string) =>
c === 'b' ? inputs.map(p => pathlib.basename(p)).join(' ')
: inputs.map(basenameNoExt).join(' '));
}
// Tup-style substitutions:
// %f inputs, space-joined %b input basenames
// %o outputs, space-joined %B input basenames without extension
// %oN (1-based) a single output, for rules with several
export function substitute(s: string, inputs: string[], outputs: string[]): string {
return s.replace(/%o(\d+)|%([a-zA-Z])/g, (match, n: string | undefined, c: string | undefined) => {
if (n !== undefined) {
let out = outputs[Number(n) - 1];
if (out === undefined) {
throw new Error(`Output index out of range (${outputs.length} outputs): ${match} in: ${s}`);
}
return out;
}
switch (c) {
case 'f': return inputs.join(' ');
case 'o': return outputs.join(' ');
case 'b': return inputs.map(p => pathlib.basename(p)).join(' ');
case 'B': return inputs.map(basenameNoExt).join(' ');
default: throw new Error(`Unknown substitution ${match} in: ${s}`);
}
});
}