5 * Copyright (c) 2016 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
7 * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
13 var spawn = require('child_process').spawn;
14 var nodeUtil = require('util');
15 var path = require('path');
17 // The module to be exported.
18 var util = module.exports = {};
20 util.namespace = require('getobject');
23 util.hooker = require('hooker');
24 util.async = require('async');
25 var _ = util._ = require('lodash');
26 var which = require('which').sync;
27 // Instead of process.exit. See https://github.com/cowboy/node-exit
28 util.exit = require('exit');
30 // Mixin Underscore.string methods.
31 _.str = require('underscore.string');
32 _.mixin(_.str.exports());
34 // Return a function that normalizes the given function either returning a
35 // value or accepting a "done" callback that accepts a single value.
36 util.callbackify = function(fn) {
37 return function callbackable() {
38 // Invoke original function, getting its result.
39 var result = fn.apply(this, arguments);
40 // If the same number or less arguments were specified than fn accepts,
41 // assume the "done" callback was already handled.
42 var length = arguments.length;
43 if (length === fn.length) { return; }
44 // Otherwise, if the last argument is a function, assume it is a "done"
45 // callback and call it.
46 var done = arguments[length - 1];
47 if (typeof done === 'function') { done(result); }
51 // Create a new Error object, with an origError property that will be dumped
52 // if grunt was run with the --debug=9 option.
53 util.error = function(err, origError) {
54 if (!nodeUtil.isError(err)) { err = new Error(err); }
55 if (origError) { err.origError = origError; }
59 // The line feed char for the current system.
60 util.linefeed = process.platform === 'win32' ? '\r\n' : '\n';
62 // Normalize linefeeds in a string.
63 util.normalizelf = function(str) {
64 return str.replace(/\r\n|\n/g, util.linefeed);
67 // What "kind" is a value?
68 // I really need to rework https://github.com/cowboy/javascript-getclass
70 'Number String Boolean Function RegExp Array Date Error'.split(' ').forEach(function(k) {
71 kindsOf['[object ' + k + ']'] = k.toLowerCase();
73 util.kindOf = function(value) {
75 if (value == null) { return String(value); }
77 return kindsOf[kindsOf.toString.call(value)] || 'object';
80 // Coerce something to an Array.
81 util.toArray = _.toArray;
83 // Return the string `str` repeated `n` times.
84 util.repeat = function(n, str) {
85 return new Array(n + 1).join(str || ' ');
88 // Given str of "a/b", If n is 1, return "a" otherwise "b".
89 util.pluralize = function(n, str, separator) {
90 var parts = str.split(separator || '/');
91 return n === 1 ? (parts[0] || '') : (parts[1] || '');
94 // Recurse through objects and arrays, executing fn for each non-object.
95 util.recurse = function(value, fn, fnContinue) {
96 function recurse(value, fn, fnContinue, state) {
98 if (state.objs.indexOf(value) !== -1) {
99 error = new Error('Circular reference detected (' + state.path + ')');
100 error.path = state.path;
104 if (fnContinue && fnContinue(value) === false) {
105 // Skip value if necessary.
107 } else if (util.kindOf(value) === 'array') {
108 // If value is an array, recurse.
109 return value.map(function(item, index) {
110 return recurse(item, fn, fnContinue, {
111 objs: state.objs.concat([value]),
112 path: state.path + '[' + index + ']',
115 } else if (util.kindOf(value) === 'object' && !Buffer.isBuffer(value)) {
116 // If value is an object, recurse.
119 obj[key] = recurse(value[key], fn, fnContinue, {
120 objs: state.objs.concat([value]),
121 path: state.path + (/\W/.test(key) ? '["' + key + '"]' : '.' + key),
126 // Otherwise pass value into fn and return.
130 return recurse(value, fn, fnContinue, {objs: [], path: ''});
133 // Spawn a child process, capturing its stdout and stderr.
134 util.spawn = function(opts, done) {
135 // Build a result object and pass it (among other things) into the
137 var callDone = function(code, stdout, stderr) {
138 // Remove trailing whitespace (newline)
139 stdout = _.rtrim(stdout);
140 stderr = _.rtrim(stderr);
141 // Create the result object.
146 toString: function() {
149 } else if ('fallback' in opts) {
150 return opts.fallback;
151 } else if (opts.grunt) {
152 // grunt.log.error uses standard out, to be fixed in 0.5.
153 return stderr || stdout;
158 // On error (and no fallback) pass an error object, otherwise pass null.
159 done(code === 0 || 'fallback' in opts ? null : new Error(stderr), result, code);
163 var pathSeparatorRe = /[\\\/]/g;
165 cmd = process.execPath;
166 args = process.execArgv.concat(process.argv[1], opts.args);
168 // On Windows, child_process.spawn will only file .exe files in the PATH,
169 // not other executable types (grunt issue #155).
171 if (!pathSeparatorRe.test(opts.cmd)) {
172 // Only use which if cmd has no path component.
173 cmd = which(opts.cmd);
175 cmd = opts.cmd.replace(pathSeparatorRe, path.sep);
178 callDone(127, '', String(err));
181 args = opts.args || [];
184 var child = spawn(cmd, args, opts.opts);
185 var stdout = new Buffer('');
186 var stderr = new Buffer('');
188 child.stdout.on('data', function(buf) {
189 stdout = Buffer.concat([stdout, new Buffer(buf)]);
193 child.stderr.on('data', function(buf) {
194 stderr = Buffer.concat([stderr, new Buffer(buf)]);
197 child.on('close', function(code) {
198 callDone(code, stdout.toString(), stderr.toString());