ktx/packages/cli/src/command-tree.ts

60 lines
2.1 KiB
TypeScript
Raw Permalink Normal View History

2026-05-13 00:33:24 +02:00
import type { Argument, CommandUnknownOpts } from '@commander-js/extra-typings';
const DESCRIPTION_COLUMN = 42;
export interface CommandTreeNode {
name: string;
description: string;
aliases: string[];
2026-05-13 00:33:24 +02:00
arguments: string[];
children: CommandTreeNode[];
}
2026-05-13 00:33:24 +02:00
export function walkCommandTree(command: CommandUnknownOpts): CommandTreeNode {
return {
name: command.name(),
description: command.description(),
aliases: command.aliases(),
2026-05-13 00:33:24 +02:00
arguments: command.registeredArguments.map(formatArgumentDeclaration),
children: command.commands.map((child) => walkCommandTree(child)),
};
}
export function formatCommandTree(node: CommandTreeNode): string {
const lines: string[] = [];
2026-05-13 00:33:24 +02:00
appendNode(node, '', '', lines);
return `${lines.join('\n')}\n`;
}
2026-05-13 00:33:24 +02:00
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));
const childPrefix =
connector === '' ? `${prefix} ` : `${prefix}${connector === '└── ' ? ' ' : '│ '}`;
2026-05-13 00:33:24 +02:00
node.children.forEach((child, index) => {
const isLast = index === node.children.length - 1;
const childConnector = 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(', ')})` : '';
2026-05-13 00:33:24 +02:00
return `${node.name}${argumentPart}${aliasPart}`;
}
2026-05-13 00:33:24 +02:00
function formatLine(label: string, description: string): string {
if (description.length === 0) {
return label;
}
2026-05-13 00:33:24 +02:00
const padding = label.length >= DESCRIPTION_COLUMN ? ' ' : ' '.repeat(DESCRIPTION_COLUMN - label.length);
return `${label}${padding}${description}`;
}