index.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /*
  2. * Jake JavaScript build tool
  3. * Copyright 2112 Matthew Eernisse ([email protected])
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. var util = require('util') // Native Node util module
  19. , exec = require('child_process').exec
  20. , spawn = require('child_process').spawn
  21. , EventEmitter = require('events').EventEmitter
  22. , utils = require('utilities')
  23. , logger = require('./logger')
  24. , Exec;
  25. var parseArgs = function (argumentsObj) {
  26. var args
  27. , arg
  28. , cmds
  29. , callback
  30. , opts = {
  31. interactive: false
  32. , printStdout: false
  33. , printStderr: false
  34. , breakOnError: true
  35. };
  36. args = Array.prototype.slice.call(argumentsObj);
  37. cmds = args.shift();
  38. // Arrayize if passed a single string command
  39. if (typeof cmds == 'string') {
  40. cmds = [cmds];
  41. }
  42. // Make a copy if it's an actual list
  43. else {
  44. cmds = cmds.slice();
  45. }
  46. // Get optional callback or opts
  47. while((arg = args.shift())) {
  48. if (typeof arg == 'function') {
  49. callback = arg;
  50. }
  51. else if (typeof arg == 'object') {
  52. utils.mixin(opts, arg);
  53. }
  54. }
  55. // Backward-compat shim
  56. if (typeof opts.stdout != 'undefined') {
  57. opts.printStdout = opts.stdout;
  58. delete opts.stdout;
  59. }
  60. if (typeof opts.stderr != 'undefined') {
  61. opts.printStderr = opts.stderr;
  62. delete opts.stderr;
  63. }
  64. return {
  65. cmds: cmds
  66. , opts: opts
  67. , callback: callback
  68. };
  69. };
  70. /**
  71. @name jake
  72. @namespace jake
  73. */
  74. utils.mixin(utils, new (function () {
  75. /**
  76. @name jake.exec
  77. @static
  78. @function
  79. @description Executes shell-commands asynchronously with an optional
  80. final callback.
  81. `
  82. @param {String[]} cmds The list of shell-commands to execute
  83. @param {Object} [opts]
  84. @param {Boolean} [opts.printStdout=false] Print stdout from each command
  85. @param {Boolean} [opts.printStderr=false] Print stderr from each command
  86. @param {Boolean} [opts.breakOnError=true] Stop further execution on
  87. the first error.
  88. @param {Boolean} [opts.windowsVerbatimArguments=false] Don't translate
  89. arguments on Windows.
  90. @param {Function} [callback] Callback to run after executing the
  91. commands
  92. @example
  93. var cmds = [
  94. 'echo "showing directories"'
  95. , 'ls -al | grep ^d'
  96. , 'echo "moving up a directory"'
  97. , 'cd ../'
  98. ]
  99. , callback = function () {
  100. console.log('Finished running commands.');
  101. }
  102. jake.exec(cmds, {stdout: true}, callback);
  103. */
  104. this.exec = function (a, b, c) {
  105. var parsed = parseArgs(arguments)
  106. , cmds = parsed.cmds
  107. , opts = parsed.opts
  108. , callback = parsed.callback;
  109. var ex = new Exec(cmds, opts, callback);
  110. ex.addListener('error', function (msg, code) {
  111. if (opts.breakOnError) {
  112. fail(msg, code);
  113. }
  114. });
  115. ex.run();
  116. return ex;
  117. };
  118. this.createExec = function (a, b, c) {
  119. return new Exec(a, b, c);
  120. };
  121. })());
  122. Exec = function () {
  123. var parsed = parseArgs(arguments)
  124. , cmds = parsed.cmds
  125. , opts = parsed.opts
  126. , callback = parsed.callback;
  127. this._cmds = cmds;
  128. this._callback = callback;
  129. this._config = opts;
  130. };
  131. util.inherits(Exec, EventEmitter);
  132. utils.mixin(Exec.prototype, new (function () {
  133. var _run = function () {
  134. var self = this
  135. , sh
  136. , cmd
  137. , args
  138. , next = this._cmds.shift()
  139. , config = this._config
  140. , errData = ''
  141. , shStdio
  142. , handleStdoutData = function (data) {
  143. self.emit('stdout', data);
  144. }
  145. , handleStderrData = function (data) {
  146. var d = data.toString();
  147. self.emit('stderr', data);
  148. // Accumulate the error-data so we can use it as the
  149. // stack if the process exits with an error
  150. errData += d;
  151. };
  152. // Keep running as long as there are commands in the array
  153. if (next) {
  154. var spawnOpts = {};
  155. this.emit('cmdStart', next);
  156. // Ganking part of Node's child_process.exec to get cmdline args parsed
  157. if (process.platform == 'win32') {
  158. cmd = 'cmd';
  159. args = ['/c', next];
  160. if (config.windowsVerbatimArguments) {
  161. spawnOpts.windowsVerbatimArguments = true;
  162. }
  163. }
  164. else {
  165. cmd = '/bin/sh';
  166. args = ['-c', next];
  167. }
  168. if (config.interactive) {
  169. spawnOpts.stdio = 'inherit';
  170. sh = spawn(cmd, args, spawnOpts);
  171. }
  172. else {
  173. shStdio = [
  174. process.stdin
  175. ];
  176. if (config.printStdout) {
  177. shStdio.push(process.stdout);
  178. }
  179. else {
  180. shStdio.push('pipe');
  181. }
  182. if (config.printStderr) {
  183. shStdio.push(process.stderr);
  184. }
  185. else {
  186. shStdio.push('pipe');
  187. }
  188. spawnOpts.stdio = shStdio;
  189. sh = spawn(cmd, args, spawnOpts);
  190. if (!config.printStdout) {
  191. sh.stdout.addListener('data', handleStdoutData);
  192. }
  193. if (!config.printStderr) {
  194. sh.stderr.addListener('data', handleStderrData);
  195. }
  196. }
  197. // Exit, handle err or run next
  198. sh.on('exit', function (code) {
  199. var msg;
  200. if (code !== 0) {
  201. msg = errData || 'Process exited with error.';
  202. msg = utils.string.trim(msg);
  203. self.emit('error', msg, code);
  204. }
  205. if (code === 0 || !config.breakOnError) {
  206. self.emit('cmdEnd', next);
  207. setTimeout(function () { _run.call(self); }, 0);
  208. }
  209. });
  210. }
  211. else {
  212. self.emit('end');
  213. if (typeof self._callback == 'function') {
  214. self._callback();
  215. }
  216. }
  217. };
  218. this.append = function (cmd) {
  219. this._cmds.push(cmd);
  220. };
  221. this.run = function () {
  222. _run.call(this);
  223. };
  224. })());
  225. utils.Exec = Exec;
  226. utils.logger = logger;
  227. module.exports = utils;