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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218import chalk from "chalk";import didYouMean from "didyoumean";import * as Result from "./Result";// import { Runner, Into } from './runner';import type { ArgParser, ParseContext, ParsingInto, ParsingResult,} from "./argparser";import { createCircuitBreaker, handleCircuitBreaker } from "./circuitbreaker";import type { From } from "./from";import { type Example, type SubcommandsHelpData, getHelpFormatter,} from "./helpFormatter";import type { Aliased, Descriptive, Named, ProvidesHelp, Versioned,} from "./helpdoc";import { positional } from "./positional";import type { Runner } from "./runner";
type Output< Commands extends Record<string, ArgParser<any> & Runner<any, any>>,> = { [key in keyof Commands]: { command: key; args: ParsingInto<Commands[key]> };}[keyof Commands];
type RunnerOutput< Commands extends Record<string, Runner<any, any> & ArgParser<any>>,> = { [key in keyof Commands]: { command: key; value: Commands[key] extends Runner<any, infer X> ? X : never; };}[keyof Commands];
/** * Combine multiple `command`s into one */export function subcommands< Commands extends Record< string, ArgParser<any> & Runner<any, any> & Partial<Descriptive & Aliased & ProvidesHelp> >,>(config: { name: string; version?: string; cmds: Commands; description?: string; /** Examples to show in help output */ examples?: Example[];}): ArgParser<Output<Commands>> & Named & Partial<Descriptive & Versioned> & Runner<Output<Commands>, RunnerOutput<Commands>> { const circuitbreaker = createCircuitBreaker(!!config.version); const type: From<string, keyof Commands> = { async from(str) { const commands = Object.entries(config.cmds).map(([name, cmd]) => { return { cmdName: name as keyof Commands, names: [name, ...(cmd.aliases ?? [])], }; }); const cmd = commands.find((x) => x.names.includes(str)); if (cmd) { return cmd.cmdName; } let errorMessage = "Not a valid subcommand name";
const closeOptions = didYouMean( str, flatMap(commands, (x) => x.names), ); if (closeOptions) { const option = Array.isArray(closeOptions) ? closeOptions[0] : closeOptions; errorMessage += `\nDid you mean ${chalk.italic(option)}?`; }
throw new Error(errorMessage); }, };
const subcommand = positional({ displayName: "subcommand", description: `one of ${Object.keys(config.cmds).join(", ")}`, type, });
function normalizeContext(context: ParseContext) { if (context.hotPath?.length === 0) { context.hotPath.push(config.name); }
// Called without any arguments? We default to subcommand help. if (!context.nodes.some((n) => !context.visitedNodes.has(n))) { context.nodes.push({ type: "longOption", index: 0, key: "help", raw: "--help", }); } }
return { version: config.version, description: config.description, name: config.name, handler: (value) => { const cmd = config.cmds[value.command]; return cmd.handler(value.args); }, register(opts) { for (const cmd of Object.values(config.cmds)) { cmd.register(opts); } circuitbreaker.register(opts); }, printHelp(context) { const data: SubcommandsHelpData = { name: config.name, path: context.hotPath ?? [config.name], version: config.version, description: config.description, commands: Object.entries(config.cmds).map(([name, cmd]) => ({ name, description: cmd.description, aliases: cmd.aliases, helpTopics: cmd.helpTopics?.() ?? [], })), examples: config.examples, }; return getHelpFormatter().formatSubcommands(data, context); }, async parse( context: ParseContext, ): Promise<ParsingResult<Output<Commands>>> { normalizeContext(context); const parsed = await subcommand.parse(context);
if (Result.isErr(parsed)) { return Result.err({ errors: parsed.error.errors, partialValue: {}, }); }
context.hotPath?.push(parsed.value as string);
const cmd = config.cmds[parsed.value]; const parsedCommand = await cmd.parse(context); if (Result.isErr(parsedCommand)) { return Result.err({ errors: parsedCommand.error.errors, partialValue: { command: parsed.value, args: parsedCommand.error.partialValue, }, }); } return Result.ok({ args: parsedCommand.value, command: parsed.value, }); }, async run(context): Promise<ParsingResult<RunnerOutput<Commands>>> { normalizeContext(context); const parsedSubcommand = await subcommand.parse(context);
if (Result.isErr(parsedSubcommand)) { const breaker = await circuitbreaker.parse(context); handleCircuitBreaker(context, this, breaker);
return Result.err({ ...parsedSubcommand.error, partialValue: {} }); }
context.hotPath?.push(parsedSubcommand.value as string);
const cmd = config.cmds[parsedSubcommand.value]; const commandRun = await cmd.run(context);
if (Result.isOk(commandRun)) { return Result.ok({ command: parsedSubcommand.value, value: commandRun.value, }); }
return Result.err({ ...commandRun.error, partialValue: { command: parsedSubcommand.value, value: commandRun.error.partialValue, }, }); }, };}
function flatMap<T, R>(array: T[], f: (t: T) => R[]): R[] { const rs: R[] = []; for (const item of array) { rs.push(...f(item)); } return rs;}