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