UNPKG

1.56 kBJavaScriptView Raw
1'use strict';
2var exec = require('child_process').exec;
3var chalk = require('chalk');
4
5module.exports = function (grunt) {
6 grunt.registerMultiTask('shell', 'Run shell commands', function () {
7 var cb = this.async();
8 var options = this.options({
9 stdout: true,
10 stderr: true,
11 stdin: true,
12 failOnError: true,
13 stdinRawMode: false
14 });
15 var cmd = this.data.command;
16
17 if (cmd === undefined) {
18 throw new Error('`command` required');
19 }
20
21 cmd = grunt.template.process(typeof cmd === 'function' ? cmd.apply(grunt, arguments) : cmd);
22
23 var cp = exec(cmd, options.execOptions, function (err, stdout, stderr) {
24 if (typeof options.callback === 'function') {
25 options.callback.call(this, err, stdout, stderr, cb);
26 } else {
27 if (err && options.failOnError) {
28 grunt.warn(err);
29 }
30 cb();
31 }
32 }.bind(this));
33
34 var captureOutput = function (child, output) {
35 if (grunt.option('color') === false) {
36 child.on('data', function (data) {
37 output.write(chalk.stripColor(data));
38 });
39 } else {
40 child.pipe(output);
41 }
42 };
43
44 grunt.verbose.writeln('Command:', chalk.yellow(cmd));
45
46 if (options.stdout || grunt.option('verbose')) {
47 captureOutput(cp.stdout, process.stdout);
48 }
49
50 if (options.stderr || grunt.option('verbose')) {
51 captureOutput(cp.stderr, process.stderr);
52 }
53
54 if (options.stdin) {
55 process.stdin.resume();
56 process.stdin.setEncoding('utf8');
57
58 if (options.stdinRawMode && process.stdin.isTTY) {
59 process.stdin.setRawMode(true);
60 }
61
62 process.stdin.pipe(cp.stdin);
63 }
64 });
65};