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) {
|
14 |
|
15 | return new Promise((resolve, reject) => {
|
16 | const dist = config.theme + '/tmp';
|
17 | const mdData = {};
|
18 | const source = {};
|
19 |
|
20 | function parseData(arr, category, page, rank, file) {
|
21 | const key = category + "_" + page;
|
22 |
|
23 | let have = !!arr.length;
|
24 |
|
25 | have = arr.some(item => {
|
26 | if (item.key === key) {
|
27 | item.files[rank] = file;
|
28 | return true;
|
29 | }
|
30 |
|
31 | return false;
|
32 | });
|
33 |
|
34 | if (!have) {
|
35 | arr.push(
|
36 | {
|
37 | page,
|
38 | key,
|
39 | files: [file]
|
40 | }
|
41 | )
|
42 | }
|
43 | }
|
44 |
|
45 | function writeFiles(data) {
|
46 | for(var k in data) {
|
47 | const category = data[k];
|
48 | category.forEach(item => {
|
49 | const key = item.key;
|
50 | let outFile = '';
|
51 | item.files.forEach(f => {
|
52 | outFile += `require('${f}'),\n`;
|
53 | })
|
54 |
|
55 | source[key] = `./tmp/__${key}`;
|
56 |
|
57 | const out = `module.exports = [\n${outFile}]`;
|
58 | fs.writeFileSync(dist + `/__${key}.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 | if (!mdData[category]) mdData[category] = [];
|
82 | parseData(mdData[category], category, page, rank, file);
|
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 | source: source,
|
100 | root: process.cwd()
|
101 | }
|
102 | fs.writeFileSync(dist + '/__md__.json', JSON.stringify(data, null, 4));
|
103 |
|
104 | resolve();
|
105 | });
|
106 |
|
107 | walker.on('error', (e) => {
|
108 | console.log(e);
|
109 | reject(e);
|
110 | });
|
111 | });
|
112 | } |
\ | No newline at end of file |