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