Version 1
[yaffs-website] / node_modules / grunt-legacy-util / index.js
1 /*
2  * grunt
3  * http://gruntjs.com/
4  *
5  * Copyright (c) 2016 "Cowboy" Ben Alman
6  * Licensed under the MIT license.
7  * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
8  */
9
10 'use strict';
11
12 // Nodejs libs.
13 var spawn = require('child_process').spawn;
14 var nodeUtil = require('util');
15 var path = require('path');
16
17 // The module to be exported.
18 var util = module.exports = {};
19
20 util.namespace = require('getobject');
21
22 // External libs.
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');
29
30 // Mixin Underscore.string methods.
31 _.str = require('underscore.string');
32 _.mixin(_.str.exports());
33
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); }
48   };
49 };
50
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; }
56   return err;
57 };
58
59 // The line feed char for the current system.
60 util.linefeed = process.platform === 'win32' ? '\r\n' : '\n';
61
62 // Normalize linefeeds in a string.
63 util.normalizelf = function(str) {
64   return str.replace(/\r\n|\n/g, util.linefeed);
65 };
66
67 // What "kind" is a value?
68 // I really need to rework https://github.com/cowboy/javascript-getclass
69 var kindsOf = {};
70 'Number String Boolean Function RegExp Array Date Error'.split(' ').forEach(function(k) {
71   kindsOf['[object ' + k + ']'] = k.toLowerCase();
72 });
73 util.kindOf = function(value) {
74   // Null or undefined.
75   if (value == null) { return String(value); }
76   // Everything else.
77   return kindsOf[kindsOf.toString.call(value)] || 'object';
78 };
79
80 // Coerce something to an Array.
81 util.toArray = _.toArray;
82
83 // Return the string `str` repeated `n` times.
84 util.repeat = function(n, str) {
85   return new Array(n + 1).join(str || ' ');
86 };
87
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] || '');
92 };
93
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) {
97     var error;
98     if (state.objs.indexOf(value) !== -1) {
99       error = new Error('Circular reference detected (' + state.path + ')');
100       error.path = state.path;
101       throw error;
102     }
103     var obj, key;
104     if (fnContinue && fnContinue(value) === false) {
105       // Skip value if necessary.
106       return value;
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 + ']',
113         });
114       });
115     } else if (util.kindOf(value) === 'object' && !Buffer.isBuffer(value)) {
116       // If value is an object, recurse.
117       obj = {};
118       for (key in value) {
119         obj[key] = recurse(value[key], fn, fnContinue, {
120           objs: state.objs.concat([value]),
121           path: state.path + (/\W/.test(key) ? '["' + key + '"]' : '.' + key),
122         });
123       }
124       return obj;
125     } else {
126       // Otherwise pass value into fn and return.
127       return fn(value);
128     }
129   }
130   return recurse(value, fn, fnContinue, {objs: [], path: ''});
131 };
132
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
136   // done function.
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.
142     var result = {
143       stdout: stdout,
144       stderr: stderr,
145       code: code,
146       toString: function() {
147         if (code === 0) {
148           return stdout;
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;
154         }
155         return stderr;
156       }
157     };
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);
160   };
161
162   var cmd, args;
163   var pathSeparatorRe = /[\\\/]/g;
164   if (opts.grunt) {
165     cmd = process.execPath;
166     args = process.execArgv.concat(process.argv[1], opts.args);
167   } else {
168     // On Windows, child_process.spawn will only file .exe files in the PATH,
169     // not other executable types (grunt issue #155).
170     try {
171       if (!pathSeparatorRe.test(opts.cmd)) {
172         // Only use which if cmd has no path component.
173         cmd = which(opts.cmd);
174       } else {
175         cmd = opts.cmd.replace(pathSeparatorRe, path.sep);
176       }
177     } catch (err) {
178       callDone(127, '', String(err));
179       return;
180     }
181     args = opts.args || [];
182   }
183
184   var child = spawn(cmd, args, opts.opts);
185   var stdout = new Buffer('');
186   var stderr = new Buffer('');
187   if (child.stdout) {
188     child.stdout.on('data', function(buf) {
189       stdout = Buffer.concat([stdout, new Buffer(buf)]);
190     });
191   }
192   if (child.stderr) {
193     child.stderr.on('data', function(buf) {
194       stderr = Buffer.concat([stderr, new Buffer(buf)]);
195     });
196   }
197   child.on('close', function(code) {
198     callDone(code, stdout.toString(), stderr.toString());
199   });
200   return child;
201 };