bitburner-src/src/NetscriptFunctions/Flags.ts

42 lines
1.4 KiB
TypeScript
Raw Normal View History

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";
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 };
export function Flags(vargs: string[]): () => (data: unknown) => FlagsRet {
return (/* ctx: NetscriptContext */) =>
(schema: unknown): FlagsRet => {
schema = toNative(schema);
if (!Array.isArray(schema)) throw new Error("flags schema passed in is invalid.");
2022-05-25 17:10:25 +02:00
const args: {
2022-07-20 05:26:21 +02:00
[key: string]: FlagType;
2022-05-25 17:10:25 +02:00
} = {};
2021-10-15 18:47:43 +02:00
2022-07-20 05:26:21 +02:00
for (const d of schema) {
let t: FlagType = String;
2022-05-25 17:10:25 +02:00
if (typeof d[1] === "number") {
t = Number;
} else if (typeof d[1] === "boolean") {
t = Boolean;
} else if (Array.isArray(d[1])) {
t = [String];
}
const numDashes = d[0].length > 1 ? 2 : 1;
args["-".repeat(numDashes) + d[0]] = t;
2021-10-15 18:47:43 +02:00
}
2022-07-20 05:26:21 +02:00
const ret: FlagsRet = libarg(args, { argv: vargs });
for (const d of schema) {
2022-05-25 17:10:25 +02:00
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
}