-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcommander.ts
More file actions
222 lines (196 loc) · 6.69 KB
/
commander.ts
File metadata and controls
222 lines (196 loc) · 6.69 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
import * as zsh from './zsh';
import * as bash from './bash';
import * as fish from './fish';
import * as powershell from './powershell';
import type { Command as CommanderCommand, ParseOptions } from 'commander';
import t, { type RootCommand } from './t';
import { assertDoubleDashes } from './shared';
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): RootCommand {
const programName = instance.name();
// Process the root command
processRootCommand(instance);
// Process all subcommands
processSubcommands(instance);
// Add the complete command for normal shell script generation
instance
.command('complete [shell]')
.description('Generate shell completion scripts')
.action(async (shell) => {
switch (shell) {
case 'zsh': {
const script = zsh.generate(programName, x);
console.log(script);
break;
}
case 'bash': {
const script = bash.generate(programName, x);
console.log(script);
break;
}
case 'fish': {
const script = fish.generate(programName, x);
console.log(script);
break;
}
case 'powershell': {
const script = powershell.generate(programName, x);
console.log(script);
break;
}
case 'debug': {
// Debug mode to print all collected commands
const commandMap = new Map<string, CommanderCommand>();
collectCommands(instance, '', commandMap);
console.log('Collected commands:');
for (const [path, cmd] of commandMap.entries()) {
console.log(
`- ${path || '<root>'}: ${cmd.description() || 'No description'}`
);
}
break;
}
default: {
console.error(`Unknown shell: ${shell}`);
console.error('Supported shells: zsh, bash, fish, powershell');
process.exit(1);
}
}
});
// Override the parse method to handle completion requests before normal parsing
const originalParse = instance.parse.bind(instance);
instance.parse = function (argv?: readonly string[], options?: ParseOptions) {
const args = argv || process.argv;
const completeIndex = args.findIndex((arg) => arg === 'complete');
const dashDashIndex = args.findIndex((arg) => arg === '--');
if (
completeIndex !== -1 &&
dashDashIndex !== -1 &&
dashDashIndex > completeIndex
) {
// This is a completion request, handle it directly
const extra = args.slice(dashDashIndex + 1);
// Handle the completion directly
assertDoubleDashes(programName);
t.parse(extra);
return instance;
}
// Normal parsing
return originalParse(argv, options);
};
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);
}
}
}
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
);
}
}
}
}
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);
}
}