@thi.ng/imago
Version:
JSON & API-based declarative and extensible image processing trees/pipelines
72 lines (71 loc) • 1.92 kB
JavaScript
import { isFunction } from "@thi.ng/checks";
import {
FMT_HH,
FMT_HHmmss_ALT,
FMT_MM,
FMT_dd,
FMT_mm,
FMT_ss,
FMT_ww,
FMT_yyyy,
FMT_yyyyMMdd_ALT
} from "@thi.ng/date";
import { illegalArgs as unsupported } from "@thi.ng/errors";
import { createHash } from "node:crypto";
import { basename, isAbsolute, join, resolve } from "node:path";
const _ = void 0;
const formatPath = (path, ctx, spec, buf) => {
path = path.replace(/\{(\w+)\}/g, (match, id) => {
const custom = ctx.opts.pathParts?.[id];
if (custom != null) {
return isFunction(custom) ? custom(ctx, spec, buf) : custom;
}
switch (id) {
case "name": {
!path && unsupported(
"cannot format `{name}`, image has no file source"
);
const name = basename(ctx.path);
const idx = name.lastIndexOf(".");
return idx > 0 ? name.substring(0, idx) : name;
}
case "sha1":
case "sha224":
case "sha256":
case "sha384":
case "sha512":
return createHash(id).update(buf).digest("hex").substring(0, 8);
case "w":
return String(ctx.size[0]);
case "h":
return String(ctx.size[1]);
case "aspect": {
const [w, h] = ctx.size;
return w > h ? "l" : w < h ? "p" : "sq";
}
case "date":
return FMT_yyyyMMdd_ALT(_, true);
case "time":
return FMT_HHmmss_ALT(_, true);
case "year":
return FMT_yyyy(_, true);
case "month":
return FMT_MM(_, true);
case "week":
return FMT_ww(_, true);
case "day":
return FMT_dd(_, true);
case "hour":
return FMT_HH(_, true);
case "minute":
return FMT_mm(_, true);
case "second":
return FMT_ss(_, true);
}
return match;
});
return isAbsolute(path) ? path : join(resolve(ctx.opts.outDir || "."), path);
};
export {
formatPath
};