UNPKG

1.77 kBJavaScriptView Raw
1"use strict";
2
3const GetterSetter = require('./utils').GetterSetter;
4const Validator = require('./validator');
5
6class Argument extends GetterSetter {
7
8 /**
9 *
10 * @param {String} synopsis - Option synopsis
11 * @param {String} description - Option description
12 * @param {String|RegExp|Function|Number} [validator] - Option validator, used for checking or casting
13 * @param {*} [defaultValue] - Default value
14 * @param {Program} program - program instance
15 */
16 constructor(synopsis, description, validator, defaultValue, program) {
17 super();
18 this._type = synopsis.substring(0, 1) === '[' ? Argument.OPTIONAL : Argument.REQUIRED;
19 this._variadic = synopsis.substr(-4, 3) === '...';
20 this._synopsis = synopsis;
21 this._name = this.getCleanNameFromNotation(synopsis);
22 this._description = description;
23 this._validator = validator ? new Validator(validator, program) : null;
24 this._default = defaultValue;
25 this.synopsis = this.makeGetterSetter('synopsis');
26 this.description = this.makeGetterSetter('description');
27 this.default = this.makeGetterSetter('default');
28 }
29
30 hasDefault() {
31 return this.default() !== undefined;
32 }
33
34 isRequired() {
35 return this._type === Argument.REQUIRED
36 }
37
38 getChoices() {
39 return this._validator ? this._validator.getChoices() : [];
40 }
41
42 isOptional() {
43 return this._type === Argument.OPTIONAL
44 }
45
46 isVariadic() {
47 return this._variadic === true
48 }
49
50 name() {
51 return this._name;
52 }
53
54 _validate(value) {
55 if (!this._validator) {
56 return value;
57 }
58 return this._validator.validate(value);
59 }
60}
61
62Object.defineProperties(Argument, {
63 "OPTIONAL": {
64 value: 'optional'
65 },
66 "REQUIRED": {
67 value: 'required'
68 }
69});
70
71module.exports = Argument;