-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelp.ts
More file actions
531 lines (476 loc) · 14.1 KB
/
help.ts
File metadata and controls
531 lines (476 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/**
* Help text generation for CLI applications.
*
* Generates formatted, colorized help output for both simple CLIs and
* command-based CLIs. Supports customizable themes, automatic URL linkification
* in terminals that support hyperlinks, option grouping, and automatic epilog
* generation from `package.json` metadata.
*
* @packageDocumentation
*/
import type {
OptionDef,
OptionsSchema,
PositionalDef,
PositionalsSchema,
} from './types.js';
import { link, supportsHyperlinks } from './osc.js';
import {
createStyler,
defaultTheme,
type Styler,
type Theme,
} from './theme.js';
import { readPackageInfoSync } from './version.js';
/**
* Minimal config shape for help generation.
*
* @group Help
* @knipignore
*/
export interface HelpConfig {
commands?: Record<
string,
{
/** Alternative names for this command */
aliases?: string[];
description: string;
options?: OptionsSchema;
positionals?: PositionalsSchema;
}
>;
description?: string;
epilog?: false | string;
name: string;
options?: OptionsSchema;
positionals?: PositionalsSchema;
version?: string;
}
/**
* URL regex pattern for matching URLs in text.
*/
const URL_PATTERN = /https?:\/\/[^\s<>"\])}]+/g;
/**
* Linkify URLs in text if terminal supports hyperlinks. Applies URL styling.
*
* @function
*/
const linkifyText = (
text: string,
styler: Styler,
stream: NodeJS.WriteStream = process.stdout,
): string => {
const canLink = supportsHyperlinks(stream);
return text.replace(URL_PATTERN, (url) => {
const styledUrl = styler.url(url);
return canLink ? link(styledUrl, url) : styledUrl;
});
};
/**
* Generate default epilog from package.json (homepage and repository).
*
* @function
*/
const generateDefaultEpilog = (styler: Styler): string[] => {
const pkgInfo = readPackageInfoSync();
const lines: string[] = [];
if (pkgInfo.homepage) {
const styledUrl = styler.url(pkgInfo.homepage);
const linkedUrl = supportsHyperlinks()
? link(styledUrl, pkgInfo.homepage)
: styledUrl;
lines.push(styler.epilog(`Homepage: ${linkedUrl}`));
}
if (pkgInfo.repository) {
const styledUrl = styler.url(pkgInfo.repository);
const linkedUrl = supportsHyperlinks()
? link(styledUrl, pkgInfo.repository)
: styledUrl;
lines.push(styler.epilog(`Repository: ${linkedUrl}`));
}
return lines;
};
/**
* Format epilog based on config. Returns empty array if epilog is disabled,
* custom epilog lines if provided, or default epilog from package.json.
*
* @function
*/
const formatEpilog = (
config: { epilog?: false | string },
styler: Styler,
): string[] => {
// Explicitly disabled
if (config.epilog === false || config.epilog === '') {
return [];
}
// Custom epilog provided
if (typeof config.epilog === 'string') {
const linkified = linkifyText(config.epilog, styler);
return [styler.epilog(linkified)];
}
// Default: generate from package.json
return generateDefaultEpilog(styler);
};
/**
* Format a single positional for help usage line. Required positionals use
* <name>, optional use [name]. Variadic positionals append "...".
*
* @function
*/
const formatPositionalUsage = (def: PositionalDef, index: number): string => {
const name = def.name ?? `arg${index}`;
const isRequired = def.required || 'default' in def;
const isVariadic = def.type === 'variadic';
const displayName = isVariadic ? `${name}...` : name;
return isRequired ? `<${displayName}>` : `[${displayName}]`;
};
/**
* Build the positionals usage string from a schema.
*
* @function
*/
const buildPositionalsUsage = (schema?: PositionalsSchema): string => {
if (!schema || schema.length === 0) {
return '';
}
return schema
.map((def, index) => formatPositionalUsage(def, index))
.join(' ');
};
/**
* Get type label for help display.
*
* @function
*/
const getTypeLabel = (def: OptionDef): string => {
switch (def.type) {
case 'array': {
const arrayDef = def as { choices?: readonly string[]; items?: string };
if (arrayDef.choices) {
return `(${arrayDef.choices.join(' | ')})[]`;
}
return `${arrayDef.items ?? 'string'}[]`;
}
case 'boolean':
return 'boolean';
case 'count':
return 'count';
case 'enum':
return def.choices.join(' | ');
case 'number':
return 'number';
case 'string':
return 'string';
default:
return 'string';
}
};
/**
* Get the flag text for an option (used for width calculation and display).
*
* @function
*/
const getOptionFlagText = (name: string, def: OptionDef): string => {
// For boolean options with default: true, show --no-<name>
const displayName =
def.type === 'boolean' && def.default === true ? `no-${name}` : name;
// Separate short and long aliases
const shortAlias = def.aliases?.find((a) => a.length === 1);
const longAliases = (def.aliases ?? [])
.filter((a) => a.length > 1)
.sort((a, b) => a.length - b.length);
// Build flag string: -v, --verb, --verbose
const flagParts: string[] = [];
if (shortAlias && displayName === name) {
flagParts.push(`-${shortAlias}`);
}
for (const alias of longAliases) {
flagParts.push(`--${alias}`);
}
flagParts.push(`--${displayName}`);
// If no short alias and no long aliases, add padding
return flagParts.length === 1 && !shortAlias
? ` ${flagParts[0]}`
: flagParts.join(', ');
};
/**
* Calculate the max flag width for a set of options.
*
* @function
*/
const calculateMaxFlagWidth = (
options: Array<{ def: OptionDef; name: string }>,
): number => {
let maxWidth = 0;
for (const { def, name } of options) {
const flagText = getOptionFlagText(name, def);
maxWidth = Math.max(maxWidth, flagText.length);
}
return maxWidth;
};
/**
* Format a single option for help output.
*
* For boolean options with `default: true`, shows `--no-<name>` instead of
* `--<name>` since that's how users would turn it off.
*
* Displays aliases in order: short alias first (-v), then multi-char aliases
* sorted by length (--verb), then the canonical name (--verbose).
*
* @function
*/
const formatOptionHelp = (
name: string,
def: OptionDef,
styler: Styler,
maxFlagWidth?: number,
): string => {
const parts: string[] = [];
const flagText = getOptionFlagText(name, def);
parts.push(` ${styler.flag(flagText)}`);
// Pad to align descriptions using provided maxFlagWidth or calculate dynamically
const basePadding = Math.max(24, (maxFlagWidth ?? flagText.length) + 4);
const padding = Math.max(0, basePadding - flagText.length - 2);
parts.push(' '.repeat(padding));
// Description
if (def.description) {
parts.push(styler.description(def.description));
}
// Type and default
const typeLabel = getTypeLabel(def);
const suffixParts = [styler.type(`[${typeLabel}]`)];
if ('default' in def && def.default !== undefined) {
suffixParts.push(
`${styler.defaultText('default:')} ${styler.defaultValue(JSON.stringify(def.default))}`,
);
}
parts.push(' ', suffixParts.join(' '));
return parts.join('');
};
/**
* Check if config has commands.
*
* @function
*/
const hasCommands = (
config: HelpConfig,
): config is HelpConfig & {
commands: Record<string, { description: string }>;
} => config.commands !== undefined && Object.keys(config.commands).length > 0;
/**
* Generate help text for a bargs config.
*
* @function
* @group Help
*/
export const generateHelp = (
config: HelpConfig,
theme: Theme = defaultTheme,
): string => {
const styler = createStyler(theme);
const lines: string[] = [];
// Header
const version = config.version ? ` v${config.version}` : '';
lines.push('');
lines.push(
`${styler.scriptName(config.name)}${styler.defaultValue(version)}`,
);
if (config.description) {
const linkifiedDesc = linkifyText(config.description, styler);
lines.push(` ${styler.description(linkifiedDesc)}`);
}
lines.push('');
// Build positional names for usage line
const posNames: string[] = [];
if (config.positionals && config.positionals.length > 0) {
for (let i = 0; i < config.positionals.length; i++) {
const pos = config.positionals[i]!;
const formatted = formatPositionalUsage(pos, i);
posNames.push(styler.positional(formatted));
}
}
// Usage
lines.push(styler.sectionHeader('USAGE'));
if (hasCommands(config)) {
const posStr = posNames.length > 0 ? ` ${posNames.join(' ')}` : '';
lines.push(styler.usage(` $ ${config.name} <command> [options]${posStr}`));
} else {
const posStr = posNames.length > 0 ? ` ${posNames.join(' ')}` : '';
lines.push(styler.usage(` $ ${config.name} [options]${posStr}`));
}
lines.push('');
// Commands
if (hasCommands(config)) {
lines.push(styler.sectionHeader('COMMANDS'));
for (const [name, cmd] of Object.entries(config.commands)) {
// Build command name with aliases: "add, a, new" or just "add"
// Calculate raw length for padding (without ANSI codes)
const rawAliasStr =
cmd.aliases && cmd.aliases.length > 0
? `${name}, ${cmd.aliases.join(', ')}`
: name;
const padding = Math.max(2, 20 - rawAliasStr.length);
const styledCmd = cmd.aliases?.length
? `${styler.command(name)}, ${styler.commandAlias(cmd.aliases.join(', '))}`
: styler.command(name);
lines.push(
` ${styledCmd}${' '.repeat(padding)}${styler.description(cmd.description)}`,
);
}
lines.push('');
}
// Options
if (config.options && Object.keys(config.options).length > 0) {
// Group options
const groups = new Map<string, Array<{ def: OptionDef; name: string }>>();
const ungrouped: Array<{ def: OptionDef; name: string }> = [];
for (const [name, def] of Object.entries(config.options)) {
if (def.hidden) {
continue;
}
if (def.group) {
const group = groups.get(def.group) ?? [];
group.push({ def, name });
groups.set(def.group, group);
} else {
ungrouped.push({ def, name });
}
}
// Calculate max flag width across all visible options for alignment
const allOptions = [...ungrouped, ...Array.from(groups.values()).flat()];
const maxFlagWidth = calculateMaxFlagWidth(allOptions);
// Print grouped options
for (const [groupName, options] of Array.from(groups.entries())) {
lines.push(styler.sectionHeader(groupName.toUpperCase()));
for (const opt of options) {
lines.push(formatOptionHelp(opt.name, opt.def, styler, maxFlagWidth));
}
lines.push('');
}
// Print ungrouped
if (ungrouped.length > 0) {
const label = hasCommands(config) ? 'GLOBAL OPTIONS' : 'OPTIONS';
lines.push(styler.sectionHeader(label));
for (const opt of ungrouped) {
lines.push(formatOptionHelp(opt.name, opt.def, styler, maxFlagWidth));
}
lines.push('');
}
}
// Positionals
if (config.positionals && config.positionals.length > 0) {
lines.push(styler.sectionHeader('POSITIONALS'));
for (let i = 0; i < config.positionals.length; i++) {
const pos = config.positionals[i]!;
const name = pos.name ?? `arg${i}`;
const formatted = pos.required ? `<${name}>` : `[${name}]`;
const padding = Math.max(0, 20 - formatted.length);
const desc = pos.description ?? '';
lines.push(
` ${styler.positional(formatted)}${' '.repeat(padding)}${styler.description(desc)}`,
);
}
lines.push('');
}
// Footer
if (hasCommands(config)) {
lines.push(
styler.example(
`Run '${config.name} <command> --help' for command-specific help.`,
),
);
lines.push('');
}
// Epilog
const epilogLines = formatEpilog(config, styler);
if (epilogLines.length > 0) {
lines.push(...epilogLines);
lines.push('');
}
return lines.join('\n');
};
/**
* Generate help text for a specific command.
*
* @function
* @group Help
*/
export const generateCommandHelp = (
config: HelpConfig,
commandName: string,
theme: Theme = defaultTheme,
): string => {
const styler = createStyler(theme);
const command = config.commands?.[commandName];
if (!command) {
return `Unknown command: ${commandName}`;
}
const lines: string[] = [];
// Header
lines.push('');
lines.push(
` ${styler.scriptName(config.name)} ${styler.command(commandName)}`,
);
const linkifiedDesc = linkifyText(command.description, styler);
lines.push(` ${styler.description(linkifiedDesc)}`);
lines.push('');
// Usage
lines.push(styler.sectionHeader('USAGE'));
const positionalsPart = buildPositionalsUsage(command.positionals);
const usageParts = [
`$ ${config.name} ${commandName}`,
'[options]',
positionalsPart,
]
.filter(Boolean)
.join(' ');
lines.push(styler.usage(` ${usageParts}`));
lines.push('');
// Collect all visible options for alignment calculation
const allOptions: Array<{ def: OptionDef; name: string }> = [];
if (command.options) {
for (const [name, def] of Object.entries(command.options)) {
if (!def.hidden) {
allOptions.push({ def, name });
}
}
}
if (config.options) {
for (const [name, def] of Object.entries(config.options)) {
if (!def.hidden) {
allOptions.push({ def, name });
}
}
}
const maxFlagWidth = calculateMaxFlagWidth(allOptions);
// Command options
if (command.options && Object.keys(command.options).length > 0) {
lines.push(styler.sectionHeader('OPTIONS'));
for (const [name, def] of Object.entries(command.options)) {
if (def.hidden) {
continue;
}
lines.push(formatOptionHelp(name, def, styler, maxFlagWidth));
}
lines.push('');
}
// Global options
if (config.options && Object.keys(config.options).length > 0) {
lines.push(styler.sectionHeader('GLOBAL OPTIONS'));
for (const [name, def] of Object.entries(config.options)) {
if (def.hidden) {
continue;
}
lines.push(formatOptionHelp(name, def, styler, maxFlagWidth));
}
lines.push('');
}
// Epilog
const epilogLines = formatEpilog(config, styler);
if (epilogLines.length > 0) {
lines.push(...epilogLines);
lines.push('');
}
return lines.join('\n');
};