vivid-builder
Version:
Simple JavaScript packages builder
106 lines (87 loc) • 2.99 kB
JavaScript
// Generated by CoffeeScript 1.3.3
var Template, events, fs, path,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
fs = require('fs');
path = require('path');
events = require('events');
Template = (function(_super) {
var fileExp, headExp, includeExp, position;
__extends(Template, _super);
includeExp = null;
fileExp = /\(\s*[\'\"]([.\/\\\w\s]+)[\'\"]\s*\)/i;
headExp = /(^|[^\\w])/;
position = 0;
Template.prototype.output = '';
Template.prototype.deps = {};
function Template(file, token, deprecated) {
var _this = this;
this.file = file;
this.token = token;
this.deprecated = deprecated != null ? deprecated : false;
if (deprecated) {
includeExp = /\/\/\<\!include\s+file\="[^"]*"\-\-\>/gi;
fileExp = /file="([^"]*)"/i;
headExp = /(^)/;
} else {
includeExp = new RegExp("(^|[^\\w])" + (this.token || 'include') + "\\s*\\(\\s*[\\'\\\"][.\\/\\\\\\w\\s]+[\\'\\\"]\\s*\\);?", 'gi');
}
fs.readFile(this.file, 'utf8', function(err, rawContent) {
_this.rawContent = rawContent;
if (err) {
throw err;
} else {
_this.basedir = path.dirname(_this.file);
_this.parse();
return _this.compile();
}
});
}
Template.prototype.parse = function() {
var inc, matches;
matches = this.rawContent.match(includeExp);
this.includes = matches ? (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = matches.length; _i < _len; _i++) {
inc = matches[_i];
_results.push(inc.match(fileExp)[1]);
}
return _results;
})() : [];
return this;
};
Template.prototype.dep = function(file, cb) {
var fullPath, tpl,
_this = this;
fullPath = path.join(this.basedir, file);
tpl = new Template(fullPath, this.token, this.deprecated);
return tpl.on('compiled', function() {
_this.deps[file] = tpl.output;
if (++position < _this.includes.length) {
return _this.dep(_this.includes[position], cb);
} else {
return cb();
}
});
};
Template.prototype.compile = function() {
var _this = this;
if (this.includes.length) {
this.dep(this.includes[position], function() {
_this.output = _this.rawContent.replace(includeExp, function(include, offset, all) {
var file;
file = include.match(fileExp)[1];
return include.match(headExp)[0] + _this.deps[file];
});
return _this.emit('compiled');
});
} else {
this.output = this.rawContent;
this.emit('compiled');
}
return this;
};
return Template;
})(events.EventEmitter);
module.exports = Template;