Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
89 lines (69 loc) · 2.52 KB
/
Copy pathindex.js
File metadata and controls
89 lines (69 loc) · 2.52 KB
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
/* eslint-env node */
'use strict';
const Plugin = require('broccoli-plugin');
const frontmatter = require('front-matter');
const mkdirp = require('mkdirp');
const fs = require('fs');
const path = require('path');
MarkdownResolver.prototype = Object.create(Plugin.prototype);
MarkdownResolver.prototype.constructor = MarkdownResolver;
function MarkdownResolver(inputNodes, options) {
options = options || {};
Plugin.call(this, inputNodes, options);
this.options = options;
}
MarkdownResolver.prototype.readDirectory = function(srcPath, allFiles) {
let files = fs.readdirSync(srcPath);
return Array.prototype.reduce.call(files, (tree, file) => {
let entry,
fileExt = path.extname(file),
fileName = file.replace(/\.[^/.]+$/, ''),
relativePath = this.relativePath(path.join(srcPath, fileName)),
isDirectory = fs.lstatSync(path.join(srcPath, file)).isDirectory();
if (!isDirectory && fileExt !== '.md') { return [...tree]; }
let index;
let existingTreeNode = Array.prototype.find.call(tree, (file, i) => {
index = i;
return file.path === relativePath;
});
if (existingTreeNode) {
entry = existingTreeNode;
} else {
entry = { path: relativePath };
}
if (isDirectory) {
entry.children = this.readDirectory(path.join(srcPath, file), allFiles);
} else {
let content = fs.readFileSync(path.join(srcPath, file), { encoding: 'utf8' });
content = frontmatter(content);
entry.content = content.body;
entry.attributes = content.attributes;
allFiles.push(entry);
}
if (existingTreeNode) {
tree[index] = entry;
}
return existingTreeNode ? [...tree] : [...tree, entry];
}, []);
}
MarkdownResolver.prototype.relativePath = function(srcDir) {
let relPath = srcDir.replace(this.options.basePath, '');
return relPath.replace(/^\/|\/$/g, '');
}
MarkdownResolver.prototype.build = function() {
let output = { files: [] };
output.trees = Array.prototype.reduce.call(this._inputNodes, (trees, srcDir) => {
trees[this.relativePath(srcDir)] = this.readDirectory(srcDir, output.files);
return trees;
}, {});
let outputBuffer = `
export let trees = ${JSON.stringify(output.trees, null, 2)};
export let files = ${JSON.stringify(output.files, null, 2)};
export default {
trees, files
};
`;
mkdirp.sync(path.join(this.outputPath, path.dirname(this.options.outputFile)));
fs.writeFileSync(path.join(this.outputPath, this.options.outputFile), outputBuffer);
};
module.exports = MarkdownResolver;