1 |
|
2 |
|
3 |
|
4 |
|
5 | const fs = require('fs');
|
6 | const path = require('path');
|
7 | const walk = require('walk');
|
8 | const yamlFront = require('yaml-front-matter');
|
9 | const sh = require('child_process').execSync;
|
10 |
|
11 | const dist = __dirname + '/tmp';
|
12 |
|
13 | function parseData(arr, page, rank, file) {
|
14 | if (!arr.length) {
|
15 | const files = [];
|
16 | files[rank] = file;
|
17 | arr.push({
|
18 | 'page': page,
|
19 | 'files': files
|
20 | })
|
21 | return;
|
22 | }
|
23 |
|
24 | arr.every(item => {
|
25 | if (item.page == page) {
|
26 | item.files[rank] = file;
|
27 | return false;
|
28 | }
|
29 | return true;
|
30 | });
|
31 | }
|
32 |
|
33 | function writeFiles(data) {
|
34 |
|
35 | if (fs.existsSync(dist)) sh(`rm -rf ${dist}`);
|
36 | fs.mkdirSync(dist);
|
37 |
|
38 | for(var k in data) {
|
39 | const category = data[k];
|
40 | category.forEach(item => {
|
41 | let outFile = '';
|
42 | item.files.forEach(f => {
|
43 | outFile += `require('${f}'),\n`
|
44 | })
|
45 |
|
46 | let out = `module.exports = [\n${outFile}]`
|
47 |
|
48 | fs.writeFileSync(dist + `/__${item.page}.js`, out);
|
49 | });
|
50 | }
|
51 | }
|
52 |
|
53 | module.exports = function walkMD(config, callback) {
|
54 | const mdData = {};
|
55 |
|
56 | const walker = walk.walk(config.root);
|
57 | walker.on('file', function (root, fileStats, next) {
|
58 | const name = fileStats.name;
|
59 | const ext = path.extname(name);
|
60 | const basename = path.basename(name, config.ext);
|
61 |
|
62 | const file = path.resolve('', root + '/' + name);
|
63 |
|
64 | if (ext === config.ext) {
|
65 | const input = fs.readFileSync(file, 'utf-8');
|
66 | const yaml = yamlFront.loadFront(input, 'content');
|
67 |
|
68 | const page = yaml.page;
|
69 | const rank = yaml.rank;
|
70 | let category = yaml.category;
|
71 |
|
72 | if (!category) category = '__default__';
|
73 |
|
74 |
|
75 | if (!mdData[category]) mdData[category] = [];
|
76 | parseData(mdData[category], page, rank, file);
|
77 |
|
78 |
|
79 |
|
80 | }
|
81 |
|
82 | next();
|
83 | });
|
84 |
|
85 | walker.on('end', () => {
|
86 | console.log(mdData);
|
87 | writeFiles(mdData);
|
88 |
|
89 |
|
90 | const data = {
|
91 | md: mdData,
|
92 | config: config
|
93 | }
|
94 | fs.writeFileSync(dist + '/__md__.json', JSON.stringify(data));
|
95 | if (callback) callback(mdData);
|
96 | });
|
97 |
|
98 | walker.on('error', (e) => {
|
99 | console.log(e);
|
100 | });
|
101 | } |
\ | No newline at end of file |