Files
sprites/tools/build/helpers.ts
Christopher Monsanto c9117ac5af Call magick by its own name, and stop gifsicle narrating
`magick convert` is ImageMagick 7 running its 6 compatibility entry point,
which since 7.1.1 prints a deprecation warning on every invocation. The build
runs it about eleven thousand times, so a deploy is eleven thousand lines of
it, and the one warning worth reading -- gifsicle's, when a rule hands it more
colors than a global colormap holds -- is buried in them. Drop `convert` and
give gifsicle -w.

Neither is a free rename: v7 semantics differ from the compatibility mode's,
and gifsicle's rule identity is its command line, so the -w rebuilds every gif
in the tree. `refactor --record` before and `refactor` after says 21847 files,
0 changed, so nothing published moves and no upload follows this.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 20:50:36 -04:00

146 lines
4.8 KiB
TypeScript

import * as fs from 'node:fs';
import * as pathlib from 'node:path';
import type {Artifact} from './artifact.ts';
import {type Cmd, basenameNoExt} from './subst.ts';
let config = new Map<string, string>();
export function setConfig(cfg: Map<string, string>): void {
config = cfg;
}
export function getconfig(name: string): string | undefined {
let value = config.get(name);
return value === '' ? undefined : value;
}
export function astable(x: string | readonly string[] | undefined): string[] {
if (x === undefined) {
return [];
}
return typeof x === 'string' ? [x] : [...x];
}
// Single-directory, single-'*' glob (all Tupfile patterns were of this form).
// Non-glob strings pass through literally; existence is checked at hash time.
// Results are sorted within a pattern; declared order is preserved across
// patterns (some rules, e.g. the pokeball sheet, are input-order-sensitive).
function globOne(pat: string): string[] {
if (!pat.includes('*')) {
return [pat];
}
let dir = pathlib.dirname(pat);
let base = pathlib.basename(pat);
if (dir.includes('*') || base.indexOf('*') !== base.lastIndexOf('*')) {
throw new Error(`Unsupported glob pattern: ${pat}`);
}
let [prefix, suffix] = base.split('*') as [string, string];
let results = [];
for (let ent of fs.readdirSync(dir, {withFileTypes: true})) {
if (!ent.isFile() && !ent.isSymbolicLink()) {
continue;
}
let name = ent.name;
if (name.startsWith('.')) {
continue; // tup.glob ignored dotfiles
}
if (name.length >= prefix.length + suffix.length
&& name.startsWith(prefix) && name.endsWith(suffix)) {
results.push(dir === '.' ? name : `${dir}/${name}`);
}
}
results.sort();
return results;
}
export function glob(pats: string | string[]): string[] {
return astable(pats).flatMap(globOne);
}
// tup.base: basename without directory or final extension. For an artifact,
// its nominal name.
export function base(x: string | Artifact): string {
return typeof x === 'string' ? basenameNoExt(x) : x.name;
}
export type SpriteData = {
id: string,
data: Record<string, string | true>,
};
// Port of util/sprites.lua spritedata. Lua used gmatch("[^-]+"), which skips
// empty segments, hence the filter.
export function spritedata(basename: string): SpriteData {
let parts = basename.split('-').filter(p => p !== '');
let data: Record<string, string | true> = {};
for (let part of parts.slice(1)) {
if (part.length === 1) {
data[part] = true;
} else {
data[part.charAt(0)] = part.slice(1);
}
}
return {id: parts[0] ?? '', data};
}
export function spriteglob(pats: string | string[], flagspec?: Record<string, unknown>): string[] {
return glob(pats).filter(filename => {
let sd = spritedata(base(filename));
for (let [k, v] of Object.entries(flagspec ?? {})) {
if (Boolean(v) !== Boolean(sd.data[k])) {
return false;
}
}
return true;
});
}
// PNG date/time tEXt chunks make magick output nondeterministic, which would
// churn every content-addressed name on a rebuild.
export let PNG_DETERMINISTIC = '-define png:exclude-chunks=date,time';
export function pad(opts: {w: number, h: number, input?: string, output?: string}): string {
let input = opts.input ?? '%f';
let output = opts.output ?? '%o';
return `magick ${input} ${PNG_DETERMINISTIC} -background transparent -gravity center -extent ${opts.w}x${opts.h} ${output}`;
}
export function trimimg(opts: {input?: string, output?: string} = {}): string {
return `magick ${opts.input ?? '%f'} ${PNG_DETERMINISTIC} -trim ${opts.output ?? '%o'}`;
}
type CompressOpts = {
pngquant?: string,
optipng?: string,
advpng?: string,
};
function compressopts(program: string, copts: CompressOpts): void {
copts.pngquant = getconfig(`${program}_PNGQUANT`) ?? copts.pngquant;
copts.optipng = getconfig(`${program}_OPTIPNG`) ?? copts.optipng;
copts.advpng = getconfig(`${program}_ADVPNG`) ?? copts.advpng;
}
export function compresspng(opts: {config?: string, output?: string} = {}): Cmd[] {
let output = opts.output ?? '%o';
let copts: CompressOpts = {};
compressopts('DEFAULT', copts);
if (opts.config) {
compressopts(opts.config, copts);
}
let cmds = [];
if (copts.pngquant !== undefined) {
// -f -o necessary to overwrite existing file
cmds.push(`pngquant -f -o ${output} ${copts.pngquant} ${output}`);
}
if (copts.optipng !== undefined) {
cmds.push(`optipng -q ${copts.optipng} ${output}`);
}
if (copts.advpng !== undefined) {
cmds.push(`advpng -q ${copts.advpng} ${output}`);
}
return cmds;
}