UNPKG

1.54 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 });
14 var cmd = this.data.command;
15
16 if (cmd === undefined) {
17 throw new Error('`command` required');
18 }
19
20 cmd = grunt.template.process(typeof cmd === 'function' ? cmd.apply(grunt, arguments) : cmd);
21
22 var cp = exec(cmd, options.execOptions, function (err, stdout, stderr) {
23 if (typeof options.callback === 'function') {
24 options.callback.call(this, err, stdout, stderr, cb);
25 } else {
26 if (err && options.failOnError) {
27 grunt.warn(err);
28 }
29 cb();
30 }
31 }.bind(this));
32
33 var captureOutput = function (child, output) {
34 if (grunt.option('color') === false) {
35 child.on('data', function (data) {
36 output.write(chalk.stripColor(data));
37 });
38 } else {
39 child.pipe(output);
40 }
41 };
42
43 grunt.verbose.writeln('Command:', chalk.yellow(cmd));
44
45 if (options.stdout || grunt.option('verbose')) {
46 captureOutput(cp.stdout, process.stdout);
47 }
48
49 if (options.stderr || grunt.option('verbose')) {
50 captureOutput(cp.stderr, process.stderr);
51 }
52
53 if (options.stdin) {
54 process.stdin.resume();
55 process.stdin.setEncoding('utf8');
56 if (typeof process.stdin.setRawMode === 'function') {
57 process.stdin.setRawMode(true);
58 }
59 process.stdin.pipe(cp.stdin);
60 }
61 });
62};