tooljs-template
Version:
Tool template engine plugin
70 lines (59 loc) • 1.96 kB
JavaScript
/**
* Module dependencies.
*/
var templates = require('consolidate');
var mkdirp = require('mkdirp').sync;
var tool = require('tooljs-tool');
var path = require('path');
var fs = require('fs');
/**
* Expose `plugin`.
*/
module.exports = plugin;
/**
* Tool for copying template files, for generators.
*
* @param {String} source Input file path
* @param {String} [target] Output file path
* @param {Object} [opts]
* @property {String} source
* @property {String} target
* @property {String} local Variable name to store this as a local,
* instead of writing it to a file.
* @return {Function} tool
*/
function plugin(source, target, opts) {
if (target && 'object' == typeof target) opts = target, target = null;
opts = opts || {};
/**
* Initialize a Template resource.
*/
var Template = tool('template')
.input('source', { type: 'string', description: 'Input directory.', required: true })
.input('target', { type: 'string', description: 'Output directory.', required: true })
.input('locals', { type: 'object', description: 'Local variables used in template.', value: {} });
/**
* Execute the tool.
*
* @param {Function} next
*/
Template.prototype.exec = function(next){
// passed in source from plugin function, otherwse whatever the parent output hooked up.
var inputPath = path.join(opts.source || this.source, source);
var outputPath = path.join(opts.target || this.target, target || source);
var self = this;
templates.handlebars(inputPath, this.locals, function(err, output){
if (err) return self.error(err);
if (!opts.local) {
mkdirp(path.dirname(outputPath));
fs.writeFileSync(outputPath, output);
} else {
// TODO: https://github.com/tooljs/tool/issues/6
// find a good way to make local templates like this.
self.locals[opts.local] = output;
}
next();
});
};
return Template;
}