1
1
'use strict'
2
2
3
3
const fs = require ( 'fs' )
4
+ const os = require ( 'os' )
4
5
const { cwd, exists} = require ( '../util' )
5
6
const chalk = require ( 'chalk' )
6
7
const path = require ( 'path' )
8
+ const ignoreFiles = [ '_navbar' , '_coverpage' , '_sidebar' ]
7
9
8
10
// eslint-disable-next-line
9
11
module . exports = function ( path = '' , sidebar ) {
10
12
const cwdPath = cwd ( path || '.' )
11
13
12
14
if ( exists ( cwdPath ) ) {
13
15
if ( sidebar ) {
14
- console . log ( sidebar )
15
16
const sidebarPath = cwdPath + '/' + sidebar || '_sidebar.md'
16
17
17
18
if ( ! exists ( sidebarPath ) ) {
18
19
genSidebar ( cwdPath , sidebarPath )
20
+ console . log ( chalk . green ( `Generate sidebar file '${ sidebar } ' success.` ) )
19
21
return true
20
22
}
21
23
@@ -28,27 +30,48 @@ module.exports = function (path = '', sidebar) {
28
30
}
29
31
30
32
function genSidebar ( cwdPath , sidebarPath ) {
31
- let node = ''
32
- travel ( cwdPath , function ( pathname ) {
33
+ let tree = ''
34
+ let lastPath = ''
35
+ let nodeName = ''
36
+ getDirFiles ( cwdPath , function ( pathname ) {
33
37
path . relative ( pathname , cwdPath )
34
38
pathname = pathname . replace ( cwdPath + '/' , '' )
35
- node += '* [' + path . basename ( pathname , '.md' ) + '](' + pathname + ')\n'
39
+ let filename = path . basename ( pathname , '.md' )
40
+ let splitPath = pathname . split ( path . sep )
41
+
42
+ if ( ignoreFiles . indexOf ( filename ) === - 1 ) {
43
+ nodeName = '- [' + filename + '](' + pathname + ')' + os . EOL
44
+ }
45
+
46
+ if ( splitPath . length > 1 ) {
47
+ if ( splitPath [ 0 ] !== lastPath ) {
48
+ lastPath = splitPath [ 0 ]
49
+ tree += os . EOL + '- ' + splitPath [ 0 ] + os . EOL
50
+ }
51
+
52
+ tree += ' ' + nodeName
53
+ } else {
54
+ if ( lastPath !== '' ) {
55
+ lastPath = ''
56
+ tree += os . EOL
57
+ }
58
+
59
+ tree += nodeName
60
+ }
36
61
} )
37
- fs . writeFile ( sidebarPath , node , 'utf8' , err => {
62
+ fs . writeFile ( sidebarPath , tree , 'utf8' , err => {
38
63
if ( err ) {
39
- throw err
64
+ console . log ( chalk . red ( `Generate sidebar file error, message: ${ err . message } ` ) )
40
65
}
41
-
42
- console . log ( 'gen success' )
43
66
} )
44
67
}
45
68
46
- function travel ( dir , callback ) {
69
+ function getDirFiles ( dir , callback ) {
47
70
fs . readdirSync ( dir ) . forEach ( function ( file ) {
48
71
let pathname = path . join ( dir , file )
49
72
50
73
if ( fs . statSync ( pathname ) . isDirectory ( ) ) {
51
- travel ( pathname , callback )
74
+ getDirFiles ( pathname , callback )
52
75
} else if ( path . extname ( file ) === '.md' ) {
53
76
callback ( pathname )
54
77
}
0 commit comments