reconstruct: cli framework

This commit is contained in:
2025-10-27 16:50:04 +08:00
parent f7167576cd
commit 7a17ca7fbf
5 changed files with 294 additions and 175 deletions

View File

@@ -5,8 +5,7 @@ import {
Argument,
Option,
CliError,
ParsedInput,
CommandResolution,
ParseResult,
} from "./types";
import {
parseArguments,
@@ -41,56 +40,57 @@ export function createCli<TContext extends object>(
return (argv: string[]): void => {
// Check for top-level help flags before any parsing.
if (shouldShowHelp(argv)) {
if (argv[0]?.startsWith("--help") || argv[0]?.startsWith("-h")) {
writer(generateHelp(rootCommand));
return;
}
const parsedInput = parseArguments(argv);
const executionResult = findCommand(
rootCommand,
parsedInput.commandPath,
).andThen((resolution) =>
processAndExecute(resolution, parsedInput, globalContext, (msg: string) =>
writer(msg),
),
const parseResult = parseArguments(argv, rootCommand);
if (parseResult.isErr()) {
const error = parseResult.error;
writer(formatError(error, rootCommand));
// If it was an unknown command, suggest alternatives.
if (error.kind === "UnknownCommand") {
// Find parent command to suggest alternatives
const parentResult = parseArguments(argv.slice(0, -1), rootCommand);
if (parentResult.isOk() && parentResult.value.command.subcommands) {
writer(generateCommandList(parentResult.value.command.subcommands));
}
}
return;
}
const executionResult = processAndExecute(
parseResult.value,
globalContext,
(msg: string) => writer(msg),
);
if (executionResult.isErr()) {
const error = executionResult.error;
writer(formatError(error, rootCommand));
// If it was an unknown command, suggest alternatives.
if (error.kind === "UnknownCommand") {
const parent = findCommand(
rootCommand,
parsedInput.commandPath.slice(0, -1),
);
if (parent.isOk() && parent.value.command.subcommands) {
writer(generateCommandList(parent.value.command.subcommands));
}
}
}
};
}
/**
* Processes the parsed input and executes the resolved command.
* @param resolution The resolved command and its context.
* @param parsedInput The raw parsed command-line input.
* @param parseResult The result from parsing with integrated command resolution.
* @param globalContext The global context for the CLI.
* @param writer Function to output messages.
* @returns A `Result` indicating the success or failure of the execution.
*/
function processAndExecute<TContext extends object>(
resolution: CommandResolution<TContext>,
parsedInput: ParsedInput,
parseResult: ParseResult<TContext>,
globalContext: TContext | undefined,
writer: (message: string) => void,
): Result<void, CliError> {
const { command, commandPath, remainingArgs } = resolution;
const { command, commandPath, options, remaining } = parseResult;
// Handle requests for help on a specific command.
if (shouldShowHelp([...remainingArgs, ...Object.keys(parsedInput.options)])) {
if (shouldShowHelp([...remaining, ...Object.keys(options)])) {
writer(generateHelp(command, commandPath));
return Ok.EMPTY;
}
@@ -98,7 +98,7 @@ function processAndExecute<TContext extends object>(
// If a command has subcommands but no action, show its help page.
if (
command.subcommands &&
command.subcommands.length > 0 &&
command.subcommands.size > 0 &&
command.action === undefined
) {
writer(generateHelp(command, commandPath));
@@ -113,20 +113,19 @@ function processAndExecute<TContext extends object>(
});
}
return processArguments(
command.args ?? [],
remainingArgs,
parsedInput.remaining,
)
return processArguments(command.args ?? [], remaining)
.andThen((args) => {
return processOptions(command.options ?? [], parsedInput.options).map(
(options) => ({ args, options }),
);
return processOptions(
command.options !== undefined
? Array.from(command.options.values())
: [],
options,
).map((processedOptions) => ({ args, options: processedOptions }));
})
.andThen(({ args, options }) => {
.andThen(({ args, options: processedOptions }) => {
const context: ActionContext<TContext> = {
args,
options,
options: processedOptions,
context: globalContext!,
};
// Finally, execute the command's action.
@@ -134,60 +133,22 @@ function processAndExecute<TContext extends object>(
});
}
/**
* Finds the target command based on a given path.
* @param rootCommand The command to start searching from.
* @param commandPath An array of strings representing the path to the command.
* @returns A `Result` containing the `CommandResolution` or an `UnknownCommandError`.
*/
function findCommand<TContext extends object>(
rootCommand: Command<TContext>,
commandPath: string[],
): Result<CommandResolution<TContext>, CliError> {
let currentCommand = rootCommand;
const resolvedPath: string[] = [];
let i = 0;
for (const name of commandPath) {
const subcommand = currentCommand.subcommands?.find(
(cmd) => cmd.name === name,
);
if (!subcommand) {
// Part of the path was not a valid command, so the rest are arguments.
return new Err({ kind: "UnknownCommand", commandName: name });
}
currentCommand = subcommand;
resolvedPath.push(name);
i++;
}
const remainingArgs = commandPath.slice(i);
return new Ok({
command: currentCommand,
commandPath: resolvedPath,
remainingArgs,
});
}
/**
* Processes and validates command arguments from the raw input.
* @param argDefs The argument definitions for the command.
* @param remainingArgs The positional arguments captured during command resolution.
* @param additionalArgs Any extra arguments parsed after options.
* @param remainingArgs The remaining positional arguments.
* @returns A `Result` with the processed arguments record or a `MissingArgumentError`.
*/
function processArguments(
argDefs: Argument[],
remainingArgs: string[],
additionalArgs: string[],
): Result<Record<string, unknown>, CliError> {
const args: Record<string, unknown> = {};
const allArgs = [...remainingArgs, ...additionalArgs];
for (let i = 0; i < argDefs.length; i++) {
const argDef = argDefs[i];
if (i < allArgs.length) {
args[argDef.name] = allArgs[i];
if (i < remainingArgs.length) {
args[argDef.name] = remainingArgs[i];
}
}

View File

@@ -20,10 +20,10 @@ export function generateHelp<TContext extends object>(
// Usage
const usageParts: string[] = ["Usage:", fullCommandName];
if (command.options && command.options.length > 0) {
if (command.options && command.options.size > 0) {
usageParts.push("[OPTIONS]");
}
if (command.subcommands && command.subcommands.length > 0) {
if (command.subcommands && command.subcommands.size > 0) {
usageParts.push("<COMMAND>");
}
if (command.args && command.args.length > 0) {
@@ -45,9 +45,9 @@ export function generateHelp<TContext extends object>(
}
// Options
if (command.options && command.options.length > 0) {
if (command.options && command.options.size > 0) {
lines.push("\nOptions:");
for (const option of command.options) {
for (const option of command.options.values()) {
const short =
option.shortName !== undefined ? `-${option.shortName}, ` : " ";
const long = `--${option.name}`;
@@ -64,9 +64,9 @@ export function generateHelp<TContext extends object>(
}
// Subcommands
if (command.subcommands && command.subcommands.length > 0) {
if (command.subcommands && command.subcommands.size > 0) {
lines.push("\nCommands:");
for (const subcommand of command.subcommands) {
for (const subcommand of command.subcommands.values()) {
lines.push(` ${subcommand.name.padEnd(20)} ${subcommand.description}`);
}
lines.push(
@@ -83,14 +83,14 @@ export function generateHelp<TContext extends object>(
* @returns A formatted string listing the available commands.
*/
export function generateCommandList<TContext extends object>(
commands: Command<TContext>[],
commands: Map<string, Command<TContext>>,
): string {
if (commands.length === 0) {
if (commands.size === 0) {
return "No commands available.";
}
const lines: string[] = ["Available commands:"];
for (const command of commands) {
for (const command of commands.values()) {
lines.push(` ${command.name.padEnd(20)} ${command.description}`);
}

View File

@@ -1,31 +1,108 @@
import { Ok, Err, Result } from "../thirdparty/ts-result-es";
import { ParsedInput, MissingArgumentError, MissingOptionError } from "./types";
import {
ParseResult,
MissingArgumentError,
MissingOptionError,
Command,
Option,
CliError,
CommandResolution,
} from "./types";
// Cache class to handle option maps with proper typing
class OptionMapCache {
private cache = new WeakMap<
object,
{
optionMap: Map<string, Option>;
shortNameMap: Map<string, string>;
}
>();
get<TContext extends object>(command: Command<TContext>) {
return this.cache.get(command);
}
set<TContext extends object>(
command: Command<TContext>,
value: {
optionMap: Map<string, Option>;
shortNameMap: Map<string, string>;
},
) {
this.cache.set(command, value);
}
}
// Lazy option map builder with global caching
function getOptionMaps<TContext extends object>(
optionCache: OptionMapCache,
command: Command<TContext>,
) {
// Quick check: if command has no options, return empty maps
if (!command.options || command.options.size === 0) {
return {
optionMap: new Map<string, Option>(),
shortNameMap: new Map<string, string>(),
};
}
let cached = optionCache.get(command);
if (cached !== undefined) {
return cached;
}
const optionMap = new Map<string, Option>();
const shortNameMap = new Map<string, string>();
for (const [optionName, option] of command.options) {
optionMap.set(optionName, option);
if (option.shortName !== undefined && option.shortName !== null) {
shortNameMap.set(option.shortName, optionName);
}
}
cached = { optionMap, shortNameMap };
optionCache.set(command, cached);
return cached;
}
/**
* Parses command line arguments into a structured format.
* This function does not validate arguments or options, it only parses the raw input.
* @param argv Array of command line arguments (e.g., from `os.pullEvent`).
* @returns A `ParsedInput` object containing the command path, options, and remaining args.
* Parses command line arguments with integrated command resolution.
* This function dynamically finds the target command during parsing and uses
* the command's option definitions for intelligent option handling.
* @param argv Array of command line arguments.
* @param rootCommand The root command to start parsing from.
* @returns A `Result` containing the `ParseResult` or a `CliError`.
*/
export function parseArguments(argv: string[]): ParsedInput {
const result: ParsedInput = {
export function parseArguments<TContext extends object>(
argv: string[],
rootCommand: Command<TContext>,
): Result<ParseResult<TContext>, CliError> {
const result: ParseResult<TContext> = {
command: rootCommand,
commandPath: [],
options: {},
remaining: [],
};
let currentCommand = rootCommand;
let i = 0;
let inOptions = false;
const optionMapCache = new OptionMapCache();
const getCurrentOptionMaps = () =>
getOptionMaps(optionMapCache, currentCommand);
while (i < argv.length) {
const arg = argv[i];
if (arg === undefined) {
if (arg === undefined || arg === null) {
i++;
continue;
}
// Handle double dash (--) - everything after is treated as a remaining argument.
// Handle double dash (--) - everything after is treated as a remaining argument
if (arg === "--") {
result.remaining.push(...argv.slice(i + 1));
break;
@@ -44,15 +121,20 @@ export function parseArguments(argv: string[]): ParsedInput {
} else {
// --option [value] format
const optionName = arg.slice(2);
if (
i + 1 < argv.length &&
argv[i + 1] !== undefined &&
!argv[i + 1].startsWith("-")
) {
result.options[optionName] = argv[i + 1];
const optionDef = getCurrentOptionMaps().optionMap.get(optionName);
// Check if this is a known boolean option or if next arg looks like a value
const nextArg = argv[i + 1];
const isKnownBooleanOption =
optionDef !== undefined && optionDef.defaultValue === undefined;
const nextArgLooksLikeValue =
nextArg !== undefined && nextArg !== null && !nextArg.startsWith("-");
if (nextArgLooksLikeValue && !isKnownBooleanOption) {
result.options[optionName] = nextArg;
i++; // Skip the value argument
} else {
// Boolean flag
// Boolean flag or no value available
result.options[optionName] = true;
}
}
@@ -60,25 +142,42 @@ export function parseArguments(argv: string[]): ParsedInput {
// Handle short options (-o or -o value)
else if (arg.startsWith("-") && arg.length > 1) {
inOptions = true;
const optionName = arg.slice(1);
const shortName = arg.slice(1);
if (
i + 1 < argv.length &&
argv[i + 1] !== undefined &&
!argv[i + 1].startsWith("-")
) {
result.options[optionName] = argv[i + 1];
// Get option maps for the new command (lazy loaded and cached)
const maps = getCurrentOptionMaps();
const optionName = maps.shortNameMap.get(shortName) ?? shortName;
const optionDef = maps.optionMap.get(optionName);
// Check if this is a known boolean option or if next arg looks like a value
const nextArg = argv[i + 1];
const isKnownBooleanOption =
optionDef !== undefined && optionDef.defaultValue === undefined;
const nextArgLooksLikeValue =
nextArg !== undefined && nextArg !== null && !nextArg.startsWith("-");
if (nextArgLooksLikeValue && !isKnownBooleanOption) {
result.options[optionName] = nextArg;
i++; // Skip the value argument
} else {
// Boolean flag
// Boolean flag or no value available
result.options[optionName] = true;
}
}
// Handle positional arguments and commands
// Handle positional arguments and command resolution
else {
if (!inOptions) {
// Before any options, treat as part of the command path
result.commandPath.push(arg);
// Try to find this as a subcommand of the current command
const subcommand = currentCommand.subcommands?.get(arg);
if (subcommand !== undefined) {
// Found a subcommand, move deeper
currentCommand = subcommand;
result.command = currentCommand;
result.commandPath.push(arg);
} else {
// Not a subcommand, treat as remaining argument
result.remaining.push(arg);
}
} else {
// After options have started, treat as a remaining argument
result.remaining.push(arg);
@@ -88,7 +187,40 @@ export function parseArguments(argv: string[]): ParsedInput {
i++;
}
return result;
return new Ok(result);
}
/**
* Finds the target command based on a given path.
* @param rootCommand The command to start searching from.
* @param commandPath An array of strings representing the path to the command.
* @returns A `Result` containing the `CommandResolution` or an `UnknownCommandError`.
*/
export function findCommand<TContext extends object>(
rootCommand: Command<TContext>,
commandPath: string[],
): Result<CommandResolution<TContext>, CliError> {
let currentCommand = rootCommand;
const resolvedPath: string[] = [];
let i = 0;
for (const name of commandPath) {
const subcommand = currentCommand.subcommands?.get(name);
if (!subcommand) {
// Part of the path was not a valid command, so the rest are arguments.
return new Err({ kind: "UnknownCommand", commandName: name });
}
currentCommand = subcommand;
resolvedPath.push(name);
i++;
}
const remainingArgs = commandPath.slice(i);
return new Ok({
command: currentCommand,
commandPath: resolvedPath,
remainingArgs,
});
}
/**

View File

@@ -104,30 +104,32 @@ export interface Command<TContext extends object> {
name: string;
/** A brief description of the command, shown in help messages. */
description: string;
/** An array of argument definitions for the command. */
/** A map of argument definitions for the command, keyed by argument name. */
args?: Argument[];
/** An array of option definitions for the command. */
options?: Option[];
/** A map of option definitions for the command, keyed by option name. */
options?: Map<string, Option>;
/**
* The function to execute when the command is run.
* It receives an `ActionContext` object.
* Should return a `Result` to indicate success or failure.
*/
action?: (context: ActionContext<TContext>) => Result<void, CliError>;
/** An array of subcommands, allowing for nested command structures. */
subcommands?: Command<TContext>[];
/** A map of subcommands, allowing for nested command structures, keyed by command name. */
subcommands?: Map<string, Command<TContext>>;
}
// --- Parsing and Execution Internals ---
/**
* @interface ParsedInput
* @description The raw output from the initial argument parsing stage.
* @interface ParseResult
* @description Enhanced parsing result that includes command resolution.
*/
export interface ParsedInput {
/** The identified command path from the arguments. */
export interface ParseResult<TContext extends object> {
/** The resolved command found during parsing. */
command: Command<TContext>;
/** The path to the resolved command. */
commandPath: string[];
/** A record of raw option values. */
/** A record of parsed option values. */
options: Record<string, unknown>;
/** Any remaining arguments that were not parsed as part of the command path or options. */
remaining: string[];