feat(cli): render command docs as tree

This commit is contained in:
Andrey Avtomonov 2026-05-13 00:33:24 +02:00
parent e8a7018c55
commit 39f0320c2b
3 changed files with 81 additions and 28 deletions

View file

@ -1,35 +1,58 @@
import type { Command } from '@commander-js/extra-typings';
import type { Argument, CommandUnknownOpts } from '@commander-js/extra-typings';
const DESCRIPTION_COLUMN = 42;
export interface CommandTreeNode {
name: string;
description: string;
aliases: string[];
arguments: string[];
children: CommandTreeNode[];
}
export function walkCommandTree(command: Command): CommandTreeNode {
export function walkCommandTree(command: CommandUnknownOpts): CommandTreeNode {
return {
name: command.name(),
description: command.description(),
aliases: command.aliases(),
children: command.commands.map((child) => walkCommandTree(child as Command)),
arguments: command.registeredArguments.map(formatArgumentDeclaration),
children: command.commands.map((child) => walkCommandTree(child)),
};
}
export function formatCommandTree(node: CommandTreeNode): string {
const lines: string[] = [];
appendNode(node, 0, lines);
appendNode(node, '', '', lines);
return `${lines.join('\n')}\n`;
}
function appendNode(node: CommandTreeNode, depth: number, lines: string[]): void {
const indent = ' '.repeat(depth);
const aliasPart = node.aliases.length > 0 ? ` (${node.aliases.join(', ')})` : '';
const descriptionPart = node.description.length > 0 ? `${node.description}` : '';
lines.push(`${indent}${node.name}${aliasPart}${descriptionPart}`);
const sortedChildren = [...node.children].sort((a, b) => a.name.localeCompare(b.name));
for (const child of sortedChildren) {
appendNode(child, depth + 1, lines);
}
function formatArgumentDeclaration(argument: Argument): string {
const name = `${argument.name()}${argument.variadic ? '...' : ''}`;
return argument.required ? `<${name}>` : `[${name}]`;
}
function appendNode(node: CommandTreeNode, prefix: string, connector: string, lines: string[]): void {
const label = formatLabel(node);
lines.push(formatLine(`${prefix}${connector}${label}`, node.description));
node.children.forEach((child, index) => {
const isLast = index === node.children.length - 1;
const childConnector = isLast ? '└── ' : '├── ';
const childPrefix = connector === '' ? ' ' : `${prefix}${isLast ? ' ' : '│ '}`;
appendNode(child, childPrefix, childConnector, lines);
});
}
function formatLabel(node: CommandTreeNode): string {
const argumentPart = node.arguments.length > 0 ? ` ${node.arguments.join(' ')}` : '';
const aliasPart = node.aliases.length > 0 ? ` (${node.aliases.join(', ')})` : '';
return `${node.name}${argumentPart}${aliasPart}`;
}
function formatLine(label: string, description: string): string {
if (description.length === 0) {
return label;
}
const padding = label.length >= DESCRIPTION_COLUMN ? ' ' : ' '.repeat(DESCRIPTION_COLUMN - label.length);
return `${label}${padding}${description}`;
}