blob: e53f9f45d8d0829e5b0e5ad0e213034b3e77a9dd [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3const fs = require('fs');
4
5const CoaObject = require('./coaobject');
6
7/**
8 * COA Parameter
9 *
10 * Base class for options and arguments
11 *
12 * --------|-----|-----|-----
13 * | Cmd | Opt | Arg
14 * --------|-----|-----|-----
15 * arr | | ✓ | ✓
16 * req | | ✓ | ✓
17 * val | | ✓ | ✓
18 * def | | ✓ | ✓
19 * input | | ✓ | ✓
20 * output | | ✓ | ✓
21 *
22 * @class CoaParam
23 * @extends CoaObject
24 */
25module.exports = class CoaParam extends CoaObject {
26 constructor(cmd) {
27 super(cmd);
28
29 this._arr = false;
30 this._req = false;
31 this._val = undefined;
32 this._def = undefined;
33 }
34
35 /**
36 * Makes a param accepts multiple values.
37 * Otherwise, the value will be used by the latter passed.
38 *
39 * @returns {COA.CoaParam} - this instance (for chainability)
40 */
41 arr() {
42 this._arr = true;
43 return this;
44 }
45
46 /**
47 * Makes a param required.
48 *
49 * @returns {COA.CoaParam} - this instance (for chainability)
50 */
51 req() {
52 this._req = true;
53 return this;
54 }
55
56 /**
57 * Set a validation (or value) function for param.
58 * Value from command line passes through before becoming available from API.
59 * Using for validation and convertion simple types to any values.
60 *
61 * @param {Function} val - validating function,
62 * invoked in the context of option instance
63 * and has one parameter with value from command line.
64 * @returns {COA.CoaParam} - this instance (for chainability)
65 */
66 val(val) {
67 this._val = val;
68 return this;
69 }
70
71 /**
72 * Set a default value for param.
73 * Default value passed through validation function as ordinary value.
74 *
75 * @param {*} def - default value of function generator
76 * @returns {COA.CoaParam} - this instance (for chainability)
77 */
78 def(def) {
79 this._def = def;
80 return this;
81 }
82
83 /**
84 * Make option value inputting stream.
85 * It's add useful validation and shortcut for STDIN.
86 *
87 * @returns {COA.CoaParam} - this instance (for chainability)
88 */
89 input() {
90 process.stdin.pause();
91 return this
92 .def(process.stdin)
93 .val(function(v) {
94 if(typeof v !== 'string')
95 return v;
96
97 if(v === '-')
98 return process.stdin;
99
100 const s = fs.createReadStream(v, { encoding : 'utf8' });
101 s.pause();
102 return s;
103 });
104 }
105
106 /**
107 * Make option value outputing stream.
108 * It's add useful validation and shortcut for STDOUT.
109 *
110 * @returns {COA.CoaParam} - this instance (for chainability)
111 */
112 output() {
113 return this
114 .def(process.stdout)
115 .val(function(v) {
116 if(typeof v !== 'string')
117 return v;
118
119 if(v === '-')
120 return process.stdout;
121
122 return fs.createWriteStream(v, { encoding : 'utf8' });
123 });
124 }
125};