-
Notifications
You must be signed in to change notification settings - Fork 52
/
snippet-finder.js
92 lines (78 loc) · 2.32 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
/* use strict */
const Plugin = require('broccoli-plugin');
const glob = require('glob');
const _Promise = require('es6-promise').Promise;
const fs = require('fs');
const path = require('path');
function findFiles(srcDir, options) {
let fileNamePattern = `**/*.+(${options.snippetExtensions.join('|')})`;
return new _Promise(function(resolve, reject) {
glob(path.join(srcDir, fileNamePattern), function (err, files) {
if (err) {
reject(err);
} else {
resolve(files);
}
});
});
}
function extractSnippets(fileContent, regexes) {
let stack = [];
let output = {};
fileContent.split("\n").forEach(function(line){
let 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);
});
let match;
let 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) => {
let regexes = options.snippetRegexes;
let snippets = extractSnippets(fs.readFileSync(filename, 'utf-8'), regexes);
for (let name in snippets) {
let destFile = path.join(outputPath, name);
let 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], this.options).then((files) => {
writeSnippets(files, this.outputPath, this.options);
});
};
module.exports = SnippetFinder;