@thi.ng/args
Version:
Declarative, functional CLI argument/options parser, app framework, arg value coercions, multi/sub-commands, usage generation, error handling etc.
46 lines (45 loc) • 1.6 kB
JavaScript
import { isHex } from "@thi.ng/checks/is-hex";
import { isNumericFloat, isNumericInt } from "@thi.ng/checks/is-numeric";
import { illegalArgs } from "@thi.ng/errors/illegal-arguments";
import { Tuple } from "./api.js";
const coerceString = (x) => x;
const coerceFloat = (x) => isNumericFloat(x) ? parseFloat(x) : illegalArgs(`not a numeric value: ${x}`);
const coerceHexInt = (x) => isHex(x) ? parseInt(x, 16) : illegalArgs(`not a hex value: ${x}`);
const coerceInt = (x) => isNumericInt(x) ? parseInt(x) : illegalArgs(`not an integer: ${x}`);
const coerceJson = (x) => JSON.parse(x);
const coerceOneOf = (values) => (x) => values.includes(x) ? x : illegalArgs(`invalid option: ${x}`);
function coerceKV(delim = "=", strict = false, multi = false) {
return (pairs) => pairs.reduce((acc, x) => {
const idx = x.indexOf(delim);
strict && idx < 1 && illegalArgs(
`got '${x}', but expected a 'key${delim}value' pair`
);
if (idx > 0) {
const id = x.substring(0, idx);
const val = x.substring(idx + 1);
if (multi) {
acc[id] ? acc[id].push(val) : acc[id] = [val];
} else {
acc[id] = val;
}
} else {
acc[x] = multi ? ["true"] : "true";
}
return acc;
}, {});
}
const coerceTuple = (coerce, size, delim = ",") => (src) => {
const parts = src.split(delim);
parts.length !== size && illegalArgs(`got '${src}', but expected a tuple of ${size} values`);
return new Tuple(parts.map(coerce));
};
export {
coerceFloat,
coerceHexInt,
coerceInt,
coerceJson,
coerceKV,
coerceOneOf,
coerceString,
coerceTuple
};