diff --git a/.agents_tmp/PLAN.md b/.agents_tmp/PLAN.md new file mode 100644 index 0000000..054da60 --- /dev/null +++ b/.agents_tmp/PLAN.md @@ -0,0 +1,236 @@ +# 1. OBJECTIVE + +为 clippy CLI 框架添加增强的帮助系统: + +1. **区分 `-h` 和 `--help` 的输出**: + - `-h` 显示概览(简短),只包含 Usage 和 Commands + - `--help` 显示详细信息,包含所有 Options、Arguments、Commands 等完整信息 + +2. **实现内置的 `help [command]` 子命令**: + - `help` → 显示当前命令的完整帮助信息 + - `help ` → 显示指定子命令的帮助信息 + +3. **支持用户对 Commands、Options、Arguments 进行分组**: + - 选项/参数可指定 `group` 属性进行分组 + - 支持自定义分组显示顺序 + +# 2. CONTEXT SUMMARY + +这是一个 TypeScript CLI 框架 (clippy),核心文件包括: + +| 文件 | 用途 | +|------|------| +| `src/types.ts` | 类型定义,包含 `OptionDef`、`ArgDef` | +| `src/help.ts` | 帮助信息格式化器 | +| `src/command.ts` | 命令构建器和解析器 | +| `src/index.ts` | 公开 API | + +当前帮助系统: +- 单一帮助信息格式(无 `-h`/`--help` 区分) +- 无内置 `help` 子命令 +- 选项/参数无分组功能 + +# 3. APPROACH OVERVIEW + +## 3.1 概览/详细帮助区分 + +- 在 `HelpConfig` 中添加 `detailedHelp` 选项控制默认行为 +- `formatHelp()` 函数增加 `detailed` 参数 +- `-h` 触发概览模式,`--help` 触发详细模式 +- 概览模式只显示:Usage + Arguments + Commands +- 详细模式显示:Usage + Arguments + Options + Global Options + Commands + 帮助提示 + +## 3.2 内置 help 子命令 + +- 添加 `addHelpCommand()` 方法注册内置 help 命令 +- 当解析到 `help [command]` 时,显示对应命令的帮助 +- 递归处理嵌套子命令的 help + +## 3.3 分组支持 + +- 在 `OptionDef`、`ArgDef` 添加可选 `group?: string` 字段 +- 在 `SubcommandInfo` 添加可选 `group?: string` 字段 +- `HelpConfig` 添加 `groupOrder?: string[]` 控制分组顺序 +- `formatHelp()` 按 group 分组输出,每组显示标题 + +# 4. IMPLEMENTATION STEPS + +## Step 1: 修改 `src/types.ts` - 添加分组字段 + +**目标**:为 OptionDef、ArgDef 添加分组支持 + +**方法**: +- `OptionDef` 添加 `group?: string` +- `ArgDef` 添加 `group?: string` + +**参考**:`src/types.ts` 第 54-71 行 + +--- + +## Step 2: 修改 `src/help.ts` - 增强 HelpConfig 和 formatHelp + +**目标**:添加分组支持和详细/概览模式 + +**方法**: + +### 2.1 更新 HelpConfig 接口 +```ts +export interface HelpConfig { + // ... 现有字段 + detailedHelp?: boolean; // 默认详细模式 + groupOrder?: string[]; // 分组显示顺序 + styles?: { + // ... 现有样式 + groupTitle?: (s: string) => string; // 分组标题样式 + }; +} +``` + +### 2.2 修改 formatHelp 函数 +- 添加 `detailed: boolean` 参数(默认 true) +- 概览模式:不显示 Options、Global Options,仅显示 Arguments 和 Commands +- 详细模式:显示全部内容 + +### 2.3 添加分组格式化逻辑 +```ts +function formatGroupedSection( + items: T[], + formatter: (item: T) => string, + groupOrder: string[], + styles: HelpConfig['styles'] +): string[] +``` + +**参考**:`src/help.ts` 第 91-217 行 + +--- + +## Step 3: 修改 `src/command.ts` - 集成帮助功能 + +**目标**:添加 `-h`/`--help` 选项和内置 help 命令 + +**方法**: + +### 3.1 添加帮助选项定义 +```ts +private _helpOptions = { + short: '-h', + long: '--help', + shortDesc: 'Show brief help', + longDesc: 'Show full help', +}; +``` + +### 3.2 修改构造函数或 init 方法 +- 自动注册 `-h` 和 `--help` 选项(隐藏,不影响正常解析) + +### 3.3 修改 `_parse` 方法 +- 检测 `-h`:显示概览帮助,exit(0) +- 检测 `--help`:显示详细帮助,exit(0) +- 检测 `help`:调用 help 命令处理器 + +### 3.4 添加 help 命令处理 +```ts +helpText(options?: { detailed?: boolean }): string { + return formatHelp({ + // ... + detailed: options?.detailed ?? true, + }); +} + +helpCommand(): Command { + // 创建内置 help 子命令 +} +``` + +### 3.5 更新 option/argument 方法 +- 允许传入 `group` 配置 + +### 3.6 添加分组配置到 configureHelp +```ts +configureHelp(config: HelpConfig & { groupOrder?: string[] }): this +``` + +**参考**:`src/command.ts` 第 281-530 行 + +--- + +## Step 4: 更新 `src/index.ts` - 导出新类型 + +**目标**:确保新类型可被外部访问 + +**方法**: +- 导出更新后的 `OptionDef`、`ArgDef` 类型 + +--- + +## Step 5: 更新测试和示例 + +**目标**:验证新功能 + +**方法**: + +### 5.1 更新 `tests/command.test.ts` +添加测试用例: +- `-h` 显示概览帮助 +- `--help` 显示详细帮助 +- `help` 子命令工作正常 +- 分组功能正常工作 + +### 5.2 更新 `examples/demo.ts` +添加分组示例: +```ts +.option('-p, --port ', 'Port', { group: 'Server Options' }) +.option('--host ', 'Host', { group: 'Server Options' }) +.option('-v, --verbose', 'Verbose', { group: 'Output Options' }) +``` + +--- + +## Step 6: 类型检查 + +**目标**:确保类型安全 + +**方法**: +- 运行 `pnpm typecheck` +- 修复任何类型错误 + +# 5. TESTING AND VALIDATION + +## 5.1 功能测试 + +| 测试场景 | 预期结果 | +|----------|----------| +| `demo -h` | 只显示 Usage 和 Commands | +| `demo --help` | 显示完整帮助信息 | +| `demo help` | 显示详细帮助 | +| `demo help serve` | 显示 serve 子命令的帮助 | +| `demo help unknown` | 显示错误提示 | +| 分组选项/参数 | 按组显示,有分组标题 | + +## 5.2 测试命令 + +```bash +# 运行测试 +pnpm test + +# 类型检查 +pnpm typecheck + +# 手动验证 +pnpm demo -h +pnpm demo --help +pnpm demo help +pnpm demo serve -h +pnpm demo serve --help +``` + +## 5.3 成功标准 + +- [ ] `-h` 只显示概览(Usage + Arguments + Commands) +- [ ] `--help` 显示完整帮助 +- [ ] `help` 子命令正常工作 +- [ ] `help ` 显示指定命令帮助 +- [ ] 分组功能正常工作 +- [ ] 所有现有测试通过 +- [ ] 类型检查通过 diff --git a/examples/demo.ts b/examples/demo.ts index bea9e5a..a639a25 100644 --- a/examples/demo.ts +++ b/examples/demo.ts @@ -30,7 +30,7 @@ const program = new Command('demo') .configureHelp({ width: 10, sortOptions: true }); // ─── `serve` command ───────────────────────────────────────── -// Demonstrates: typed options with parsers, defaults, env vars +// Demonstrates: typed options with parsers, defaults, env vars, grouped options const serve = new Command('serve') .description('Start a development server', 'Start dev server') @@ -38,13 +38,23 @@ const serve = new Command('serve') default: 3000, parser: parseIntStrict, env: 'PORT', + group: 'Server Options', }) - .option('-H, --host ', 'Hostname to bind', { default: 'localhost' }) - .option('--https', 'Enable HTTPS', {}) - .option('--no-open', 'Do not open browser after start', {}) + .option('-H, --host ', 'Hostname to bind', { + default: 'localhost', + group: 'Server Options', + }) + .option('--https', 'Enable HTTPS', { group: 'Server Options' }) + .option('--no-open', 'Do not open browser after start', { group: 'Server Options' }) .option('-l, --log-level ', 'Log level', { default: 'info' as 'debug' | 'info' | 'warn' | 'error', choices: ['debug', 'info', 'warn', 'error'], + group: 'Output Options', + }) + .option('-v, --verbose', 'Verbose output', { group: 'Output Options' }) + .option('--json', 'Output as JSON', { group: 'Output Options' }) + .configureHelp({ + groupOrder: ['Server Options', 'Output Options'], }) .action((opts) => { // ✅ Full type inference: @@ -53,6 +63,8 @@ const serve = new Command('serve') // opts.https → boolean (boolean flag) // opts.open → boolean (negatable) // opts.logLevel → string (has default) + // opts.verbose → boolean + // opts.json → boolean console.log('\n🚀 Starting server...\n'); console.log(' Port: ', opts.port); // number @@ -60,6 +72,8 @@ const serve = new Command('serve') console.log(' HTTPS: ', opts.https); // boolean console.log(' Open: ', opts.open); // boolean console.log(' Log level: ', opts.logLevel); // string + console.log(' Verbose: ', opts.verbose); // boolean + console.log(' JSON: ', opts.json); // boolean console.log(); }); diff --git a/examples/split.ts b/examples/split.ts index 94510c1..1189ffe 100644 --- a/examples/split.ts +++ b/examples/split.ts @@ -1,4 +1,6 @@ -import { program } from "../src"; +import { Command } from "../src"; + +const program = new Command('split'); program .option('--first','') @@ -11,7 +13,7 @@ program program.parse(); -const options = program.opts(); +const options = program.opts() as { first?: boolean; separator?: string }; console.log('Options:', options.first); // const limit = options.first ? 1 : undefined; // console.log(program.args[0].split(options.separator, limit)); diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index fb3ca16..f5d24f5 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,2 +1,5 @@ +packages: + - '.' + overrides: esbuild: 0.26.0 \ No newline at end of file diff --git a/src/command.ts b/src/command.ts index 9faa0a2..f26966c 100644 --- a/src/command.ts +++ b/src/command.ts @@ -146,6 +146,7 @@ export class Command< env?: string; choices?: string[]; hidden?: boolean; + group?: string; } ): Command, Args> { this._options.push({ @@ -157,6 +158,7 @@ export class Command< hidden: config?.hidden ?? false, envVar: config?.env, choices: config?.choices, + group: config?.group, }); return this as any; } @@ -176,6 +178,7 @@ export class Command< parser?: Parser extends ((v: string, p: any) => any) ? Parser : never; env?: string; choices?: string[]; + group?: string; } ): Command, Args> { this._options.push({ @@ -187,6 +190,7 @@ export class Command< hidden: false, envVar: config?.env, choices: config?.choices, + group: config?.group, }); return this as any; } @@ -213,6 +217,7 @@ export class Command< default?: unknown; parser?: Parser extends ((v: string, p: any) => any) ? Parser : never; choices?: string[]; + group?: string; } ): Command infer R ? [R] : N extends `<${string}...>` | `[${string}...]` ? [string[]] : N extends `<${string}>` ? [string] : [string | undefined])]> { this._args.push({ @@ -221,6 +226,7 @@ export class Command< parser: config?.parser, defaultValue: config?.default, choices: config?.choices, + group: config?.group, }); return this as any; } @@ -307,6 +313,12 @@ export class Command< // Route to subcommand FIRST so subcommands get their own --help const [firstArg, ...rest] = rawArgs; if (firstArg && !firstArg.startsWith('-')) { + // Check for built-in help command + if (firstArg === 'help') { + this._handleHelpCommand(rest); + return; + } + const sub = this._subcommands.get(firstArg); if (sub) { if (this._hooks.preSubcommand) { @@ -317,9 +329,13 @@ export class Command< } } - // Check for help (after subcommand routing) - if (rawArgs.includes('--help') || rawArgs.includes('-h')) { - process.stdout.write(this.helpText()); + // Check for help flags (after subcommand routing) + if (rawArgs.includes('--help')) { + process.stdout.write(this.helpText({ detailed: true })); + process.exit(0); + } + if (rawArgs.includes('-h')) { + process.stdout.write(this.helpText({ detailed: false })); process.exit(0); } @@ -355,8 +371,58 @@ export class Command< this._error(`Unknown command: '${rawArgs[0]}'`, 'clippy.unknownCommand'); } else if (this._subcommands.size > 0) { // No action and no subcommand specified: show help - process.stdout.write(this.helpText()); + process.stdout.write(this.helpText({ detailed: true })); + } + } + + /** Handle the built-in help command: help [command] */ + private _handleHelpCommand(args: string[]): void { + if (args.length === 0) { + // help - show full help for this command + process.stdout.write(this.helpText({ detailed: true })); + process.exit(0); + return; + } + + const [targetName, ...remaining] = args; + if (!targetName) { + process.stdout.write(this.helpText({ detailed: true })); + process.exit(0); + return; + } + + const targetCmd = this._subcommands.get(targetName); + + if (targetCmd) { + // Check for help subcommand on the target + if (remaining[0] === 'help') { + process.stdout.write(targetCmd.helpText({ detailed: true })); + process.exit(0); + return; + } + + // Check for -h or --help on target + if (remaining.includes('--help')) { + process.stdout.write(targetCmd.helpText({ detailed: true })); + process.exit(0); + return; + } + if (remaining.includes('-h')) { + process.stdout.write(targetCmd.helpText({ detailed: false })); + process.exit(0); + return; + } + + // Show detailed help for target command + process.stdout.write(targetCmd.helpText({ detailed: true })); + process.exit(0); + return; } + + // Unknown command + process.stderr.write(`${ansi.c(ansi.red, 'error')}: unknown command '${targetName}'\n`); + process.stderr.write(this.helpText({ detailed: false })); + process.exit(1); } private _parseOptionsAndArgs(rawArgs: string[]): void { @@ -625,7 +691,7 @@ export class Command< // ── Help ───────────────────────────────────────────────────── - helpText(): string { + helpText(options?: { detailed?: boolean }): string { const subcommandInfos: SubcommandInfo[] = []; const seen = new Set>(); for (const [, cmd] of this._subcommands) { @@ -636,6 +702,7 @@ export class Command< description: cmd._summary || cmd._description, aliases: cmd._aliases, hidden: cmd._hidden, + group: cmd._helpConfig.groupOrder ? undefined : undefined, // Groups for subcommands would be configured separately }); } @@ -652,10 +719,11 @@ export class Command< subcommands: subcommandInfos, helpConfig: this._helpConfig, parentNames, + detailed: options?.detailed ?? true, }); } - outputHelp(): void { - process.stdout.write(this.helpText()); + outputHelp(options?: { detailed?: boolean }): void { + process.stdout.write(this.helpText(options)); } } diff --git a/src/help.ts b/src/help.ts index c817411..c4f417e 100644 --- a/src/help.ts +++ b/src/help.ts @@ -11,6 +11,10 @@ export interface HelpConfig { sortOptions?: boolean; sortCommands?: boolean; showGlobalOptions?: boolean; + /** Group order for options/args/commands display, ungrouped items appear last */ + groupOrder?: string[]; + /** Show all options/args in -h mode (false = brief mode only) */ + showAllOnBrief?: boolean; styles?: { title?: (s: string) => string; usage?: (s: string) => string; @@ -22,6 +26,7 @@ export interface HelpConfig { argName?: (s: string) => string; hint?: (s: string) => string; error?: (s: string) => string; + groupTitle?: (s: string) => string; }; } @@ -49,6 +54,7 @@ const DEFAULT_STYLES: Required> = { argName: (s) => s, hint: (s) => `${ansi.gray}${s}${ansi.reset}`, error: (s) => `${ansi.red}${s}${ansi.reset}`, + groupTitle: (s) => `${ansi.bold}${s}${ansi.reset}`, }; @@ -86,6 +92,47 @@ export interface SubcommandInfo { description: string; aliases: string[]; hidden: boolean; + group?: string; +} + +/** Group items by their group property, returning ordered sections */ +function groupItems( + items: T[], + groupOrder: string[] +): Map { + const groups = new Map(); + + for (const item of items) { + const group = item.group; + if (!groups.has(group)) { + groups.set(group, []); + } + groups.get(group)!.push(item); + } + + return groups; +} + +/** Sort groups according to groupOrder, ungrouped items last */ +function sortGroups( + groupedItems: Map, + groupOrder: string[] +): Array<{ group: string | undefined; items: T[] }> { + const result: Array<{ group: string | undefined; items: T[] }> = []; + + // First add ordered groups + for (const groupName of groupOrder) { + if (groupedItems.has(groupName)) { + result.push({ group: groupName, items: groupedItems.get(groupName)! }); + } + } + + // Then add ungrouped items (group = undefined) + if (groupedItems.has(undefined)) { + result.push({ group: undefined, items: groupedItems.get(undefined)! }); + } + + return result; } export function formatHelp(config: { @@ -99,15 +146,20 @@ export function formatHelp(config: { globalOptions?: OptionDef[]; helpConfig?: HelpConfig; parentNames?: string[]; + /** When false (-h), omit Options section; true (--help) shows all */ + detailed?: boolean; }): string { const { name, version, description, options, args, subcommands, globalOptions = [], helpConfig = {}, parentNames = [], + detailed = true, } = config; const styles = { ...DEFAULT_STYLES, ...(helpConfig.styles ?? {}) }; const width = helpConfig.width ?? (process.stdout.columns ?? 80); const lines: string[] = []; + const groupOrder = helpConfig.groupOrder ?? []; + const showAllOnBrief = helpConfig.showAllOnBrief ?? false; const fullName = [...parentNames, name].join(' '); @@ -117,12 +169,6 @@ export function formatHelp(config: { lines.push(''); } - // ── Version ── - // if (version) { - // lines.push(styles.hint(`version ${version}`)); - // lines.push(''); - // } - // ── Usage ── const usageParts = [fullName]; if (options.length > 0) usageParts.push('[options]'); @@ -134,51 +180,69 @@ export function formatHelp(config: { lines.push(` ${styles.usage(usageStr)}`); lines.push(''); - // ── Arguments ── + // ── Arguments (always show) ── const visibleArgs = args.filter(a => a.description); if (visibleArgs.length > 0) { - lines.push(styles.title('Arguments:')); - const nameWidth = Math.max(...visibleArgs.map(a => stripAnsi(a.name).length)) + 4; - for (const arg of visibleArgs) { - const namePart = padEnd(styles.argName(arg.name), nameWidth + 6); - const descPart = styles.optionDesc(arg.description); - const choiceHint = arg.choices ? styles.hint(` (choices: ${arg.choices.join(', ')})`) : ''; - lines.push(` ${namePart}${descPart}${choiceHint}`); + const groupedArgs = groupItems(visibleArgs, groupOrder); + const sortedArgGroups = sortGroups(groupedArgs, groupOrder); + + for (const { group, items } of sortedArgGroups) { + if (group) { + lines.push(styles.groupTitle(group)); + lines.push(''); + } + const nameWidth = Math.max(...items.map(a => stripAnsi(a.name).length)) + 4; + for (const arg of items) { + const namePart = padEnd(styles.argName(arg.name), nameWidth + 6); + const descPart = styles.optionDesc(arg.description); + const choiceHint = arg.choices ? styles.hint(` (choices: ${arg.choices.join(', ')})`) : ''; + lines.push(` ${namePart}${descPart}${choiceHint}`); + } + lines.push(''); } - lines.push(''); } - // ── Options ── + // ── Options (only in detailed mode or showAllOnBrief) ── + const showOptions = detailed || showAllOnBrief; const visibleOptions = options.filter(o => !o.hidden); - if (visibleOptions.length > 0) { + if (showOptions && visibleOptions.length > 0) { const sorted = helpConfig.sortOptions ? [...visibleOptions].sort((a, b) => a.flags.localeCompare(b.flags)) : visibleOptions; lines.push(styles.title('Options:')); - const flagWidth = Math.max(...sorted.map(o => stripAnsi(o.flags).length)) + 2; - - for (const opt of sorted) { - const flagPart = padEnd(styles.optionFlag(opt.flags), flagWidth + 4); - const descPart = styles.optionDesc(opt.description); - - const hints: string[] = []; - if (opt.envVar) hints.push(`env: ${opt.envVar}`); - if (opt.choices) hints.push(`choices: ${opt.choices.join(', ')}`); - if (opt.defaultValue !== undefined) { - const dv = JSON.stringify(opt.defaultValue); - hints.push(`default: ${dv}`); + + const groupedOptions = groupItems(sorted, groupOrder); + const sortedOptionGroups = sortGroups(groupedOptions, groupOrder); + + for (const { group, items } of sortedOptionGroups) { + if (group) { + lines.push(styles.groupTitle(group)); } - if (opt.required) hints.push('required'); + const flagWidth = Math.max(...items.map(o => stripAnsi(o.flags).length)) + 2; - const hintStr = hints.length > 0 ? styles.hint(` (${hints.join(', ')})`) : ''; - lines.push(` ${flagPart}${descPart}${hintStr}`); + for (const opt of items) { + const flagPart = padEnd(styles.optionFlag(opt.flags), flagWidth + 4); + const descPart = styles.optionDesc(opt.description); + + const hints: string[] = []; + if (opt.envVar) hints.push(`env: ${opt.envVar}`); + if (opt.choices) hints.push(`choices: ${opt.choices.join(', ')}`); + if (opt.defaultValue !== undefined) { + const dv = JSON.stringify(opt.defaultValue); + hints.push(`default: ${dv}`); + } + if (opt.required) hints.push('required'); + + const hintStr = hints.length > 0 ? styles.hint(` (${hints.join(', ')})`) : ''; + lines.push(` ${flagPart}${descPart}${hintStr}`); + } + lines.push(''); } - lines.push(''); } // ── Global Options ── - if (helpConfig.showGlobalOptions && globalOptions.length > 0) { + if (showOptions && helpConfig.showGlobalOptions && globalOptions.length > 0) { const sorted = [...globalOptions].filter(o => !o.hidden); if (sorted.length > 0) { lines.push(styles.title('Global Options:')); @@ -191,26 +255,36 @@ export function formatHelp(config: { } } - // ── Subcommands ── + // ── Subcommands (always show) ── const visibleCommands = subcommands.filter(c => !c.hidden); if (visibleCommands.length > 0) { const sorted = helpConfig.sortCommands ? [...visibleCommands].sort((a, b) => a.name.localeCompare(b.name)) : visibleCommands; - lines.push(styles.title('Commands:')); - const nameWidth = Math.max(...sorted.map(c => stripAnsi(c.name).length)) + 2; + const groupedCommands = groupItems(sorted, groupOrder); + const sortedCommandGroups = sortGroups(groupedCommands, groupOrder); + + for (const { group, items } of sortedCommandGroups) { + if (group) { + lines.push(styles.groupTitle(group)); + lines.push(''); + } + const nameWidth = Math.max(...items.map(c => stripAnsi(c.name).length)) + 2; - for (const cmd of sorted) { - const aliasPart = cmd.aliases.length > 0 - ? `|${cmd.aliases.join('|')}` - : ''; - const namePart = padEnd(styles.commandName(cmd.name + aliasPart), nameWidth + 8); - lines.push(` ${namePart}${styles.commandDesc(cmd.description)}`); + for (const cmd of items) { + const aliasPart = cmd.aliases.length > 0 + ? `|${cmd.aliases.join('|')}` + : ''; + const namePart = padEnd(styles.commandName(cmd.name + aliasPart), nameWidth + 8); + lines.push(` ${namePart}${styles.commandDesc(cmd.description)}`); + } + lines.push(''); + } + if (detailed) { + lines.push(styles.hint(`Run '${fullName} [command] --help' for more information on a command.`)); + lines.push(''); } - lines.push(''); - lines.push(styles.hint(`Run '${fullName} [command] --help' for more information on a command.`)); - lines.push(''); } return lines.join('\n'); diff --git a/src/types.ts b/src/types.ts index 4fa44da..f017813 100644 --- a/src/types.ts +++ b/src/types.ts @@ -60,6 +60,7 @@ export interface OptionDef { hidden: boolean; envVar?: string; choices?: string[]; + group?: string; } export interface ArgDef { @@ -68,6 +69,7 @@ export interface ArgDef { parser: ((v: string, prev: unknown) => unknown) | undefined; defaultValue?: unknown; choices?: string[]; + group?: string; } // ─── Type-level Opts Map ───────────────────────────────────── diff --git a/tests/command.test.ts b/tests/command.test.ts index 8479fad..e1fdc49 100644 --- a/tests/command.test.ts +++ b/tests/command.test.ts @@ -102,3 +102,54 @@ describe('Command - runtime parsing', () => { expect(cmd.name()).toBe('foo'); }); }); + +describe('Command - help system', () => { + it('shows brief help on -h', async () => { + const cmd = new Command('test') + .description('A test command') + .option('-p, --port ', 'port number', { default: 3000 }) + .addCommand(new Command('sub').description('A subcommand')); + + const briefHelp = cmd.helpText({ detailed: false }); + // Brief mode should not include Options section + expect(briefHelp).toContain('Usage:'); + expect(briefHelp).toContain('sub'); // Commands are shown in both modes + expect(briefHelp).not.toContain('Options:'); + }); + + it('shows detailed help on --help', async () => { + const cmd = new Command('test') + .description('A test command') + .option('-p, --port ', 'port number', { default: 3000 }) + .addCommand(new Command('sub').description('A subcommand')); + + const detailedHelp = cmd.helpText({ detailed: true }); + // Detailed mode should include Options section + expect(detailedHelp).toContain('Usage:'); + expect(detailedHelp).toContain('sub'); // Commands are shown in both modes + expect(detailedHelp).toContain('Options:'); + }); + + it('groups options by group property', async () => { + const cmd = new Command('test') + .option('-p, --port ', 'port', { group: 'Server' }) + .option('--host ', 'host', { group: 'Server' }) + .option('-v, --verbose', 'verbose', { group: 'Output' }) + .configureHelp({ groupOrder: ['Server', 'Output'] }); + + const help = cmd.helpText({ detailed: true }); + expect(help).toContain('Server'); + expect(help).toContain('Output'); + }); + + it('adds group to arguments', async () => { + const cmd = new Command('test') + .argument('', 'input file', { group: 'Input' }) + .argument('[out]', 'output file', { group: 'Output' }) + .configureHelp({ groupOrder: ['Input', 'Output'] }); + + const help = cmd.helpText({ detailed: true }); + expect(help).toContain('Input'); + expect(help).toContain('Output'); + }); +});