forked from samchon/typia
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArgumentParser.ts
More file actions
49 lines (46 loc) · 1.65 KB
/
ArgumentParser.ts
File metadata and controls
49 lines (46 loc) · 1.65 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
import commander from "commander";
import inquirer from "inquirer";
import { PackageManager } from "./PackageManager";
export namespace ArgumentParser {
export type Inquiry<T> = (
pack: PackageManager,
command: commander.Command,
prompt: (opt?: inquirer.StreamOptions) => inquirer.PromptModule,
action: (closure: (options: Partial<T>) => Promise<T>) => Promise<T>,
) => Promise<T>;
export const parse = async <T>(
pack: PackageManager,
inquiry: (
pack: PackageManager,
command: commander.Command,
prompt: (opt?: inquirer.StreamOptions) => inquirer.PromptModule,
action: (closure: (options: Partial<T>) => Promise<T>) => Promise<T>,
) => Promise<T>,
): Promise<T> => {
// TAKE OPTIONS
const action = (closure: (options: Partial<T>) => Promise<T>) =>
new Promise<T>((resolve, reject) => {
commander.program.action(async (...args: unknown[]) => {
try {
// Commander passes: (positionalArgs..., options, command)
// Use program.opts() for reliable option extraction
const options = commander.program.opts() as Partial<T>;
// If there are positional arguments (files), attach them to options
if (args.length > 0 && Array.isArray(args[0])) {
(options as Partial<T> & { files?: string[] }).files = args[0];
}
resolve(await closure(options));
} catch (exp) {
reject(exp);
}
});
commander.program.parseAsync().catch(reject);
});
return inquiry(
pack,
commander.program,
inquirer.createPromptModule,
action,
);
};
}