Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/Schniz/cmd-ts. 💻 A type-driven command line argument parser cmd-ts.now.sh
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235import chalk from "chalk";import * as Result from "./Result";import type { ArgParser, ParseContext, ParsingResult, Register,} from "./argparser";import type { Default, OnMissing } from "./default";import type { Descriptive, EnvDoc, LongDoc, ProvidesHelp, ShortDoc,} from "./helpdoc";import { findOption } from "./newparser/findOption";import { type HasType, type OutputOf, type Type, extendType } from "./type";import { boolean as booleanIdentity } from "./types";import type { AllOrNothing } from "./utils";
type FlagConfig<Decoder extends Type<boolean, any>> = LongDoc & HasType<Decoder> & Partial<ShortDoc & Descriptive & EnvDoc & OnMissing<OutputOf<Decoder>>> & AllOrNothing<Default<OutputOf<Decoder>>>;
/** * A decoder from `string` to `boolean` * works for `true` and `false` only. */export const boolean: Type<string, boolean> = { async from(str) { if (str === "true") return true; if (str === "false") return false; throw new Error( `expected value to be either "true" or "false". got: "${str}"`, ); }, displayName: "true/false", defaultValue: () => false,};
export function fullFlag<Decoder extends Type<boolean, any>>( config: FlagConfig<Decoder>,): ArgParser<OutputOf<Decoder>> & ProvidesHelp & Register & Partial<Descriptive> { const decoder = extendType(boolean, config.type);
return { description: config.description ?? config.type.description, helpTopics() { let usage = `--${config.long}`; if (config.short) { usage += `, -${config.short}`; } const defaults: string[] = [];
if (config.env) { const env = process.env[config.env] === undefined ? "" : `=${chalk.italic(process.env[config.env])}`; defaults.push(`env: ${config.env}${env}`); }
if (config.defaultValue) { try { const defaultValue = config.defaultValue(); if (config.defaultValueIsSerializable) { defaults.push(`default: ${chalk.italic(defaultValue)}`); } else { defaults.push("optional"); } } catch (e) {} } else if (config.type.defaultValue) { try { const defaultValue = config.type.defaultValue(); if (config.type.defaultValueIsSerializable) { defaults.push(`default: ${chalk.italic(defaultValue)}`); } else { defaults.push("optional"); } } catch (e) {} } else if (config.onMissing || config.type.onMissing) { defaults.push("optional"); }
return [ { category: "flags", usage, defaults, description: config.description ?? config.type.description ?? "self explanatory", }, ]; }, register(opts) { opts.forceFlagLongNames.add(config.long); if (config.short) { opts.forceFlagShortNames.add(config.short); } }, async parse({ nodes, visitedNodes, }: ParseContext): Promise<ParsingResult<OutputOf<Decoder>>> { const options = findOption(nodes, { longNames: [config.long], shortNames: config.short ? [config.short] : [], }).filter((x) => !visitedNodes.has(x)); options.forEach((opt) => visitedNodes.add(opt));
if (options.length > 1) { return Result.err({ errors: [ { nodes: options, message: `Expected 1 occurence, got ${options.length}`, }, ], }); }
const valueFromEnv = config.env ? process.env[config.env] : undefined; const onMissingFn = config.onMissing || config.type.onMissing;
let rawValue: string; let envPrefix = "";
if (options.length === 0 && valueFromEnv !== undefined) { rawValue = valueFromEnv; envPrefix = `env[${chalk.italic(config.env)}]: `; } else if (options.length === 0 && config.defaultValue) { try { const defaultValue = config.defaultValue(); return Result.ok(defaultValue); } catch (e: any) { const message = `Default value not found for '--${config.long}': ${e.message}`; return Result.err({ errors: [{ message, nodes: [] }], }); } } else if (options.length === 0 && onMissingFn) { try { const missingValue = await onMissingFn(); return Result.ok(missingValue); } catch (e: any) { const message = `Failed to get missing value for '--${config.long}': ${e.message}`; return Result.err({ errors: [{ message, nodes: [] }], }); } } else if (options.length === 0 && config.type.defaultValue) { try { const defaultValue = config.type.defaultValue(); return Result.ok(defaultValue); } catch (e: any) { const message = `Default value not found for '--${config.long}': ${e.message}`; return Result.err({ errors: [{ message, nodes: [] }], }); } } else if (options.length === 1) { rawValue = options[0].value?.node.raw ?? "true"; } else { return Result.err({ errors: [ { nodes: [], message: `No value provided for --${config.long}` }, ], }); }
const decoded = await Result.safeAsync(decoder.from(rawValue));
if (Result.isErr(decoded)) { return Result.err({ errors: [ { nodes: options, message: envPrefix + decoded.error.message, }, ], }); }
return decoded; }, };}
type BooleanType = Type<boolean, boolean>;
/** * Decodes an argument which is in the form of a key and a boolean value, and allows parsing the following ways: * * - `--long` where `long` is the provided `long` * - `-s=value` where `s` is the provided `short` * Shorthand forms can be combined: * - `-abcd` will call all flags for the short forms of `a`, `b`, `c` and `d`. * @param config flag configurations */export function flag<Decoder extends Type<boolean, any>>( config: FlagConfig<Decoder>,): ArgParser<OutputOf<Decoder>> & ProvidesHelp & Register & Partial<Descriptive>;export function flag( config: LongDoc & Partial< HasType<never> & ShortDoc & Descriptive & EnvDoc & OnMissing<OutputOf<BooleanType>> > & AllOrNothing<Default<OutputOf<BooleanType>>>,): ArgParser<OutputOf<BooleanType>> & ProvidesHelp & Register & Partial<Descriptive>;export function flag( config: LongDoc & Partial<HasType<any> & ShortDoc & Descriptive & EnvDoc> & AllOrNothing<Default<OutputOf<any>>>,): ArgParser<OutputOf<any>> & ProvidesHelp & Register & Partial<Descriptive> { return fullFlag({ type: booleanIdentity, ...config, });}