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 | for(var k in data) {
|
41 | const category = data[k];
|
42 | category.forEach(item => {
|
43 | const newPage = k + '_' + item.page;
|
44 | let outFile = '';
|
45 | item.files.forEach(f => {
|
46 | outFile += `require('${f}'),\n`;
|
47 | })
|
48 |
|
49 | source[newPage] = `./tmp/__${newPage}`;
|
50 |
|
51 | const out = `module.exports = [\n${outFile}]`;
|
52 | fs.writeFileSync(dist + `/__${newPage}.js`, out);
|
53 | });
|
54 | }
|
55 | }
|
56 |
|
57 | const walker = walk.walk(config.root);
|
58 | walker.on('file', function (root, fileStats, next) {
|
59 | const name = fileStats.name;
|
60 | const ext = path.extname(name);
|
61 | const basename = path.basename(name, config.ext);
|
62 |
|
63 | const file = path.resolve('', root + '/' + name);
|
64 | if (ext === config.ext) {
|
65 | const input = fs.readFileSync(file, 'utf-8');
|
66 | const yaml = yamlFront.loadFront(input, 'content');
|
67 |
|
68 | const page = yaml.page;
|
69 | const rank = yaml.rank;
|
70 | let category = yaml.category;
|
71 |
|
72 | if (!category) category = '__default__';
|
73 |
|
74 | if (category !== '__nav__') {
|
75 | if (!mdData[category]) mdData[category] = [];
|
76 | parseData(mdData[category], category + '_' + page, rank, file);
|
77 | }
|
78 | }
|
79 | next();
|
80 | });
|
81 |
|
82 | walker.on('end', () => {
|
83 | console.log(chalk.green('=========解析markdown========='));
|
84 | console.log(chalk.green(JSON.stringify(mdData, null, 4)));
|
85 | console.log(chalk.green('=========end========='));
|
86 |
|
87 | writeFiles(mdData);
|
88 |
|
89 |
|
90 | const data = {
|
91 | md: mdData,
|
92 | config: config,
|
93 | source: source,
|
94 | root: process.cwd()
|
95 | }
|
96 | fs.writeFileSync(dist + '/__md__.json', JSON.stringify(data, null, 4));
|
97 | if (callback) callback(mdData);
|
98 | });
|
99 |
|
100 | walker.on('error', (e) => {
|
101 | console.log(e);
|
102 | });
|
103 | } |
\ | No newline at end of file |