diff options
Diffstat (limited to 'u/process/argv.ts')
-rw-r--r-- | u/process/argv.ts | 42 |
1 files changed, 24 insertions, 18 deletions
diff --git a/u/process/argv.ts b/u/process/argv.ts index dcdba85..dca5098 100644 --- a/u/process/argv.ts +++ b/u/process/argv.ts @@ -1,4 +1,4 @@ -import { Either, type Mapper, type IEither } from '@emprespresso/pengueno'; +import { Either, type Mapper, type IEither, Optional } from '@emprespresso/pengueno'; export const isArgKey = <K extends string>(k: string): k is K => k.startsWith('--'); @@ -13,22 +13,27 @@ export const getArg = <K extends string, V>( argv: Array<string>, whenValue: ArgHandler<V>, ): IEither<Error, V> => { - const value = - argv - .filter((_argv) => isArgKey(_argv) && _argv.split('=')[0] === arg) - .map((_argv, i) => { - const next = _argv.includes('=') ? _argv.split('=')[1] : argv.at(i + 1); - if (next) { - if (isArgKey(next)) return whenValue.unspecified; - return whenValue.present(next); - } - return whenValue.unspecified; - }) - .find((x) => x) ?? whenValue.absent; - if (value === undefined) { - return Either.left(new Error('no value specified for ' + arg)); + const argIndex = Optional.from(argv.findIndex((_argv) => isArgKey(_argv) && _argv.split('=')[0] === arg)).filter( + (index) => index >= 0 && index < argv.length, + ); + if (!argIndex.present()) { + return Optional.from(whenValue.absent) + .map((v) => Either.right<Error, V>(v)) + .orSome(() => + Either.left( + new Error(`arg ${arg} is not present in arguments list and does not have an 'absent' value`), + ), + ) + .get(); } - return Either.right(value); + + return argIndex + .flatMap((idx) => + Optional.from(argv.at(idx)).map((_argv) => (_argv.includes('=') ? _argv.split('=')[1] : argv.at(idx + 1))), + ) + .map((next) => (isArgKey(next) ? whenValue.unspecified : whenValue.present(next))) + .map((v) => Either.right<Error, V>(<V>v)) + .get(); }; type MappedArgs< @@ -55,10 +60,10 @@ export const argv = < return getArg(arg, argv, handler).mapRight((value) => [arg, value] as const); }; - return args + const res = args .map(processArg) .reduce( - (acc: IEither<Error, Partial<Result>>, current: IEither<Error, readonly [Args[number], unknown]>) => + (acc: IEither<Error, Partial<Result>>, current: IEither<Error, [Args[number], unknown]>) => acc.flatMap((accValue) => current.mapRight(([key, value]) => ({ ...accValue, @@ -68,4 +73,5 @@ export const argv = < Either.right(<Partial<Result>>{}), ) .mapRight((result) => <Result>result); + return res; }; |