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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
var is = require('is');
var childProcess = require('child_process');
var spawn = require('spawn-cmd').spawn;
var Promise = require('./promise');
/**
Execute a command
@param {String} command
@param {Object} options
@return {Promise}
*/
function exec(command, options) {
var d = Promise.defer();
var child = childProcess.exec(command, options, function(err, stdout, stderr) {
if (!err) {
return d.resolve();
}
err.message = stdout.toString('utf8') + stderr.toString('utf8');
d.reject(err);
});
child.stdout.on('data', function (data) {
d.notify(data);
});
child.stderr.on('data', function (data) {
d.notify(data);
});
return d.promise;
}
/**
Spawn an executable
@param {String} command
@param {Array} args
@param {Object} options
@return {Promise}
*/
function spawnCmd(command, args, options) {
var d = Promise.defer();
var child = spawn(command, args, options);
child.on('error', function(error) {
return d.reject(error);
});
child.stdout.on('data', function (data) {
d.notify(data);
});
child.stderr.on('data', function (data) {
d.notify(data);
});
child.on('close', function(code) {
if (code === 0) {
d.resolve();
} else {
d.reject(new Error('Error with command "'+command+'"'));
}
});
return d.promise;
}
/**
Transform an option object to a command line string
@param {String|number} value
@param {String}
*/
function escapeShellArg(value) {
if (is.number(value)) {
return value;
}
value = String(value);
value = value.replace(/"/g, '\\"');
return '"' + value + '"';
}
/**
Transform a map of options into a command line arguments string
@param {Object} options
@return {String}
*/
function optionsToShellArgs(options) {
var result = [];
for (var key in options) {
var value = options[key];
if (value === null || value === undefined || value === false) {
continue;
}
if (is.bool(value)) {
result.push(key);
} else {
result.push(key + '=' + escapeShellArg(value));
}
}
return result.join(' ');
}
module.exports = {
exec: exec,
spawn: spawnCmd,
optionsToShellArgs: optionsToShellArgs
};
|