-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapply-defaults.js
87 lines (78 loc) · 2.23 KB
/
apply-defaults.js
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
"use strict";
module.exports = applyDefaults;
/**
* Applies default values (if any) to the arguments
*/
function applyDefaults (defaults, originalArgs) {
defaults = defaults || {};
let command = defaults.command;
let args = Array.prototype.slice.call(originalArgs);
let options;
let lastArg = args[args.length - 1];
if (lastArg === null || lastArg === undefined ||
(typeof lastArg === "object" && !Array.isArray(lastArg))) {
// The last argument is the options object
options = args.pop();
}
if (args.length === 1) {
if (command) {
// The args were passed as a single string or an array of strings
args = args[0];
}
else if (typeof args[0] === "string") {
// The command and args were passed as a single string
command = args.shift();
}
else if (Array.isArray(args[0])) {
// The command and args were passed as an array
command = args[0][0];
args = args[0].slice(1);
}
}
else if (!command) {
// The first argument is the command
command = args.shift();
}
if (typeof defaults.args === "string") {
if (typeof args === "string") {
// Concatenate the two strings
args = defaults.args + " " + args;
}
else if (args.length === 0) {
args = defaults.args;
}
else {
// Insert the default arg at the beginning of the array
args.unshift(defaults.args);
}
}
else if (Array.isArray(defaults.args)) {
// Append the arg(s) to the default args
args = defaults.args.concat(args);
}
if (defaults.options) {
if (options) {
// Merge the default options with the options arg
options = Object.assign({}, defaults.options, options);
}
else {
// Clone the default options
options = Object.assign({}, defaults.options);
}
}
// By default, use the current process's environment variables.
// except for NODE environment variables, which could impact how the child process runs.
options = options || {};
if (!options.env) {
options.env = Object.assign({}, process.env, {
NODE_ENV: "",
NODE_OPTIONS: "",
});
}
if (typeof args === "string") {
return [command + " " + args, options];
}
else {
return [command].concat(args, options);
}
}