gulp-nette-basepath
Version:
Parse build blocks in Nette/Latte templates and resolves its Nette's basePath variable.
97 lines (74 loc) • 3.21 kB
JavaScript
var gutil = require('gulp-util');
var through = require('through2');
var useref = require('node-useref');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var restoreStream = through.obj();
module.exports = function (options) {
var opts = options || {};
var verbose = opts.verbose || false;
if(!opts.basePath) {
opts.basePath = './www';
}
function resolveBasePath(filePath, options) {
return filePath.replace('{$basePath}', options.basePath);
}
return through.obj(function (file, enc, cb) {
if(verbose) {
console.log('Processing '+file.path);
}
var output = useref(file.contents.toString());
var assets = output[1];
['css', 'js'].forEach(function (type) {
var files = assets[type];
if (files) {
Object.keys(files).forEach(function (name) {
var buffer = [];
var filepaths = files[name].assets;
if (filepaths.length) {
var searchPaths;
if (files[name].searchPaths) {
searchPaths = path.join(file.cwd, files[name].searchPaths);
} else if (opts.searchPath) {
if (Array.isArray(opts.searchPath)) {
searchPaths = '{' + opts.searchPath.join(',') + '}';
} else {
searchPaths = opts.searchPath;
}
searchPaths = path.join(file.cwd, searchPaths);
} else {
searchPaths = process.cwd();
}
filepaths.forEach(function (filepath) {
filepath = resolveBasePath(filepath, opts);
if(verbose) {
console.log(filepath);
}
filepath = path.join((searchPaths || file.base), filepath);
filepath = glob.sync(filepath);
try {
buffer.push(fs.readFileSync(filepath[0]));
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-nette-basepath', err));
}
}, this);
var resolved = resolveBasePath(name, opts);
if(verbose) {
console.log('==> '+resolved);
}
var joinedFile = new gutil.File({
cwd: file.cwd,
base: file.base,
path: path.join(file.base, resolved),
contents: new Buffer(buffer.join(gutil.linefeed))
});
this.push(joinedFile);
}
}, this);
}
}, this);
restoreStream.write(file, cb);
});
};
;