2021-10-15 18:47:43 +02:00
|
|
|
import { toNative } from "./toNative";
|
2022-07-15 05:03:54 +02:00
|
|
|
import libarg from "arg";
|
2022-07-20 05:26:21 +02:00
|
|
|
import { ScriptArg } from "../Netscript/ScriptArg";
|
2022-08-09 21:41:47 +02:00
|
|
|
import { NetscriptContext } from "../Netscript/APIWrapper";
|
2021-10-15 18:47:43 +02:00
|
|
|
|
2022-07-20 05:26:21 +02:00
|
|
|
type FlagType = StringConstructor | NumberConstructor | BooleanConstructor | StringConstructor[];
|
|
|
|
type FlagsRet = { [key: string]: ScriptArg };
|
2022-08-09 21:41:47 +02:00
|
|
|
export function Flags(ctx: NetscriptContext | string[]): (data: unknown) => FlagsRet {
|
2022-08-10 00:08:04 +02:00
|
|
|
const vargs = Array.isArray(ctx) ? ctx : ctx.workerScript.args;
|
2022-08-09 21:41:47 +02:00
|
|
|
return (schema: unknown): FlagsRet => {
|
|
|
|
schema = toNative(schema);
|
|
|
|
if (!Array.isArray(schema)) throw new Error("flags schema passed in is invalid.");
|
|
|
|
const args: {
|
|
|
|
[key: string]: FlagType;
|
|
|
|
} = {};
|
2021-10-15 18:47:43 +02:00
|
|
|
|
2022-08-09 21:41:47 +02:00
|
|
|
for (const d of schema) {
|
|
|
|
let t: FlagType = String;
|
|
|
|
if (typeof d[1] === "number") {
|
|
|
|
t = Number;
|
|
|
|
} else if (typeof d[1] === "boolean") {
|
|
|
|
t = Boolean;
|
|
|
|
} else if (Array.isArray(d[1])) {
|
|
|
|
t = [String];
|
2021-10-15 18:47:43 +02:00
|
|
|
}
|
2022-08-09 21:41:47 +02:00
|
|
|
const numDashes = d[0].length > 1 ? 2 : 1;
|
|
|
|
args["-".repeat(numDashes) + d[0]] = t;
|
|
|
|
}
|
|
|
|
const ret: FlagsRet = libarg(args, { argv: vargs });
|
|
|
|
for (const d of schema) {
|
|
|
|
if (!ret.hasOwnProperty("--" + d[0]) || !ret.hasOwnProperty("-" + d[0])) ret[d[0]] = d[1];
|
|
|
|
}
|
|
|
|
for (const key of Object.keys(ret)) {
|
|
|
|
if (!key.startsWith("-")) continue;
|
|
|
|
const value = ret[key];
|
|
|
|
delete ret[key];
|
|
|
|
const numDashes = key.length === 2 ? 1 : 2;
|
|
|
|
ret[key.slice(numDashes)] = value;
|
|
|
|
}
|
|
|
|
return ret;
|
|
|
|
};
|
2021-10-15 18:47:43 +02:00
|
|
|
}
|