exec.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. module.exports = function(grunt) {
  7. var cp = require('child_process')
  8. , f = require('util').format
  9. , util = grunt.util
  10. , log = grunt.log
  11. , verbose = grunt.verbose;
  12. grunt.registerMultiTask('exec', 'Execute shell commands.', function() {
  13. var data = this.data
  14. , o = {
  15. stdout: data.stdout !== undefined ? data.stdout : true
  16. , stderr: data.stderr !== undefined ? data.stderr : true
  17. }
  18. , command
  19. , childProcess
  20. , args = [].slice.call(arguments, 0)
  21. , done = this.async();
  22. // allow for command to be specified in either
  23. // 'command' or 'cmd' property
  24. command = data.command || data.cmd;
  25. if (!command) {
  26. log.error('Missing command property.');
  27. return done(false);
  28. }
  29. if (util._.isFunction(command)) {
  30. command = command.apply(grunt, args);
  31. }
  32. if (!util._.isString(command)) {
  33. log.error('Command property must be a string.');
  34. return done(false);
  35. }
  36. verbose.subhead(command);
  37. childProcess = cp.exec(command);
  38. o.stdout && childProcess.stdout.on('data', function (d) { log.write(d); });
  39. o.stderr && childProcess.stderr.on('data', function (d) { log.error(d); });
  40. childProcess.on('exit', function(code) {
  41. if (code > 0) {
  42. log.error(f('Exited with code: %d.', code));
  43. return done(false);
  44. }
  45. verbose.ok(f('Exited with code: %d.', code));
  46. done();
  47. });
  48. });
  49. };