[484] | 1 | // grunt-exec |
---|
| 2 | // ========== |
---|
| 3 | // * GitHub: https://github.com/jharding/grunt-exec |
---|
| 4 | // * Copyright (c) 2012 Jake Harding |
---|
| 5 | // * Licensed under the MIT license. |
---|
| 6 | |
---|
| 7 | module.exports = function(grunt) { |
---|
| 8 | var cp = require('child_process') |
---|
| 9 | , f = require('util').format |
---|
| 10 | , _ = grunt.util._ |
---|
| 11 | , log = grunt.log |
---|
| 12 | , verbose = grunt.verbose; |
---|
| 13 | |
---|
| 14 | grunt.registerMultiTask('exec', 'Execute shell commands.', function() { |
---|
| 15 | var data = this.data |
---|
| 16 | , execOptions = {} |
---|
| 17 | , stdout = data.stdout !== undefined ? data.stdout : true |
---|
| 18 | , stderr = data.stderr !== undefined ? data.stderr : true |
---|
| 19 | , callback = _.isFunction(data.callback) ? data.callback : function() {} |
---|
[516] | 20 | , exitCodes = data.exitCode || data.exitCodes || 0 |
---|
[484] | 21 | , command |
---|
| 22 | , childProcess |
---|
| 23 | , args = [].slice.call(arguments, 0) |
---|
| 24 | , done = this.async(); |
---|
| 25 | |
---|
[516] | 26 | // https://github.com/jharding/grunt-exec/pull/30 |
---|
| 27 | exitCodes = _.isArray(exitCodes) ? exitCodes : [exitCodes]; |
---|
| 28 | |
---|
[484] | 29 | // allow for command to be specified in either |
---|
[516] | 30 | // 'command' or 'cmd' property, or as a string. |
---|
| 31 | command = data.command || data.cmd || (_.isString(data) && data); |
---|
[484] | 32 | |
---|
| 33 | data.cwd && (execOptions.cwd = data.cwd); |
---|
| 34 | data.maxBuffer && (execOptions.maxBuffer = data.maxBuffer); |
---|
| 35 | |
---|
| 36 | if (!command) { |
---|
| 37 | log.error('Missing command property.'); |
---|
| 38 | return done(false); |
---|
| 39 | } |
---|
| 40 | |
---|
| 41 | if (_.isFunction(command)) { |
---|
| 42 | command = command.apply(grunt, args); |
---|
| 43 | } |
---|
| 44 | |
---|
| 45 | if (!_.isString(command)) { |
---|
| 46 | log.error('Command property must be a string.'); |
---|
| 47 | return done(false); |
---|
| 48 | } |
---|
| 49 | |
---|
| 50 | verbose.subhead(command); |
---|
[516] | 51 | verbose.writeln(f('Expecting exit code %s', exitCodes.join(' or '))); |
---|
[484] | 52 | |
---|
| 53 | childProcess = cp.exec(command, execOptions, callback); |
---|
| 54 | |
---|
| 55 | stdout && childProcess.stdout.on('data', function (d) { log.write(d); }); |
---|
| 56 | stderr && childProcess.stderr.on('data', function (d) { log.error(d); }); |
---|
| 57 | |
---|
| 58 | childProcess.on('exit', function(code) { |
---|
[516] | 59 | if (exitCodes.indexOf(code) < 0) { |
---|
[484] | 60 | log.error(f('Exited with code: %d.', code)); |
---|
| 61 | return done(false); |
---|
| 62 | } |
---|
| 63 | |
---|
| 64 | verbose.ok(f('Exited with code: %d.', code)); |
---|
| 65 | done(); |
---|
| 66 | }); |
---|
| 67 | }); |
---|
| 68 | }; |
---|