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