blob: a833e75b2d377b49f58aaa96e0a86cd1435d492e [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001/*
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.
13var spawn = require('child_process').spawn;
14var nodeUtil = require('util');
15var path = require('path');
16
17// The module to be exported.
18var util = module.exports = {};
19
20util.namespace = require('getobject');
21
22// External libs.
23util.hooker = require('hooker');
24util.async = require('async');
25// Dont pollute other lodash: https://github.com/gruntjs/grunt-legacy-util/issues/17
26var _ = util._ = require('lodash').runInContext();
27var which = require('which').sync;
28// Instead of process.exit. See https://github.com/cowboy/node-exit
29util.exit = require('exit');
30
31// Mixin Underscore.string methods.
32_.str = require('underscore.string');
33_.mixin(_.str.exports());
34
35// Return a function that normalizes the given function either returning a
36// value or accepting a "done" callback that accepts a single value.
37util.callbackify = function(fn) {
38 return function callbackable() {
39 // Invoke original function, getting its result.
40 var result = fn.apply(this, arguments);
41 // If the same number or less arguments were specified than fn accepts,
42 // assume the "done" callback was already handled.
43 var length = arguments.length;
44 if (length === fn.length) { return; }
45 // Otherwise, if the last argument is a function, assume it is a "done"
46 // callback and call it.
47 var done = arguments[length - 1];
48 if (typeof done === 'function') { done(result); }
49 };
50};
51
52// Create a new Error object, with an origError property that will be dumped
53// if grunt was run with the --debug=9 option.
54util.error = function(err, origError) {
55 if (!nodeUtil.isError(err)) { err = new Error(err); }
56 if (origError) { err.origError = origError; }
57 return err;
58};
59
60// The line feed char for the current system.
61util.linefeed = process.platform === 'win32' ? '\r\n' : '\n';
62
63// Normalize linefeeds in a string.
64util.normalizelf = function(str) {
65 return str.replace(/\r\n|\n/g, util.linefeed);
66};
67
68// What "kind" is a value?
69// I really need to rework https://github.com/cowboy/javascript-getclass
70var kindsOf = {};
71'Number String Boolean Function AsyncFunction RegExp Array Date Error'.split(' ').forEach(function(k) {
72 kindsOf['[object ' + k + ']'] = k.toLowerCase();
73});
74util.kindOf = function(value) {
75 // Null or undefined.
76 if (value == null) { return String(value); }
77 // Everything else.
78 return kindsOf[kindsOf.toString.call(value)] || 'object';
79};
80
81// Coerce something to an Array.
82util.toArray = _.toArray;
83
84// Return the string `str` repeated `n` times.
85util.repeat = function(n, str) {
86 return new Array(n + 1).join(str || ' ');
87};
88
89// Given str of "a/b", If n is 1, return "a" otherwise "b".
90util.pluralize = function(n, str, separator) {
91 var parts = str.split(separator || '/');
92 return n === 1 ? (parts[0] || '') : (parts[1] || '');
93};
94
95// Recurse through objects and arrays, executing fn for each non-object.
96util.recurse = function(value, fn, fnContinue) {
97 function recurse(value, fn, fnContinue, state) {
98 var error;
99 if (state.objs.indexOf(value) !== -1) {
100 error = new Error('Circular reference detected (' + state.path + ')');
101 error.path = state.path;
102 throw error;
103 }
104 var obj, key;
105 if (fnContinue && fnContinue(value) === false) {
106 // Skip value if necessary.
107 return value;
108 } else if (util.kindOf(value) === 'array') {
109 // If value is an array, recurse.
110 return value.map(function(item, index) {
111 return recurse(item, fn, fnContinue, {
112 objs: state.objs.concat([value]),
113 path: state.path + '[' + index + ']',
114 });
115 });
116 } else if (util.kindOf(value) === 'object' && !Buffer.isBuffer(value)) {
117 // If value is an object, recurse.
118 obj = {};
119 for (key in value) {
120 obj[key] = recurse(value[key], fn, fnContinue, {
121 objs: state.objs.concat([value]),
122 path: state.path + (/\W/.test(key) ? '["' + key + '"]' : '.' + key),
123 });
124 }
125 return obj;
126 } else {
127 // Otherwise pass value into fn and return.
128 return fn(value);
129 }
130 }
131 return recurse(value, fn, fnContinue, {objs: [], path: ''});
132};
133
134// Spawn a child process, capturing its stdout and stderr.
135util.spawn = function(opts, done) {
136 // Build a result object and pass it (among other things) into the
137 // done function.
138 var callDone = function(code, stdout, stderr) {
139 // Remove trailing whitespace (newline)
140 stdout = _.rtrim(stdout);
141 stderr = _.rtrim(stderr);
142 // Create the result object.
143 var result = {
144 stdout: stdout,
145 stderr: stderr,
146 code: code,
147 toString: function() {
148 if (code === 0) {
149 return stdout;
150 } else if ('fallback' in opts) {
151 return opts.fallback;
152 } else if (opts.grunt) {
153 // grunt.log.error uses standard out, to be fixed in 0.5.
154 return stderr || stdout;
155 }
156 return stderr;
157 }
158 };
159 // On error (and no fallback) pass an error object, otherwise pass null.
160 done(code === 0 || 'fallback' in opts ? null : new Error(stderr), result, code);
161 };
162
163 var cmd, args;
164 var pathSeparatorRe = /[\\\/]/g;
165 if (opts.grunt) {
166 cmd = process.execPath;
167 args = process.execArgv.concat(process.argv[1], opts.args);
168 } else {
169 // On Windows, child_process.spawn will only file .exe files in the PATH,
170 // not other executable types (grunt issue #155).
171 try {
172 if (!pathSeparatorRe.test(opts.cmd)) {
173 // Only use which if cmd has no path component.
174 cmd = which(opts.cmd);
175 } else {
176 cmd = opts.cmd.replace(pathSeparatorRe, path.sep);
177 }
178 } catch (err) {
179 callDone(127, '', String(err));
180 return;
181 }
182 args = opts.args || [];
183 }
184
185 var child = spawn(cmd, args, opts.opts);
186 var stdout = Buffer.from('');
187 var stderr = Buffer.from('');
188 if (child.stdout) {
189 child.stdout.on('data', function(buf) {
190 stdout = Buffer.concat([stdout, Buffer.from(buf)]);
191 });
192 }
193 if (child.stderr) {
194 child.stderr.on('data', function(buf) {
195 stderr = Buffer.concat([stderr, Buffer.from(buf)]);
196 });
197 }
198 child.on('close', function(code) {
199 callDone(code, stdout.toString(), stderr.toString());
200 });
201 return child;
202};