fix: cli framework

fix:
- cli command path wrong
- help output nil
This commit is contained in:
2025-10-27 22:02:15 +08:00
parent 7a17ca7fbf
commit 1891259ee7
3 changed files with 10 additions and 5 deletions

View File

@@ -22,7 +22,9 @@ import { generateHelp, shouldShowHelp, generateCommandList } from "./help";
export interface CreateCliOptions<TContext extends object> { export interface CreateCliOptions<TContext extends object> {
/** An optional global context object to be made available in all command actions. */ /** An optional global context object to be made available in all command actions. */
globalContext?: TContext; globalContext?: TContext;
/** An optional function to handle output. Defaults to the global `print` function. */ /** An optional function to handle output.
* Default: textutils.pagedPrint(msg, term.getCursorPos()[1] - 2)
**/
writer?: (message: string) => void; writer?: (message: string) => void;
} }
@@ -36,12 +38,15 @@ export function createCli<TContext extends object>(
rootCommand: Command<TContext>, rootCommand: Command<TContext>,
options: CreateCliOptions<TContext> = {}, options: CreateCliOptions<TContext> = {},
): (argv: string[]) => void { ): (argv: string[]) => void {
const { globalContext, writer = print } = options; const {
globalContext,
writer = (msg) => textutils.pagedPrint(msg, term.getCursorPos()[1] - 2),
} = options;
return (argv: string[]): void => { return (argv: string[]): void => {
// Check for top-level help flags before any parsing. // Check for top-level help flags before any parsing.
if (argv[0]?.startsWith("--help") || argv[0]?.startsWith("-h")) { if (argv[0]?.startsWith("--help") || argv[0]?.startsWith("-h")) {
writer(generateHelp(rootCommand)); writer(generateHelp(rootCommand, [rootCommand.name]));
return; return;
} }

View File

@@ -11,7 +11,7 @@ export function generateHelp<TContext extends object>(
commandPath: string[] = [], commandPath: string[] = [],
): string { ): string {
const lines: string[] = []; const lines: string[] = [];
const fullCommandName = [...commandPath, command.name].join(" "); const fullCommandName = commandPath.join(" ");
// Description // Description
if (command.description !== undefined) { if (command.description !== undefined) {

View File

@@ -81,7 +81,7 @@ export function parseArguments<TContext extends object>(
): Result<ParseResult<TContext>, CliError> { ): Result<ParseResult<TContext>, CliError> {
const result: ParseResult<TContext> = { const result: ParseResult<TContext> = {
command: rootCommand, command: rootCommand,
commandPath: [], commandPath: [rootCommand.name],
options: {}, options: {},
remaining: [], remaining: [],
}; };