forked from moudy/broccoli-template-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (62 loc) · 2.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var Transform = require('broccoli-transform');
var RSVP = require('rsvp');
var mkdirp = require('mkdirp');
var walk = require('walk');
var fs = require('fs');
var path = require('path');
DEFAULTS = {
namespace: 'JST'
};
function BroccoliTemplateBuilder(inputTree, options) {
if (!(this instanceof BroccoliTemplateBuilder)) {
return new BroccoliTemplateBuilder(inputTree, options);
}
this.inputTree = inputTree;
this.options = options || {};
this.options.namespace || (options.namespace = DEFAULTS.namespace);
}
BroccoliTemplateBuilder.prototype = Object.create(Transform.prototype);
BroccoliTemplateBuilder.prototype.constructor = BroccoliTemplateBuilder;
BroccoliTemplateBuilder.prototype.targetExtension = 'js';
BroccoliTemplateBuilder.prototype.transform = function (srcDir, destDir) {
var options = this.options;
var files = [];
mkdirp.sync(path.join(destDir, path.dirname(options.outputFile)));
function isMatch (name) {
var extension = path.extname(name).substr(1);
return options.extensions.indexOf(extension) !== -1;
}
function namespace (name, string) {
return options.namespace+'["'+name+'"]='+string;
}
function buildName (file) {
var extension = path.extname(file);
return file.replace(srcDir+'/', '').replace(extension, '');
}
function compile (string) {
return (options.compile ? options.compile(string) : '"'+string+'"')+';\n';
}
return new RSVP.Promise(function(resolve, reject) {
var walker = walk.walk(srcDir);
walker.on('file', function (root, fileStats, next) {
if (!isMatch(fileStats.name)) return next();
var path = root+'/'+fileStats.name;
fs.readFile(path, {encoding: 'utf8'}, function (err, string) {
var name = buildName(path);
string = compile(string);
string = namespace(name, string);
files.push(string);
next();
});
});
walker.on('end', function () {
var data = "if (window.JST === undefined) { window.JST = {}; }\n";
data = data + files.join('');
fs.writeFile(path.join(destDir, options.outputFile), data, function (err) {
if (err) reject(err);
resolve(destDir);
});
});
});
};
module.exports = BroccoliTemplateBuilder;