summaryrefslogtreecommitdiff
path: root/bin/wiki/ImportarDesdeURL/node_modules/arg/index.js
blob: 29827c58fa40171a2f4f1931b3196a8bfc069eeb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
function arg(argv, opts) {
	const result = {_: []};

	/* eslint-disable default-case */
	switch (arguments.length) {
		case 0:
			return result;
		case 1:
			opts = argv;
			argv = null;
			break;
	}
	/* eslint-enable default-case */

	argv = argv || process.argv.slice(2);

	const aliases = {};
	const handlers = {};

	for (const key of Object.keys(opts)) {
		if (typeof opts[key] === 'string') {
			aliases[key] = opts[key];
			continue;
		}

		const type = opts[key];

		if (!type || (typeof type !== 'function' && !(Array.isArray(type) && type.length === 1 && typeof type[0] === 'function'))) {
			throw new Error(`Type missing or not a function or valid array type: ${key}`);
		}

		handlers[key] = type;
	}

	for (let i = 0, len = argv.length; i < len; i++) {
		const arg = argv[i];

		if (arg.length < 2) {
			result._.push(arg);
			continue;
		}

		if (arg === '--') {
			result._ = result._.concat(argv.slice(i + 1));
			break;
		}

		if (arg[0] === '-') {
			const [originalArgName, argStr] = arg[1] === '-' ? arg.split('=', 2) : [arg, undefined];

			let argName = originalArgName;
			while (argName in aliases) {
				argName = aliases[argName];
			}

			if (!(argName in handlers)) {
				throw new Error(`Unknown or unexpected option: ${originalArgName}`);
			}

			/* eslint-disable operator-linebreak */
			const [type, isArray] = Array.isArray(handlers[argName])
				? [handlers[argName][0], true]
				: [handlers[argName], false];
			/* eslint-enable operator-linebreak */

			let value;
			if (type === Boolean) {
				value = true;
			} else if (argStr === undefined) {
				if (argv.length < i + 2 || (argv[i + 1].length > 1 && argv[i + 1][0] === '-')) {
					const extended = originalArgName === argName ? '' : ` (alias for ${argName})`;
					throw new Error(`Option requires argument: ${originalArgName}${extended}`);
				}

				value = type(argv[i + 1], argName, result[argName]);
				++i;
			} else {
				value = type(argStr, argName, result[argName]);
			}

			if (isArray) {
				if (result[argName]) {
					result[argName].push(value);
				} else {
					result[argName] = [value];
				}
			} else {
				result[argName] = value;
			}
		} else {
			result._.push(arg);
		}
	}

	return result;
}

module.exports = arg;