From 373d9ec700c0097a22cf665a8e33cf48998d1dc2 Mon Sep 17 00:00:00 2001 From: Elizabeth Date: Mon, 2 Jun 2025 11:14:52 -0700 Subject: Minor things --- u/process/argv.ts | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ u/process/mod.ts | 1 + 2 files changed, 66 insertions(+) create mode 100644 u/process/argv.ts (limited to 'u/process') diff --git a/u/process/argv.ts b/u/process/argv.ts new file mode 100644 index 0000000..657c9a7 --- /dev/null +++ b/u/process/argv.ts @@ -0,0 +1,65 @@ +import { Either, type IEither } from "@emprespresso/pengueno"; + +export const isArgKey = (k: string): k is K => + k.startsWith("--"); + +export const getArg = ( + arg: K, + args: Array, +): IEither => { + const result = args.findIndex((_arg) => _arg.startsWith(arg)); + if (result < 0) return Either.left(new Error("no argument found for " + arg)); + const [resultArg, next]: Array = [ + args[result], + args.at(result + 1), + ]; + if (resultArg && resultArg.includes("=")) { + return Either.right(resultArg.split("=")[1] as V); + } + if (typeof next === "undefined") + return Either.left(new Error("no value specified for " + arg)); + if (isArgKey(next)) + return Either.left( + new Error("next value for arg " + arg + " is another arg " + next), + ); + return Either.right(next as V); +}; + +type ObjectFromList, V = string> = { + [K in T extends ReadonlyArray ? U : never]: V; +}; +export const argv = ( + args: ReadonlyArray, + defaultArgs?: Partial>, + argv = Deno.args, +) => { + return args + .map((arg) => [arg, getArg(arg, argv)] as [K, IEither]) + .map(([arg, specified]): [K, IEither] => [ + arg, + specified.fold((e, val) => { + const hasDefaultVal = e && defaultArgs && arg in defaultArgs; + if (hasDefaultVal) { + return Either.right(defaultArgs[arg]!); + } else if (!val || e) { + return Either.left(e ?? new Error("unknown")); + } + return Either.right(val); + }), + ]) + .reduce( + ( + acc: IEither>, + x: [K, IEither], + ): IEither> => { + const [arg, eitherVal] = x; + return acc.flatMap((args) => { + return eitherVal.mapRight((envValue) => ({ + ...args, + [arg]: envValue, + })); + }); + }, + Either.right({} as ObjectFromList), + ); +}; diff --git a/u/process/mod.ts b/u/process/mod.ts index 3f02d46..211e9a7 100644 --- a/u/process/mod.ts +++ b/u/process/mod.ts @@ -1,3 +1,4 @@ export * from "./env.ts"; export * from "./run.ts"; export * from "./validate_identifier.ts"; +export * from "./argv.ts"; -- cgit v1.2.3-70-g09d2