UNPKG

6.21 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var chek_1 = require("chek");
4var logger_1 = require("./logger");
5// The original args with node and executed path stripped.
6var _args = process.argv.slice(2);
7var _command = null;
8// Array of packages to install
9var _commands = [];
10// All arguments normalized
11var _normalized = [];
12// Flags passed in cli.
13var _flags = {};
14// Expression for finding flags.
15var _flagExp = /^--?/;
16// Checks if flag is inverse.
17var _noFlagExp = /^--no-/;
18/**
19 * Cast To Type
20 * : Loosely tries to cast numbers and booleans.
21 *
22 * @param val the value to be cast.
23 */
24function castToType(val) {
25 if (/^(true|false)$/.test(val))
26 return chek_1.toBoolean(val);
27 if (/^[\d\.]+$/.test(val))
28 return chek_1.toNumber(val);
29 return val;
30}
31exports.castToType = castToType;
32/**
33 * Flags To Array
34 * : Convert flag object to array.
35 *
36 * @param flags object containing flags.
37 */
38function flagsToArray(flags) {
39 var arr = [];
40 for (var k in flags) {
41 var flag = flags[k];
42 var prefix = flags[k] === false ? '--no-' : k.length > 1 ? '--' : '-';
43 arr.push(prefix + k);
44 if (!chek_1.isBoolean(flags[k]))
45 arr.push(flags[k]);
46 }
47 return arr;
48}
49exports.flagsToArray = flagsToArray;
50/**
51 * Split Args
52 * : Splits string of command arguments honoring quotes.
53 *
54 * @param str the string representing arguments.
55 */
56function splitArgs(str) {
57 if (chek_1.isArray(str))
58 return str;
59 if (!chek_1.isString(str))
60 return [];
61 var arr = [];
62 str
63 .split(/(\x22[^\x22]*\x22)/)
64 .filter(function (x) { return x; })
65 .forEach(function (s) {
66 if (s.match('\x22'))
67 arr.push(s.replace(/\x22/g, ''));
68 else
69 arr = arr.concat(s.trim().split(' '));
70 });
71 return arr;
72}
73exports.splitArgs = splitArgs;
74/**
75 * Normalize
76 * : Spreads multi flag arguments and breaks arguments usign = sign.
77 *
78 * @example
79 * -am: returns -a, -m.
80 * --flag=value: returns --flag, value.
81 *
82 * @param args arguments to be normalized.
83 */
84function normalizeArgs(args, exclude) {
85 var result = [];
86 args = splitArgs(args || []);
87 exclude = splitArgs(exclude || []);
88 args.slice(0).forEach(function (arg) {
89 var val;
90 if (~arg.indexOf('=')) {
91 var kv = arg.split('=');
92 arg = kv[0];
93 val = kv[1];
94 }
95 if (/^-{1}[a-z]/i.test(arg)) {
96 var spread = arg.slice(1).split('').map(function (a) { return '-' + a; });
97 if (val)
98 spread.push(val);
99 result = result.concat(spread);
100 }
101 else {
102 result.push(arg);
103 if (val)
104 result.push(val);
105 }
106 });
107 return filterArgs(result, exclude);
108}
109exports.normalizeArgs = normalizeArgs;
110/**
111 * Filter Args
112 * : Filters an array of arguments by exclusion list.
113 *
114 * @param args the arguments to be filtered.
115 * @param exclude the arguments to be excluded.
116 */
117function filterArgs(args, exclude) {
118 args = splitArgs(args || []);
119 exclude = splitArgs(exclude || []);
120 var clone = args.slice(0);
121 return clone.filter(function (arg, i) {
122 if (!~exclude.indexOf(arg))
123 return true;
124 var next = clone[i + 1];
125 if (_flagExp.test(arg) && next && !_flagExp.test(next))
126 clone.splice(i + 1, 1);
127 return false;
128 });
129}
130exports.filterArgs = filterArgs;
131/**
132 * Merge Args
133 * : Merges two sets of command arguments.
134 *
135 * @param def array of default args.
136 * @param args array of new args.
137 */
138function mergeArgs(def, args, exclude) {
139 exclude = splitArgs(exclude || []);
140 def = normalizeArgs(def);
141 args = normalizeArgs(args);
142 var clone = def.slice(0);
143 args.forEach(function (arg, i) {
144 var next = args[i + 1];
145 var isFlag = _flagExp.test(arg);
146 var isFlagNext = _flagExp.test(next || '');
147 var defIdx = def.indexOf(arg);
148 // Arg exists check if flag that accepts value.
149 if (~defIdx && isFlag && !isFlagNext) {
150 clone[defIdx + 1] = next;
151 args.splice(i + 1, 1);
152 }
153 else if (!~defIdx) {
154 clone.push(arg);
155 }
156 });
157 return filterArgs(clone, exclude);
158}
159exports.mergeArgs = mergeArgs;
160/**
161 * Parse
162 * : Parses command arguments.
163 *
164 * @param args the arguments to be parsed if null uses process.argv.slice(2)
165 * @param exclude any flags or commands that should be excluded.
166 */
167function parse(args, exclude) {
168 var normalized = normalizeArgs(args || _args, exclude);
169 var clone = normalized.slice(0);
170 clone.forEach(function (arg, i) {
171 var next = clone[i + 1];
172 var isFlag = _flagExp.test(arg);
173 var isFlagNext = _flagExp.test(next || '');
174 var isNoFlag = _noFlagExp.test(arg);
175 if (isFlag) {
176 var key = isNoFlag ? arg.replace(_noFlagExp, '') : arg.replace(_flagExp, '');
177 key = key.split('.').map(function (k) { return chek_1.camelcase(k); }).join('.'); // handle dot keys.
178 var curVal = chek_1.get(_flags, key);
179 var exists = chek_1.isValue(curVal);
180 if (exists)
181 curVal = chek_1.toArray(curVal, []);
182 if (!isFlagNext && next) {
183 if (isNoFlag)
184 logger_1.log.error("Oops cannot set flag value using inverse (--no-xxx) flag " + arg + ".");
185 var val = castToType(next);
186 if (exists) {
187 curVal.push(val);
188 val = curVal;
189 }
190 chek_1.set(_flags, key, val);
191 clone.splice(i + 1, 1);
192 }
193 else {
194 chek_1.set(_flags, key, isNoFlag ? false : true);
195 }
196 }
197 else {
198 _commands.push(castToType(arg));
199 }
200 });
201 if (_commands)
202 _command = _commands.shift();
203 return {
204 command: _command,
205 commands: _commands,
206 cmd: _command,
207 cmds: _commands,
208 flags: _flags,
209 source: _args,
210 normalized: normalized
211 };
212}
213exports.parse = parse;
214//# sourceMappingURL=argv.js.map
\No newline at end of file