-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelp.ts
More file actions
346 lines (298 loc) · 9.86 KB
/
Copy pathhelp.ts
File metadata and controls
346 lines (298 loc) · 9.86 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
import chalk from "chalk";
import type { Command, Help, HelpContext, Option } from "commander";
interface Example {
description: string;
command: string;
}
const examplesMap = new WeakMap<Command, Example[]>();
const notesMap = new WeakMap<Command, string[]>();
export function addExamples(cmd: Command, examples: Example[]): void {
examplesMap.set(cmd, examples);
}
export function addNotes(cmd: Command, notes: string[]): void {
notesMap.set(cmd, notes);
}
function header(title: string): string {
return chalk.yellow.bold(title);
}
function findCommand(parent: Command, name: string): Command | undefined {
return parent.commands.find(
(c) => c.name() === name || c.aliases().includes(name),
);
}
function getCommandPath(cmd: Command): string {
const parts: string[] = [];
let current: Command | null = cmd;
while (current) {
parts.unshift(current.name());
current = current.parent;
}
return parts.join(" ");
}
function getRootProgram(cmd: Command): Command {
let root = cmd;
while (root.parent) {
root = root.parent;
}
return root;
}
function formatOptionSynopsis(opt: Option): string {
/* v8 ignore next -- Commander always sets long or short */
const flag = opt.long || opt.short || "";
if (opt.required) {
const match = opt.flags.match(/<([^>]+)>/);
const valueName = match ? match[1] : "value";
return `[${flag}=<${valueName}>]`;
} else if (opt.optional) {
const match = opt.flags.match(/\[([^\]]+)\]/);
const valueName = match ? match[1] : "value";
return `[${flag}[=<${valueName}>]]`;
}
return `[${flag}]`;
}
function formatSynopsis(path: string, cmd: Command): string {
const parts = [path];
for (const arg of cmd.registeredArguments) {
if (arg.required) {
parts.push(`<${arg.name()}>`);
} else {
parts.push(`[<${arg.name()}>]`);
}
}
for (const opt of cmd.options) {
if (opt.hidden) continue;
parts.push(formatOptionSynopsis(opt));
}
return parts.join(" ");
}
function formatOptionList(options: readonly Option[]): string[] {
const maxLen = Math.max(...options.map((o) => o.flags.length));
return options.map((opt) => {
const flags = opt.flags.padEnd(maxLen + 2);
/* v8 ignore next -- Commander always sets description to '' */
return ` ${chalk.green(flags)}${opt.description ?? ""}`;
});
}
function formatGlobalParameters(program: Command): string {
const lines: string[] = [];
lines.push(header("GLOBAL PARAMETERS"));
lines.push("");
lines.push(...formatOptionList(program.options));
lines.push("");
return lines.join("\n");
}
export function formatTopLevelHelp(program: Command): string {
const lines: string[] = [];
lines.push(header("NAME"));
lines.push("");
lines.push(` ${program.name()}`);
lines.push("");
lines.push(header("DESCRIPTION"));
lines.push("");
lines.push(` ${program.description()}`);
lines.push("");
lines.push(header("AVAILABLE COMMANDS"));
lines.push("");
const commands = program.commands
.filter((c) => !(c as Command & { _hidden?: boolean })._hidden)
.slice()
.sort((a, b) => a.name().localeCompare(b.name()));
const maxLen = Math.max(...commands.map((c) => c.name().length));
for (const cmd of commands) {
const name = cmd.name().padEnd(maxLen + 2);
lines.push(` ${chalk.green(name)}${cmd.summary() || cmd.description()}`);
}
lines.push("");
lines.push(formatGlobalParameters(program));
return lines.join("\n");
}
export function formatCommandDetails(
program: Command,
cmd: Command,
path: string,
): string {
const lines: string[] = [];
// NAME
lines.push(header("NAME"));
lines.push("");
const aliases = cmd.aliases().filter((a) => a.length > 0);
if (aliases.length > 0) {
lines.push(` ${path} ${chalk.dim(`(alias: ${aliases.join(", ")})`)}`);
} else {
lines.push(` ${path}`);
}
// DESCRIPTION
lines.push("");
lines.push(header("DESCRIPTION"));
lines.push("");
for (const descLine of cmd.description().split("\n")) {
lines.push(` ${descLine}`);
}
const subcommands = cmd.commands.filter(
(c) => !(c as Command & { _hidden?: boolean })._hidden,
);
if (subcommands.length > 0) {
// Command group with subcommands
lines.push("");
lines.push(header("SYNOPSIS"));
lines.push("");
lines.push(` ${path} <command>`);
lines.push("");
lines.push(header("SUBCOMMANDS"));
lines.push("");
const maxLen = Math.max(...subcommands.map((c) => c.name().length));
for (const sub of subcommands) {
const name = sub.name().padEnd(maxLen + 2);
lines.push(` ${chalk.green(name)}${sub.summary() || sub.description()}`);
}
} else {
// Leaf command
lines.push("");
lines.push(header("SYNOPSIS"));
lines.push("");
lines.push(` ${formatSynopsis(path, cmd)}`);
const options = cmd.options.filter((o) => !o.hidden);
if (options.length > 0) {
lines.push("");
lines.push(header("OPTIONS"));
lines.push("");
lines.push(...formatOptionList(options));
}
}
// EXAMPLES
const examples = examplesMap.get(cmd);
if (examples && examples.length > 0) {
lines.push("");
lines.push(header("EXAMPLES"));
lines.push("");
for (const ex of examples) {
lines.push(` ${ex.description}:`);
lines.push(` $ ${ex.command}`);
lines.push("");
}
}
// NOTES
const notes = notesMap.get(cmd);
if (notes && notes.length > 0) {
lines.push("");
lines.push(header("NOTES"));
lines.push("");
for (const note of notes) {
lines.push(` ${note}`);
}
}
// GLOBAL PARAMETERS
lines.push("");
lines.push(formatGlobalParameters(program));
return lines.join("\n");
}
function unknownCommandError(attempted: string): never {
console.error(chalk.red(`Error: '${attempted}' is not a geonic command.`));
console.error(`\nSee 'geonic help' for available commands.`);
process.exit(1);
}
function showHelp(program: Command, args: string[]): void {
if (args.length === 0) {
console.log(formatTopLevelHelp(program));
return;
}
let current = program;
const resolved: Command[] = [];
for (let i = 0; i < args.length; i++) {
const found = findCommand(current, args[i]);
if (!found) {
unknownCommandError(args.slice(0, i + 1).join(" "));
}
resolved.push(found);
current = found;
}
const target = resolved[resolved.length - 1];
const path = [program.name(), ...resolved.map((c) => c.name())].join(" ");
console.log(formatCommandDetails(program, target, path));
}
export function enforceKnownCommandHelp(program: Command): void {
// Commander prints help and exits 0 when --help/-h is present, even if the
// remaining operand is not a known subcommand (e.g. `geonic hello --help`).
// Wrap outputHelp() on every command group so that case errors with exit 1,
// matching `geonic help <unknown>`. Call after all commands are registered.
// Token the user actually typed to invoke each command (name or alias),
// recorded at dispatch time so error messages echo e.g. "models" as typed,
// not the canonical name "custom-data-models".
const typedNames = new WeakMap<Command, string>();
// Path from the program down to cmd, using the recorded typed tokens.
const typedCommandPath = (cmd: Command): string[] => {
const path: string[] = [];
let current: Command | null = cmd;
while (current && current.parent) {
path.unshift(typedNames.get(current) ?? current.name());
current = current.parent;
}
return path;
};
const visit = (cmd: Command): void => {
if (cmd.commands.length > 0) {
// preSubcommand fires on dispatch, before commander's --help
// short-circuit; parent.args[0] is the operand commander resolved the
// subcommand from. Hooks are not inherited, so attach per group.
cmd.hook("preSubcommand", (parent, subCommand) => {
const token = parent.args[0];
if (token !== undefined) {
typedNames.set(subCommand, token);
}
});
const originalOutputHelp = cmd.outputHelp.bind(cmd);
// Same parameter type as Command.outputHelp (including deprecated overload)
cmd.outputHelp = (
contextOptions?: HelpContext | ((str: string) => string),
): void => {
// cmd.args lists operands first, then unparsed options such as --help.
// Only a leading non-empty, non-dash token is a genuine operand — a
// non-dash token found later may be the value of an unrecognized option.
const operand = cmd.args[0];
if (operand && !operand.startsWith("-") && !findCommand(cmd, operand)) {
unknownCommandError([...typedCommandPath(cmd), operand].join(" "));
}
originalOutputHelp(contextOptions as HelpContext | undefined);
};
}
for (const sub of cmd.commands) {
visit(sub);
}
};
visit(program);
}
export function registerHelpCommand(program: Command): void {
// Disable Commander's built-in help command
program.addHelpCommand(false);
// Override --help to use our wp-cli style format
program.configureHelp({
formatHelp: (cmd: Command, _helper: Help): string => {
const root = getRootProgram(cmd);
if (cmd === root) {
return formatTopLevelHelp(root);
}
const path = getCommandPath(cmd);
return formatCommandDetails(root, cmd, path);
},
});
// Register the `help` command
program
.command("help")
.description("Get help on a specific command")
.argument("[args...]")
.allowUnknownOption()
.action((args: string[]) => {
showHelp(program, args);
});
// Show help when `geonic` is run with no arguments, or show error for unknown commands
program.argument("[command...]").action((commands: string[]) => {
if (commands.length > 0) {
console.error(
`geonic: '${commands[0]}' is not a geonic command. See 'geonic help'.`,
);
process.exitCode = 1;
return;
}
showHelp(program, []);
});
}