-
-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathgenerate.js
87 lines (72 loc) · 2.22 KB
/
generate.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
76
77
78
79
80
81
82
83
84
85
86
87
'use strict'
const fs = require('fs')
const os = require('os')
const {cwd, exists} = require('../util')
const path = require('path')
const logger = require('../util/logger')
const ignoreFiles = ['_navbar', '_coverpage', '_sidebar']
module.exports = function (path, sidebar, options) {
const cwdPath = cwd(path || '.')
if (exists(cwdPath)) {
if (sidebar) {
const sidebarPath = cwdPath + '/' + sidebar || '_sidebar.md'
if (!exists(sidebarPath) || options.overwrite) {
genSidebar(cwdPath, sidebarPath)
logger.success(`Successfully generated the sidebar file '${sidebar}'.`)
return true
}
logger.error(`The sidebar file '${sidebar}' already exists.`)
process.exitCode = 1
return false
}
}
logger.error(`${cwdPath} directory does not exist.`)
}
function genSidebar(cwdPath, sidebarPath) {
let tree = ''
let lastPath = ''
let nodeName = ''
getDirFiles(cwdPath, function (pathname) {
path.relative(pathname, cwdPath)
pathname = pathname.replace(cwdPath + path.sep, '')
let filename = path.basename(pathname, '.md')
let splitPath = pathname.split(path.sep)
if (ignoreFiles.indexOf(filename) !== -1) {
return true
}
nodeName = '- [' + toCamelCase(filename) + '](' + pathname.replace(/\\/g, '/') + ')' + os.EOL
if (splitPath.length > 1) {
if (splitPath[0] !== lastPath) {
lastPath = splitPath[0]
tree += os.EOL + '- ' + toCamelCase(splitPath[0]) + os.EOL
}
tree += ' ' + nodeName
} else {
if (lastPath !== '') {
lastPath = ''
tree += os.EOL
}
tree += nodeName
}
})
fs.writeFile(sidebarPath, tree, 'utf8', err => {
if (err) {
logger.error(`Couldn't generate the sidebar file, error: ${err.message}`)
}
})
}
function getDirFiles(dir, callback) {
fs.readdirSync(dir).forEach(function (file) {
let pathname = path.join(dir, file)
if (fs.statSync(pathname).isDirectory()) {
getDirFiles(pathname, callback)
} else if (path.extname(file) === '.md') {
callback(pathname)
}
})
}
function toCamelCase(str) {
return str.replace(/\b(\w)/g, function (match, capture) {
return capture.toUpperCase()
}).replace(/-|_/g, ' ')
}