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