-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (83 loc) · 3.04 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
var Bluebird = require('bluebird'),
fs = Bluebird.promisifyAll(require('fs')),
pathUtil = require('path'),
Pecan = require('pecan');
module.exports = function asparagus(src, options) {
// default options
options = options || {};
src = src || options.src;
// throw if src is not defined
if (!src) {
throw new Error('First argument must be the source path');
}
var dest = options.dest || src;
function getFiles(src, dest) {
return findFiles(src)
.map(function (filename) {
if (isDirname(filename)) {
return resolveWith(filename, src, dest);
} else {
// if a file, compile it and return the compiler
return compileFile(null, {
src: src,
dest: dest,
filename: filename
}, options);
}
})
.catch(function (err) {
return compileFile(err, {
src: src,
dest: dest,
filename: pathUtil.basename(src)
}, options);
});
}
function resolveWith(dirname, src, dest) {
return new Bluebird(function (resolve) {
return resolve(getFiles(pathUtil.join(src, dirname), pathUtil.join(dest, dirname)));
});
}
return getFiles(src, dest);
};
function compileFile(err, attrs, options) {
var errCode = err && err.cause && err.cause.code,
paths;
// If there is no error or the error was 'Not a directory'
if (!err || (errCode === 'ENOTDIR')) {
// If there is no exclusive option or this path is not excluded
if (!options.exclusive || isExclusive(attrs, options)) {
paths = getPaths(attrs.src, attrs.dest, attrs.filename);
// compile
Pecan.create(paths, options).compile();
// listen to the `end` event
Pecan.queue[paths.tmplPath].on('end', function () {
// Call the optional cb if no more to compile
if (typeof options.onEnd === 'function' && Object.keys(Pecan.queue).length === 0) {
options.onEnd(paths);
}
});
}
} else if (errCode !== 'ENOENT' && !isDirname(attrs.filename)) {
throw new Error(err);
}
}
function getPaths(src, dest, filename) {
// if the src/dest paths include the filenames (ext)
src = isDirname(src) ? src : pathUtil.dirname(src);
dest = isDirname(dest) ? dest : pathUtil.dirname(dest);
return {
jsPath: pathUtil.join(dest, filename.replace(pathUtil.extname(filename), '.js')),
tmplPath: pathUtil.join(src, filename)
};
}
function isExclusive(attrs, options) {
return Boolean(options.exclusive && attrs.src.split(pathUtil.sep).indexOf(options.exclusive) !== -1);
}
function isDirname(node) {
return Boolean(pathUtil.extname(node)) === false;
}
function findFiles(source) {
return fs.readdirAsync(source);
}