-
Notifications
You must be signed in to change notification settings - Fork 7
/
gen_summary.js
75 lines (55 loc) · 2.13 KB
/
gen_summary.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const fs = require('fs'),
path = require('path'),
Parser = require('markdown-parser2')
function generate(parser, root, prefix, path, level) {
result = parser.parse(
fs.readFileSync(`${path}`, { encoding: 'utf8' }))
let title = 'unknown'
if (result.headings.length) {
title = result.headings[0].trim()
}
msg = `${Array(level).join(' ')}- [${title}](${path})\n`
return msg
}
function init() {
const parser = new Parser(),
root = './',
readmeFilename = "README.md",
summaryFilename = 'SUMMARY.md'
let ret = Promise.resolve(),
summaryContent = ''
const isReadme = path => path.includes(readmeFilename)
const walkSync = (dir, pattern, ignorelist = [], level = 1, prefix = '') => {
let index = level == 1 ? 1 : 0
fs.readdirSync(dir).sort((a, b) => {
if (isReadme(a) && !isReadme(b)) {
return -1
} else if (!isReadme(a) && isReadme(b)) {
return 1
}
return a < b ? -1 : a > b ? 1 : 0
}).forEach(file => {
let isDir = fs.statSync(path.join(dir, file)).isDirectory()
if ((file.match(pattern) && !ignorelist.includes(file)) || (isDir && !ignorelist.includes(file))) {
if (index == 0) {
adding = prefix
} else {
adding = prefix ? prefix + '.' + index : '' + index
}
if (isDir) {
walkSync(path.join(dir, file), pattern, ignorelist, level + 1, adding)
} else {
summaryContent += generate(parser, root, adding, path.join(dir, file), index == 0 ? level - 1 : level)
}
if (level == 1) {
summaryContent += '\n\n'
}
index = index + 1
}
})
};
walkSync(root, `\.md$`, ['node_modules', '.git', '_book', summaryFilename])
fs.writeFileSync(`${root}/${summaryFilename}`, summaryContent, { encoding: 'utf8' })
console.log(`\x1b[32m${summaryFilename} generated successfully.`)
}
init()