1 | ;
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const error_1 = require("./error");
|
4 | // jsdoc, see constructor.
|
5 | class Argument {
|
6 | /**
|
7 | * class of argument.
|
8 | * ```
|
9 | * cmd --path foo/bar buzz.txt
|
10 | * ↑ this one!
|
11 | * ```
|
12 | * @param arg pass '<foo>'(required) or '[foo]'(optional) or '<foo...>'(required & variadic) or '[foo...]'(optional & variadic)
|
13 | * @class
|
14 | */
|
15 | constructor(arg) {
|
16 | switch (arg.charAt(0)) {
|
17 | case "<":
|
18 | this.required = true;
|
19 | this.name = arg.slice(1, -1);
|
20 | break;
|
21 | case "[":
|
22 | this.required = false;
|
23 | this.name = arg.slice(1, -1);
|
24 | break;
|
25 | default:
|
26 | throw new error_1.CommandpostError({
|
27 | message: `unsupported format: ${arg}`,
|
28 | parts: [arg],
|
29 | reason: error_1.ErrorReason.UnsupportedFormatArgument,
|
30 | params: {
|
31 | origin: this,
|
32 | arg,
|
33 | },
|
34 | });
|
35 | }
|
36 | if (/\.\.\.$/.test(this.name)) {
|
37 | this.name = this.name.slice(0, -3);
|
38 | this.variadic = true;
|
39 | }
|
40 | else {
|
41 | this.variadic = false;
|
42 | }
|
43 | }
|
44 | /**
|
45 | * parse args.
|
46 | * build to opts.
|
47 | *
|
48 | * e.g. #1
|
49 | * instance member: name=foo, required=true, variadic=false
|
50 | * method arguments: opts={}, args=["foo!", "bar!"].
|
51 | * opts are modified to { foo: "foo!" } and return ["bar!"].
|
52 | *
|
53 | * e.g. #2
|
54 | * instance member: name=foo, required=false, variadic=true
|
55 | * method arguments: opts={}, args=["foo!", "bar!"].
|
56 | * opts are modified to { foo: ["foo!", "bar!"] } and return [].
|
57 | *
|
58 | * @param opts build target object
|
59 | * @param args
|
60 | * @returns {string[]} rest args
|
61 | */
|
62 | parse(opts, args) {
|
63 | if (this.required && this.variadic && args.length === 0) {
|
64 | throw new error_1.CommandpostError({
|
65 | message: `${this.name} requires more than one argument`,
|
66 | parts: [this.name],
|
67 | reason: error_1.ErrorReason.ArgumentsRequired,
|
68 | params: {
|
69 | origin: this,
|
70 | opts,
|
71 | args,
|
72 | },
|
73 | });
|
74 | }
|
75 | if (this.variadic) {
|
76 | opts[this.name] = args;
|
77 | args = [];
|
78 | return args;
|
79 | }
|
80 | let arg = args.shift();
|
81 | if (this.required && !arg) {
|
82 | throw new error_1.CommandpostError({
|
83 | message: `${this.name} is required`,
|
84 | reason: error_1.ErrorReason.ArgumentRequired,
|
85 | parts: [this.name],
|
86 | params: {
|
87 | origin: this,
|
88 | opts,
|
89 | args,
|
90 | },
|
91 | });
|
92 | }
|
93 | opts[this.name] = arg;
|
94 | return args;
|
95 | }
|
96 | }
|
97 | exports.default = Argument;
|
98 | //# sourceMappingURL=argument.js.map |
\ | No newline at end of file |