forked from ef4/ember-code-snippet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsnippet-finder.js
92 lines (78 loc) · 2.29 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* jshint node: true */
/* use strict */
var Plugin = require('broccoli-plugin');
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|ts|coffee|html|hbs|md|css|sass|scss|less|emblem|yaml)"), 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 writeSnippets(files, outputPath, options) {
files.forEach((filename) => {
var regexes = options.snippetRegexes;
var snippets = extractSnippets(fs.readFileSync(filename, 'utf-8'), regexes);
for (var name in snippets) {
var destFile = path.join(outputPath, name);
var includeExtensions = options.includeExtensions;
if (includeExtensions) {
destFile += path.extname(filename);
}
fs.writeFileSync(destFile, snippets[name]);
}
});
}
function SnippetFinder(inputNode, options) {
if (!(this instanceof SnippetFinder)) {
return new SnippetFinder(inputNode, options);
}
Plugin.call(this, [inputNode], {
name: 'SnippetFinder',
annotation: `SnippetFinder output: ${options.outputFile}`,
persistentOutput: options.persistentOutput,
needCache: options.needCache,
});
this.options = options;
}
SnippetFinder.prototype = Object.create(Plugin.prototype);
SnippetFinder.prototype.constructor = SnippetFinder;
SnippetFinder.prototype.build = function() {
return findFiles(this.inputPaths[0]).then((files) => {
writeSnippets(files, this.outputPath, this.options);
});
};
module.exports = SnippetFinder;