forked from shelljs/shelljs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec.js
237 lines (206 loc) · 7.13 KB
/
exec.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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
var common = require('./common');
var _tempDir = require('./tempdir').tempDir;
var _pwd = require('./pwd');
var path = require('path');
var fs = require('fs');
var child = require('child_process');
var DEFAULT_MAXBUFFER_SIZE = 20 * 1024 * 1024;
var DEFAULT_ERROR_CODE = 1;
common.register('exec', _exec, {
unix: false,
canReceivePipe: true,
wrapOutput: false,
handlesFatalDynamically: true,
});
// We use this function to run `exec` synchronously while also providing realtime
// output.
function execSync(cmd, opts, pipe) {
if (!common.config.execPath) {
try {
common.error('Unable to find a path to the node binary. Please manually set config.execPath');
} catch (e) {
if (opts.fatal) {
throw e;
}
return;
}
}
var tempDir = _tempDir();
var paramsFile = path.join(tempDir, common.randomFileName());
var stderrFile = path.join(tempDir, common.randomFileName());
var stdoutFile = path.join(tempDir, common.randomFileName());
opts = common.extend({
silent: common.config.silent,
fatal: common.config.fatal, // TODO(nfischer): this and the line above are probably unnecessary
cwd: _pwd().toString(),
env: process.env,
maxBuffer: DEFAULT_MAXBUFFER_SIZE,
encoding: 'utf8',
}, opts);
if (fs.existsSync(paramsFile)) common.unlinkSync(paramsFile);
if (fs.existsSync(stderrFile)) common.unlinkSync(stderrFile);
if (fs.existsSync(stdoutFile)) common.unlinkSync(stdoutFile);
opts.cwd = path.resolve(opts.cwd);
var paramsToSerialize = {
command: cmd,
execOptions: opts,
pipe: pipe,
stdoutFile: stdoutFile,
stderrFile: stderrFile,
};
fs.writeFileSync(paramsFile, JSON.stringify(paramsToSerialize), 'utf8');
var execArgs = [
path.join(__dirname, 'exec-child.js'),
paramsFile,
];
/* istanbul ignore else */
if (opts.silent) {
opts.stdio = 'ignore';
} else {
opts.stdio = [0, 1, 2];
}
var code = 0;
// Welcome to the future
try {
// Bad things if we pass in a `shell` option to child_process.execFileSync,
// so we need to explicitly remove it here.
delete opts.shell;
child.execFileSync(common.config.execPath, execArgs, opts);
} catch (e) {
// Commands with non-zero exit code raise an exception.
code = e.status || DEFAULT_ERROR_CODE;
}
// fs.readFileSync uses buffer encoding by default, so call
// it without the encoding option if the encoding is 'buffer'.
// Also, if the exec timeout is too short for node to start up,
// the files will not be created, so these calls will throw.
var stdout = '';
var stderr = '';
if (opts.encoding === 'buffer') {
stdout = fs.readFileSync(stdoutFile);
stderr = fs.readFileSync(stderrFile);
} else {
stdout = fs.readFileSync(stdoutFile, opts.encoding);
stderr = fs.readFileSync(stderrFile, opts.encoding);
}
// No biggie if we can't erase the files now -- they're in a temp dir anyway
try { common.unlinkSync(paramsFile); } catch (e) {}
try { common.unlinkSync(stderrFile); } catch (e) {}
try { common.unlinkSync(stdoutFile); } catch (e) {}
if (code !== 0) {
// Note: `silent` should be unconditionally true to avoid double-printing
// the command's stderr, and to avoid printing any stderr when the user has
// set `shell.config.silent`.
common.error(stderr, code, { continue: true, silent: true, fatal: opts.fatal });
}
var obj = common.ShellString(stdout, stderr, code);
return obj;
} // execSync()
// Wrapper around exec() to enable echoing output to console in real time
function execAsync(cmd, opts, pipe, callback) {
opts = common.extend({
silent: common.config.silent,
fatal: common.config.fatal, // TODO(nfischer): this and the line above are probably unnecessary
cwd: _pwd().toString(),
env: process.env,
maxBuffer: DEFAULT_MAXBUFFER_SIZE,
encoding: 'utf8',
}, opts);
var c = child.exec(cmd, opts, function (err, stdout, stderr) {
if (callback) {
if (!err) {
callback(0, stdout, stderr);
} else if (err.code === undefined) {
// See issue #536
/* istanbul ignore next */
callback(1, stdout, stderr);
} else {
callback(err.code, stdout, stderr);
}
}
});
if (pipe) c.stdin.end(pipe);
if (!opts.silent) {
c.stdout.pipe(process.stdout);
c.stderr.pipe(process.stderr);
}
return c;
}
//@
//@ ### exec(command [, options] [, callback])
//@
//@ Available options:
//@
//@ + `async`: Asynchronous execution. If a callback is provided, it will be set to
//@ `true`, regardless of the passed value (default: `false`).
//@ + `fatal`: Exit upon error (default: `false`).
//@ + `silent`: Do not echo program output to console (default: `false`).
//@ + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and
//@ what is written to stdout and stderr when not in silent mode (default: `'utf8'`).
//@ + and any option available to Node.js's
//@ [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback)
//@
//@ Examples:
//@
//@ ```javascript
//@ var version = exec('node --version', {silent:true}).stdout;
//@
//@ var child = exec('some_long_running_process', {async:true});
//@ child.stdout.on('data', function(data) {
//@ /* ... do something with data ... */
//@ });
//@
//@ exec('some_long_running_process', function(code, stdout, stderr) {
//@ console.log('Exit code:', code);
//@ console.log('Program output:', stdout);
//@ console.log('Program stderr:', stderr);
//@ });
//@ ```
//@
//@ Executes the given `command` _synchronously_, unless otherwise specified.
//@ When in synchronous mode, this returns a [ShellString](#shellstringstr).
//@ Otherwise, this returns the child process object, and the `callback`
//@ receives the arguments `(code, stdout, stderr)`.
//@
//@ Not seeing the behavior you want? `exec()` runs everything through `sh`
//@ by default (or `cmd.exe` on Windows), which differs from `bash`. If you
//@ need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option.
//@
//@ **Security note:** as `shell.exec()` executes an arbitrary string in the
//@ system shell, it is **critical** to properly sanitize user input to avoid
//@ **command injection**. For more context, consult the [Security
//@ Guidelines](https://github.com/shelljs/shelljs/wiki/Security-guidelines).
function _exec(command, options, callback) {
options = options || {};
var pipe = common.readFromPipe();
// Callback is defined instead of options.
if (typeof options === 'function') {
callback = options;
options = { async: true };
}
// Callback is defined with options.
if (typeof options === 'object' && typeof callback === 'function') {
options.async = true;
}
options = common.extend({
silent: common.config.silent,
fatal: common.config.fatal,
async: false,
}, options);
if (!command) {
try {
common.error('must specify command');
} catch (e) {
if (options.fatal) {
throw e;
}
return;
}
}
if (options.async) {
return execAsync(command, options, pipe, callback);
} else {
return execSync(command, options, pipe);
}
}
module.exports = _exec;