index.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*
  2. * Jake JavaScript build tool
  3. * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
  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. let util = require('util'); // Native Node util module
  19. let spawn = require('child_process').spawn;
  20. let EventEmitter = require('events').EventEmitter;
  21. let logger = require('./logger');
  22. let file = require('./file');
  23. let Exec;
  24. const _UUID_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  25. let parseArgs = function (argumentsObj) {
  26. let args;
  27. let arg;
  28. let cmds;
  29. let callback;
  30. let 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. opts = Object.assign(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. let 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. let 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. let parsed = parseArgs(arguments);
  106. let cmds = parsed.cmds;
  107. let opts = parsed.opts;
  108. let callback = parsed.callback;
  109. let 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. // From Math.uuid.js, https://github.com/broofa/node-uuid
  122. // Robert Kieffer (robert@broofa.com), MIT license
  123. this.uuid = function (length, radix) {
  124. var chars = _UUID_CHARS
  125. , uuid = []
  126. , r
  127. , i;
  128. radix = radix || chars.length;
  129. if (length) {
  130. // Compact form
  131. i = -1;
  132. while (++i < length) {
  133. uuid[i] = chars[0 | Math.random()*radix];
  134. }
  135. } else {
  136. // rfc4122, version 4 form
  137. // rfc4122 requires these characters
  138. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
  139. uuid[14] = '4';
  140. // Fill in random data. At i==19 set the high bits of clock sequence as
  141. // per rfc4122, sec. 4.1.5
  142. i = -1;
  143. while (++i < 36) {
  144. if (!uuid[i]) {
  145. r = 0 | Math.random()*16;
  146. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  147. }
  148. }
  149. }
  150. return uuid.join('');
  151. };
  152. })();
  153. Exec = function () {
  154. let parsed = parseArgs(arguments);
  155. let cmds = parsed.cmds;
  156. let opts = parsed.opts;
  157. let callback = parsed.callback;
  158. this._cmds = cmds;
  159. this._callback = callback;
  160. this._config = opts;
  161. };
  162. util.inherits(Exec, EventEmitter);
  163. Object.assign(Exec.prototype, new (function () {
  164. let _run = function () {
  165. let self = this;
  166. let sh;
  167. let cmd;
  168. let args;
  169. let next = this._cmds.shift();
  170. let config = this._config;
  171. let errData = '';
  172. let shStdio;
  173. let handleStdoutData = function (data) {
  174. self.emit('stdout', data);
  175. };
  176. let handleStderrData = function (data) {
  177. let d = data.toString();
  178. self.emit('stderr', data);
  179. // Accumulate the error-data so we can use it as the
  180. // stack if the process exits with an error
  181. errData += d;
  182. };
  183. // Keep running as long as there are commands in the array
  184. if (next) {
  185. let spawnOpts = {};
  186. this.emit('cmdStart', next);
  187. // Ganking part of Node's child_process.exec to get cmdline args parsed
  188. if (process.platform == 'win32') {
  189. cmd = 'cmd';
  190. args = ['/c', next];
  191. if (config.windowsVerbatimArguments) {
  192. spawnOpts.windowsVerbatimArguments = true;
  193. }
  194. }
  195. else {
  196. cmd = '/bin/sh';
  197. args = ['-c', next];
  198. }
  199. if (config.interactive) {
  200. spawnOpts.stdio = 'inherit';
  201. sh = spawn(cmd, args, spawnOpts);
  202. }
  203. else {
  204. shStdio = [
  205. process.stdin
  206. ];
  207. if (config.printStdout) {
  208. shStdio.push(process.stdout);
  209. }
  210. else {
  211. shStdio.push('pipe');
  212. }
  213. if (config.printStderr) {
  214. shStdio.push(process.stderr);
  215. }
  216. else {
  217. shStdio.push('pipe');
  218. }
  219. spawnOpts.stdio = shStdio;
  220. sh = spawn(cmd, args, spawnOpts);
  221. if (!config.printStdout) {
  222. sh.stdout.addListener('data', handleStdoutData);
  223. }
  224. if (!config.printStderr) {
  225. sh.stderr.addListener('data', handleStderrData);
  226. }
  227. }
  228. // Exit, handle err or run next
  229. sh.on('exit', function (code) {
  230. let msg;
  231. if (code !== 0) {
  232. msg = errData || 'Process exited with error.';
  233. msg = msg.trim();
  234. self.emit('error', msg, code);
  235. }
  236. if (code === 0 || !config.breakOnError) {
  237. self.emit('cmdEnd', next);
  238. setTimeout(function () { _run.call(self); }, 0);
  239. }
  240. });
  241. }
  242. else {
  243. self.emit('end');
  244. if (typeof self._callback == 'function') {
  245. self._callback();
  246. }
  247. }
  248. };
  249. this.append = function (cmd) {
  250. this._cmds.push(cmd);
  251. };
  252. this.run = function () {
  253. _run.call(this);
  254. };
  255. })());
  256. utils.Exec = Exec;
  257. utils.file = file;
  258. utils.logger = logger;
  259. module.exports = utils;