/
dependent-prompts.ts
65 lines (56 loc) · 1.85 KB
/
dependent-prompts.ts
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
import { InteractiveCommand } from "../src/interactive-command.ts";
import { InteractiveOption } from "../src/interactive-option.ts";
/**
* Set the default value of an option to the return value of a callback function.
* This is useful for creating dependant prompts for options.
*
* @param option
* @param callback - A function that returns the default value for the option
*/
export const setPromptDefault = (
option: InteractiveOption,
callback: (command: InteractiveCommand) => string,
) => {
let { readFunction } = option;
readFunction = readFunction?.bind(option) as typeof readFunction;
option.readFunction = async (
currentValue: unknown,
option: InteractiveOption,
command: InteractiveCommand,
) =>
readFunction?.(
currentValue ?? (await Promise.resolve(callback(command))),
option,
command,
);
};
const program = new InteractiveCommand();
const shippingAddress = new InteractiveOption(
"-a, --shipping-address <address>",
"shipping address",
).makeOptionMandatory();
const billingAddress = new InteractiveOption(
"-b, --billing-address <address>",
"billing address",
).makeOptionMandatory();
// Set the default value of the billing address to the value of the shipping
// address
setPromptDefault(
billingAddress,
(command) => command.opts<{ shippingAddress: string }>().shippingAddress,
);
program
.command("order")
.addOption(shippingAddress)
.addOption(billingAddress)
.action((_options, cmd: InteractiveCommand) => {
console.log("Options: %o", cmd.opts());
});
await program
// Enables interactive mode (when -i or --interactive is passed in)
// This should almost always be called on the root command right before
// calling parseAsync
.interactive("-i, --interactive", "interactive mode")
.parseAsync(process.argv);
// Try the following commands:
// dependent-prompts order -i