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