-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcommander.ts
More file actions
246 lines (216 loc) · 7.72 KB
/
Copy pathcommander.ts
File metadata and controls
246 lines (216 loc) · 7.72 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
import type { Command as CommanderCommand } from 'commander';
import t, { Command as TabCommand, type RootCommand } from './t';
// rawArgs is available on (just) the Commander root command, but is not included in the TypeScript types.
interface CommandWithRawArgs extends CommanderCommand {
rawArgs: string[];
}
const execPath = process.execPath;
const processArgs = process.argv.slice(1);
const quotedExecPath = quoteIfNeeded(execPath);
const quotedProcessArgs = processArgs.map(quoteIfNeeded);
const quotedProcessExecArgs = process.execArgv.map(quoteIfNeeded);
const x = `${quotedExecPath} ${quotedProcessExecArgs.join(' ')} ${quotedProcessArgs[0]}`;
function quoteIfNeeded(path: string): string {
return path.includes(' ') ? `'${path}'` : path;
}
export default function tab(
instance: CommanderCommand,
completionConfig?: { completionCommandName?: string }
): RootCommand {
const programName = instance.name();
// Process the root command
processRootCommand(instance);
// Process all subcommands
processSubcommands(instance);
// Make a `completion` command with a required command-argument.
const completionCommandName =
completionConfig?.completionCommandName ?? 'complete';
const completionCommand = instance
.createCommand(completionCommandName)
.description('Generate shell completion scripts')
.addArgument(
instance
.createArgument('<shell>', 'Shell type for completion script')
.choices(['zsh', 'bash', 'fish', 'powershell'])
)
.action((shell) => {
t.setup(programName, x, shell);
});
completionCommand.copyInheritedSettings(instance);
// Make a `complete` command for generating tab-time complete suggestions.
const completeCommand = instance
.createCommand('complete')
.description('Generate completion suggestions')
.usage('-- [args...]')
.argument('[args...]')
.action((args) => {
if (completionCommandName !== 'complete') {
// Check for user trying to generate shell completion script, since not using usual tab overloaded complete `command`.
const rawArgs = (instance as CommandWithRawArgs).rawArgs;
if (args.length === 1 && !rawArgs.includes('--'))
instance.error(
`error: completion requests are called like \`complete -- [args]\`.\n(Did you mean \`${completionCommandName} ${args[0]}\` to generate shell script?)`
);
}
t.parse(args);
});
completeCommand.copyInheritedSettings(instance);
if (completionCommandName !== 'complete') {
// We have indepdendent commands so can hook them up directly.
instance.addCommand(completionCommand);
instance.addCommand(completeCommand, { hidden: true });
} else {
// We need to add a dual-use command, work out calling pattern, and dispatch.
instance
.command('complete')
.description('Generate shell completion scripts')
.argument(
'[shell]',
'shell type (choices: "zsh", "bash", "fish", "powershell")'
)
.allowExcessArguments()
.action((_shell, _options, cmd) => {
// Work out how we are being called, by user or by script as completion handler.
const rawArgs = (instance as CommandWithRawArgs).rawArgs;
const completeIndex = rawArgs.indexOf('complete');
const dashDashIndex = rawArgs.indexOf('--');
if (
completeIndex !== -1 &&
dashDashIndex !== -1 &&
dashDashIndex === completeIndex + 1
) {
// Commander stripped `--`, so put it back for reparse
completeCommand.parse(['--', ...cmd.args], { from: 'user' });
} else {
completionCommand.parse(cmd.args, {
from: 'user',
});
}
});
}
return t;
}
/**
* Detect whether a commander option flag expects a value argument.
* Options with `<value>` or `[value]` in their flags are value-taking.
*/
function optionTakesValue(flags: string): boolean {
return flags.includes('<') || flags.includes('[');
}
/**
* Register a commander option with the tab library, correctly setting
* isBoolean based on whether the option takes a value.
*
* The tab Command.option() method infers isBoolean from the argument types:
* - string arg → alias, isBoolean=true
* - function arg → handler, isBoolean=false
* So for value-taking options with an alias, we pass a no-op handler
* and the alias separately to get isBoolean=false.
*/
function registerOption(
tabCommand: {
option: (
value: string,
description: string,
handlerOrAlias?: ((...args: unknown[]) => void) | string,
alias?: string
) => unknown;
},
flags: string,
longFlag: string,
description: string,
shortFlag?: string
): void {
const takesValue = optionTakesValue(flags);
if (shortFlag) {
if (takesValue) {
// Pass a no-op handler to force isBoolean=false, with alias as 4th arg
tabCommand.option(longFlag, description, () => {}, shortFlag);
} else {
tabCommand.option(longFlag, description, shortFlag);
}
} else {
if (takesValue) {
tabCommand.option(longFlag, description, () => {});
} else {
tabCommand.option(longFlag, description);
}
}
}
function processRootCommand(command: CommanderCommand): void {
// Add root command options to the root t instance
for (const option of command.options) {
// Extract short flag from the name if it exists (e.g., "-c, --config" -> "c")
const flags = option.flags;
const shortFlag = flags.match(/^-([a-zA-Z]), --/)?.[1];
const longFlag = flags.match(/--([a-zA-Z0-9-]+)/)?.[1];
if (longFlag) {
registerOption(t, flags, longFlag, option.description || '', shortFlag);
}
}
processArguments(t, command);
}
function processArguments(tabCommand: TabCommand, cmd: CommanderCommand): void {
for (const arg of cmd.registeredArguments) {
const choices = arg.argChoices;
if (choices?.length) {
tabCommand.argument(
arg.name(),
(complete) => {
for (const choice of choices) complete(choice, '');
},
arg.variadic
);
} else {
tabCommand.argument(arg.name(), undefined, arg.variadic);
}
}
}
function processSubcommands(rootCommand: CommanderCommand): void {
// Build a map of command paths
const commandMap = new Map<string, CommanderCommand>();
// Collect all commands with their full paths
collectCommands(rootCommand, '', commandMap);
// Process each command
for (const [path, cmd] of commandMap.entries()) {
if (path === '') continue; // Skip root command, already processed
// Add command using t.ts API
const command = t.command(path, cmd.description() || '');
// Add command options
for (const option of cmd.options) {
// Extract short flag from the name if it exists (e.g., "-c, --config" -> "c")
const flags = option.flags;
const shortFlag = flags.match(/^-([a-zA-Z]), --/)?.[1];
const longFlag = flags.match(/--([a-zA-Z0-9-]+)/)?.[1];
if (longFlag) {
registerOption(
command,
flags,
longFlag,
option.description || '',
shortFlag
);
}
}
processArguments(command, cmd);
}
}
function collectCommands(
command: CommanderCommand,
parentPath: string,
commandMap: Map<string, CommanderCommand>
): void {
// Add this command to the map
commandMap.set(parentPath, command);
// Process subcommands
for (const subcommand of command.commands) {
// Skip the completion command
if (subcommand.name() === 'complete') continue;
// Build the full path for this subcommand
const subcommandPath = parentPath
? `${parentPath} ${subcommand.name()}`
: subcommand.name();
// Recursively collect subcommands
collectCommands(subcommand, subcommandPath, commandMap);
}
}