UNPKG

2.75 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var chek_1 = require("chek");
4// The original array.
5var _args = process.argv.slice(0);
6exports.args = _args;
7// The original args with node and executed path stripped.
8var _baseArgs = _args.slice(2);
9exports.normalized = _baseArgs;
10// The original args without node, executed path and first command stripped.
11var _optionArgs = _baseArgs.slice(1);
12exports.options = _optionArgs;
13// Array of packages to install
14var _cmds = [];
15// Flags passed in cli.
16var _flags = {};
17// Expression for finding flags.
18var _flagExp = /^--?/;
19// Holds array of args to be excluded.
20var _exclude = [];
21/**
22 * Is Flag
23 * Checks if value is type of flag param.
24 *
25 * @param flag the value to inspect to detect if is flag.
26 */
27function isFlag(flag) {
28 if (_flagExp.test(flag)) {
29 if (/^--/.test(flag))
30 return 'value';
31 return 'boolean';
32 }
33 return false;
34}
35exports.isFlag = isFlag;
36/**
37 * Parse Element
38 * Inspects value parses value as command or flag.
39 *
40 * @param val the value to inspect/convert to flag.
41 * @param idx the current index position of the value.
42 * @param args the array of argv params.
43 */
44function parseElement(val, idx, args) {
45 var flagType = isFlag(val);
46 if (!flagType)
47 return false;
48 if (flagType === 'boolean')
49 return true;
50 var nextIdx = idx + 1;
51 if (args[nextIdx]) {
52 _exclude.push(nextIdx);
53 var val_1 = args[nextIdx];
54 if (val_1 === 'true' || val_1 === 'false')
55 return chek_1.toBoolean(val_1);
56 return chek_1.castType(val_1, chek_1.getType(val_1));
57 }
58 // If not next arg is boolean flag.
59 return true;
60}
61exports.parseElement = parseElement;
62// Parse the arguments
63function parse(args) {
64 args = args || _baseArgs;
65 args.forEach(function (el, idx) {
66 var flag = parseElement(el, idx, args);
67 if (!flag && _exclude.indexOf(idx) === -1)
68 _cmds.push(el);
69 else if (flag)
70 _flags[el.replace(_flagExp, '')] = flag;
71 });
72 return {
73 flags: _flags,
74 cmds: _cmds,
75 cmd: _cmds[0] // the primary command.
76 };
77}
78exports.parse = parse;
79/**
80 * Find
81 * Iterates expected or valid values stopping if matching value is found in provided args.
82 *
83 * @param valid array of expected valid values.
84 * @param args array of params to inspect.
85 */
86function find(valid, args) {
87 // If no command line args passed try to parse them.
88 args = args || parse().cmds;
89 var i = valid.length;
90 var found;
91 while (i-- && !found) {
92 if (chek_1.contains(args, valid[i]))
93 found = valid[i];
94 }
95 return found;
96}
97exports.find = find;
98//# sourceMappingURL=argv.js.map
\No newline at end of file