function File(file) {
if (!file) file = {};
// record path change
var history = file.path ? [file.path] : file.history;
this.history = history || [];
this.cwd = file.cwd || process.cwd();
this.base = file.base || this.cwd;
// stat = files stats object
this.stat = file.stat || null;
// contents = stream, buffer, or null if not read
this.contents = file.contents || null;
this._isVinyl = true;
}...
This is a lodash.template function wrapper. You must pass in a valid gulp file object so it is available to the user or it will
error. You can not configure any of the delimiters. Look at the [lodash docs](http://lodash.com/docs#template) for more info.
## new File(obj)
This is just [vinyl](https://github.com/wearefractal/vinyl)
```javascript
var file = new gutil.File({
base: path.join(__dirname, './fixtures/'),
cwd: __dirname,
path: path.join(__dirname, './fixtures/test.coffee')
});
```
## noop()
...function PluginError(plugin, message, opt) {
if (!(this instanceof PluginError)) throw new Error('Call PluginError using new');
Error.call(this);
var options = parseOptions(plugin, message, opt);
var self = this;
// if options has an error, grab details from it
if (options.error) {
// These properties are not enumerable, so we have to add them explicitly.
arrayUniq(Object.keys(options.error).concat(nonEnumberableProperties))
.forEach(function(prop) {
self[prop] = options.error[prop];
});
}
var properties = ['name', 'message', 'fileName', 'lineNumber', 'stack', 'showStack', 'showProperties', 'plugin'];
// options object can override
properties.forEach(function(prop) {
if (prop in options) this[prop] = options[prop];
}, this);
// defaults
if (!this.name) this.name = 'Error';
if (!this.stack) {
// Error.captureStackTrace appends a stack property which relies on the toString method of the object it is applied to.
// Since we are using our own toString method which controls when to display the stack trace if we don't go through this
// safety object, then we'll get stack overflow problems.
var safety = {
toString: function() {
return this._messageWithDetails() + '\nStack:';
}.bind(this)
};
Error.captureStackTrace(safety, arguments.callee || this.constructor);
this.__safety = safety;
}
if (!this.plugin) throw new Error('Missing plugin name');
if (!this.message) throw new Error('Missing error message');
}...
- If you pass an error in as the message the stack will be pulled from that, otherwise one will be created.
- Note that if you pass in a custom stack string you need to include the message along with that.
- Error properties will be included in `err.toString()`. Can be omitted by including `{showProperties: false}` in the options.
These are all acceptable forms of instantiation:
```javascript
var err = new gutil.PluginError('test', {
message: 'something broke'
});
var err = new gutil.PluginError({
plugin: 'test',
message: 'something broke'
});
...beep = function (val, cb) {
if (!process.stdout.isTTY ||
process.argv.indexOf('--no-beep') !== -1 ||
process.argv.indexOf('--beep=false') !== -1) {
return;
}
cb = cb || function () {};
if (val === parseInt(val)) {
if (val < 0) {
throw new TypeError('Negative numbers are not accepted');
}
if (val === 0) {
cb();
return;
}
for (var i = 0; i < val; i++) {
setTimeout(function (i) {
beep();
if (i === val - 1) {
cb();
}
}, BEEP_DELAY * i, i);
}
} else if (!val) {
beep();
cb();
} else if (typeof val === 'string') {
melodicalBeep(val.split(''), cb);
} else {
throw new TypeError('Not an accepted type');
}
}n/a
buffer = function (fn) {
var buf = [];
var end = function(cb) {
this.push(buf);
cb();
if(fn) fn(null, buf);
};
var push = function(data, enc, cb) {
buf.push(data);
cb();
};
return through.obj(push, end);
}...
The stream will emit one data event after the stream piped to it has ended. The data will be the same array passed to the callback
.
Callback is optional and receives two arguments: error and data
```javascript
gulp.src('stuff/*.js')
.pipe(gutil.buffer(function(err, files) {
}));
```
## new PluginError(pluginName, message[, options])
- pluginName should be the module name of your plugin
...combine = function (){
var args = arguments;
if (args.length === 1 && Array.isArray(args[0])) {
args = args[0];
}
return function(){
return pipeline.apply(pipeline, args);
};
}n/a
date = function (date, mask, utc, gmt) {
// You can't provide utc if you skip other args (use the 'UTC:' mask prefix)
if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) {
mask = date;
date = undefined;
}
date = date || new Date;
if(!(date instanceof Date)) {
date = new Date(date);
}
if (isNaN(date)) {
throw TypeError('Invalid date');
}
mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']);
// Allow setting the utc/gmt argument via the mask
var maskSlice = mask.slice(0, 4);
if (maskSlice === 'UTC:' || maskSlice === 'GMT:') {
mask = mask.slice(4);
utc = true;
if (maskSlice === 'GMT:') {
gmt = true;
}
}
var _ = utc ? 'getUTC' : 'get';
var d = date[_ + 'Date']();
var D = date[_ + 'Day']();
var m = date[_ + 'Month']();
var y = date[_ + 'FullYear']();
var H = date[_ + 'Hours']();
var M = date[_ + 'Minutes']();
var s = date[_ + 'Seconds']();
var L = date[_ + 'Milliseconds']();
var o = utc ? 0 : date.getTimezoneOffset();
var W = getWeek(date);
var N = getDayOfWeek(date);
var flags = {
d: d,
dd: pad(d),
ddd: dateFormat.i18n.dayNames[D],
dddd: dateFormat.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dateFormat.i18n.monthNames[m],
mmmm: dateFormat.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(Math.round(L / 10)),
t: H < 12 ? 'a' : 'p',
tt: H < 12 ? 'am' : 'pm',
T: H < 12 ? 'A' : 'P',
TT: H < 12 ? 'AM' : 'PM',
Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''),
o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10],
W: W,
N: N
};
return mask.replace(token, function (match) {
if (match in flags) {
return flags[match];
}
return match.slice(1, match.length - 1);
});
}n/a
isBuffer = function (o) {
return typeof o === 'object' && o instanceof Buffer;
}n/a
isNull = function (v) {
return v === null;
}n/a
isStream = function (o) {
return !!o && o instanceof Stream;
}n/a
log = function (){
if(hasGulplog()){
// specifically deferring loading here to keep from registering it globally
var gulplog = require('gulplog');
gulplog.info.apply(gulplog, arguments);
} else {
// specifically defering loading because it might not be used
var fancylog = require('fancy-log');
fancylog.apply(null, arguments);
}
return this;
}...
</table>
## Usage
```javascript
var gutil = require('gulp-util');
gutil.log('stuff happened', 'Really it did', gutil.colors.magenta
('123'));
gutil.replaceExtension('file.coffee', '.js'); // file.js
var opt = {
name: 'todd',
file: someGulpFile
};
...noop = function () {
return through.obj();
}...
```javascript
// gulp should be called like this :
// $ gulp --type production
gulp.task('scripts', function() {
gulp.src('src/**/*.js')
.pipe(concat('script.js'))
.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
.pipe(gulp.dest('dist/'));
});
```
## buffer(cb)
This is similar to es.wait but instead of buffering text into one string it buffers anything into an array (so very useful for file
objects).
...replaceExtension = function (npath, ext) {
if (typeof npath !== 'string') return npath;
if (npath.length === 0) return npath;
var nFileName = path.basename(npath, path.extname(npath))+ext;
return path.join(path.dirname(npath), nFileName);
}...
## Usage
```javascript
var gutil = require('gulp-util');
gutil.log('stuff happened', 'Really it did', gutil.colors.magenta('123'));
gutil.replaceExtension('file.coffee', '.js'); // file.js
var opt = {
name: 'todd',
file: someGulpFile
};
gutil.template('test <%= name %> <%= file.path %>', opt) // test todd /js/hi.js
```
...template = function (tmpl, data) {
var fn = template(tmpl, forcedSettings);
var wrapped = function(o) {
if (typeof o === 'undefined' || typeof o.file === 'undefined') {
throw new Error('Failed to provide the current file as "file" to the template');
}
return fn(o);
};
return (data ? wrapped(data) : wrapped);
}...
gutil.replaceExtension('file.coffee', '.js'); // file.js
var opt = {
name: 'todd',
file: someGulpFile
};
gutil.template('test <%= name %> <%= file.path %>', opt
) // test todd /js/hi.js
```
### log(msg...)
Logs stuff. Already prefixed with [gulp] and all that. If you pass in multiple arguments it will join them by a space.
The default gulp coloring using gutil.colors.<color>:
...function File(file) {
if (!file) file = {};
// record path change
var history = file.path ? [file.path] : file.history;
this.history = history || [];
this.cwd = file.cwd || process.cwd();
this.base = file.base || this.cwd;
// stat = files stats object
this.stat = file.stat || null;
// contents = stream, buffer, or null if not read
this.contents = file.contents || null;
this._isVinyl = true;
}...
This is a lodash.template function wrapper. You must pass in a valid gulp file object so it is available to the user or it will
error. You can not configure any of the delimiters. Look at the [lodash docs](http://lodash.com/docs#template) for more info.
## new File(obj)
This is just [vinyl](https://github.com/wearefractal/vinyl)
```javascript
var file = new gutil.File({
base: path.join(__dirname, './fixtures/'),
cwd: __dirname,
path: path.join(__dirname, './fixtures/test.coffee')
});
```
## noop()
...isVinyl = function (file) {
return file && file._isVinyl === true;
}n/a
clone = function (opt) {
if (typeof opt === 'boolean') {
opt = {
deep: opt,
contents: true
};
} else if (!opt) {
opt = {
deep: true,
contents: true
};
} else {
opt.deep = opt.deep === true;
opt.contents = opt.contents !== false;
}
// clone our file contents
var contents;
if (this.isStream()) {
contents = this.contents.pipe(new Stream.PassThrough());
this.contents = this.contents.pipe(new Stream.PassThrough());
} else if (this.isBuffer()) {
contents = opt.contents ? cloneBuffer(this.contents) : this.contents;
}
var file = new File({
cwd: this.cwd,
base: this.base,
stat: (this.stat ? cloneStats(this.stat) : null),
history: this.history.slice(),
contents: contents
});
// clone our custom properties
Object.keys(this).forEach(function(key) {
// ignore built-in fields
if (key === '_contents' || key === 'stat' ||
key === 'history' || key === 'path' ||
key === 'base' || key === 'cwd') {
return;
}
file[key] = opt.deep ? clone(this[key], true) : this[key];
}, this);
return file;
}n/a
inspect = function () {
var inspect = [];
// use relative path if possible
var filePath = (this.base && this.path) ? this.relative : this.path;
if (filePath) {
inspect.push('"'+filePath+'"');
}
if (this.isBuffer()) {
inspect.push(this.contents.inspect());
}
if (this.isStream()) {
inspect.push(inspectStream(this.contents));
}
return '<File '+inspect.join(' ')+'>';
}n/a
isBuffer = function () {
return isBuffer(this.contents);
}n/a
isDirectory = function () {
return this.isNull() && this.stat && this.stat.isDirectory();
}n/a
isNull = function () {
return isNull(this.contents);
}n/a
isStream = function () {
return isStream(this.contents);
}n/a
pipe = function (stream, opt) {
if (!opt) opt = {};
if (typeof opt.end === 'undefined') opt.end = true;
if (this.isStream()) {
return this.contents.pipe(stream, opt);
}
if (this.isBuffer()) {
if (opt.end) {
stream.end(this.contents);
} else {
stream.write(this.contents);
}
return stream;
}
// isNull
if (opt.end) stream.end();
return stream;
}...
Returns a stream that does nothing but pass data straight through.
```javascript
// gulp should be called like this :
// $ gulp --type production
gulp.task('scripts', function() {
gulp.src('src/**/*.js')
.pipe(concat('script.js'))
.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
.pipe(gulp.dest('dist/'));
});
```
## buffer(cb)
...function PluginError(plugin, message, opt) {
if (!(this instanceof PluginError)) throw new Error('Call PluginError using new');
Error.call(this);
var options = parseOptions(plugin, message, opt);
var self = this;
// if options has an error, grab details from it
if (options.error) {
// These properties are not enumerable, so we have to add them explicitly.
arrayUniq(Object.keys(options.error).concat(nonEnumberableProperties))
.forEach(function(prop) {
self[prop] = options.error[prop];
});
}
var properties = ['name', 'message', 'fileName', 'lineNumber', 'stack', 'showStack', 'showProperties', 'plugin'];
// options object can override
properties.forEach(function(prop) {
if (prop in options) this[prop] = options[prop];
}, this);
// defaults
if (!this.name) this.name = 'Error';
if (!this.stack) {
// Error.captureStackTrace appends a stack property which relies on the toString method of the object it is applied to.
// Since we are using our own toString method which controls when to display the stack trace if we don't go through this
// safety object, then we'll get stack overflow problems.
var safety = {
toString: function() {
return this._messageWithDetails() + '\nStack:';
}.bind(this)
};
Error.captureStackTrace(safety, arguments.callee || this.constructor);
this.__safety = safety;
}
if (!this.plugin) throw new Error('Missing plugin name');
if (!this.message) throw new Error('Missing error message');
}...
- If you pass an error in as the message the stack will be pulled from that, otherwise one will be created.
- Note that if you pass in a custom stack string you need to include the message along with that.
- Error properties will be included in `err.toString()`. Can be omitted by including `{showProperties: false}` in the options.
These are all acceptable forms of instantiation:
```javascript
var err = new gutil.PluginError('test', {
message: 'something broke'
});
var err = new gutil.PluginError({
plugin: 'test',
message: 'something broke'
});
...function Error() { [native code] }n/a
_messageDetails = function () {
if (!this.showProperties) {
return '';
}
var properties = arrayDiffer(Object.keys(this), propertiesNotToDisplay);
if (properties.length === 0) {
return '';
}
var self = this;
properties = properties.map(function stringifyProperty(prop) {
return ' ' + prop + ': ' + self[prop];
});
return 'Details:\n' + properties.join('\n');
}n/a
_messageWithDetails = function () {
var messageWithDetails = 'Message:\n ' + this.message;
var details = this._messageDetails();
if (details !== '') {
messageWithDetails += '\n' + details;
}
return messageWithDetails;
}n/a
toString = function () {
var sig = chalk.red(this.name) + ' in plugin \'' + chalk.cyan(this.plugin) + '\'';
var detailsWithStack = function(stack) {
return this._messageWithDetails() + '\nStack:\n' + stack;
}.bind(this);
var msg;
if (this.showStack) {
if (this.__safety) { // There is no wrapped error, use the stack captured in the PluginError ctor
msg = this.__safety.stack;
} else if (this._stack) {
msg = detailsWithStack(this._stack);
} else { // Stack from wrapped error
msg = detailsWithStack(this.stack);
}
} else {
msg = this._messageWithDetails();
}
return sig + '\n' + msg;
}...
## new PluginError(pluginName, message[, options])
- pluginName should be the module name of your plugin
- message can be a string or an existing error
- By default the stack will not be shown. Set `options.showStack` to true if you think the stack is important for your error.
- If you pass an error in as the message the stack will be pulled from that, otherwise one will be created.
- Note that if you pass in a custom stack string you need to include the message along with that.
- Error properties will be included in `err.toString()`. Can be omitted by including `{
showProperties: false}` in the options.
These are all acceptable forms of instantiation:
```javascript
var err = new gutil.PluginError('test', {
message: 'something broke'
});
...hasColor = function () { [native code] }n/a
stripColor = function (str) {
return typeof str === 'string' ? str.replace(ansiRegex, '') : str;
}n/a