forked from ef4/ember-code-snippet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snippet-finder.js
78 lines (65 loc) · 1.92 KB
/
snippet-finder.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
/* jshint node: true */
var Writer = require('broccoli-writer');
var glob = require('glob');
var _Promise = require('es6-promise').Promise;
var fs = require('fs');
var path = require('path');
function findFiles(srcDir) {
return new _Promise(function(resolve, reject) {
glob(path.join(srcDir, "**/*.+(js|coffee|html|hbs|md|css|sass|scss|less|emblem)"), function (err, files) {
if (err) {
reject(err);
} else {
resolve(files);
}
});
});
}
function extractSnippets(fileContent, regexes) {
var stack = [];
var output = {};
fileContent.split("\n").forEach(function(line){
var top = stack[stack.length - 1];
if (top && top.regex.end.test(line)) {
output[top.name] = top.content.join("\n");
stack.pop();
}
stack.forEach(function(snippet) {
snippet.content.push(line);
});
var match;
var regex = regexes.find(function(regex) {
return match = regex.begin.exec(line);
});
if (match) {
stack.push({
regex: regex,
name: match[1],
content: []
});
}
});
return output;
}
function SnippetFinder(inputTree, snippetRegexes) {
if (!(this instanceof SnippetFinder)) {
return new SnippetFinder(inputTree, snippetRegexes);
}
this.inputTree = inputTree;
this.snippetRegexes = snippetRegexes;
}
SnippetFinder.prototype = Object.create(Writer.prototype);
SnippetFinder.prototype.constructor = SnippetFinder;
SnippetFinder.prototype.write = function (readTree, destDir) {
var regexes = this.snippetRegexes;
return readTree(this.inputTree).then(findFiles).then(function(files){
files.forEach(function(filename){
var snippets = extractSnippets(fs.readFileSync(filename, 'utf-8'), regexes);
for (var name in snippets){
fs.writeFileSync(path.join(destDir, name)+path.extname(filename),
snippets[name]);
}
});
});
};
module.exports = SnippetFinder;