Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: generate sidebar nested #160

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 77 additions & 40 deletions lib/commands/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {cwd, exists} = require('../util')
const path = require('path')
const logger = require('../util/logger')
const ignoreFiles = ['_navbar', '_coverpage', '_sidebar']
const indent = ' '

// eslint-disable-next-line
module.exports = function (path = '', sidebar) {
Expand All @@ -16,7 +17,8 @@ module.exports = function (path = '', sidebar) {
const sidebarPath = cwdPath + '/' + sidebar || '_sidebar.md'

if (!exists(sidebarPath)) {
genSidebar(cwdPath, sidebarPath)
const lines = generateSidebar(cwdPath)
writeSidebar(lines, sidebarPath)
logger.success(`Successfully generated the sidebar file '${sidebar}'.`)
return true
}
Expand All @@ -30,51 +32,86 @@ module.exports = function (path = '', sidebar) {
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 + '/', '')
let filename = path.basename(pathname, '.md')
let splitPath = pathname.split(path.sep)

if (ignoreFiles.indexOf(filename) === -1) {
nodeName = '- [' + filename + '](' + pathname + ')' + os.EOL
function generateSidebar(cwdPath) {
return generateSidebarOfDirectory(cwdPath, cwdPath, 0)
}

/**
* @returns a list of string
*/
function generateSidebarOfDirectory(baseDirectory, currentDirectory, indentCount) {
let lines = []
// Current directory
const contentOfCurrentDirectory = generateSidebarContentOfDirectory(currentDirectory, indentCount)
console.log(contentOfCurrentDirectory)
lines.push(contentOfCurrentDirectory)

// Get all directories
const subDirectories = listDirectory(currentDirectory)
for (const subDirectory of subDirectories) {
const subLines = generateSidebarOfDirectory(baseDirectory, subDirectory, indentCount + 1)
for (const subLine of subLines) {
lines.push(subLine)
}
}

if (splitPath.length > 1) {
if (splitPath[0] !== lastPath) {
lastPath = splitPath[0]
tree += os.EOL + '- ' + splitPath[0] + os.EOL
}
// Get all files under currentDirectory
const mdFilePaths = listMdFilePaths(currentDirectory)
for (const mdFilePath of mdFilePaths) {
const mdFilePathLink = generateSidebarLinkOfFile(baseDirectory, mdFilePath, indentCount + 1)
console.log(mdFilePathLink)
lines.push(mdFilePathLink)
}

tree += ' ' + nodeName
} else {
if (lastPath !== '') {
lastPath = ''
tree += os.EOL
return lines
}

function listDirectory(directory) {
return fs.readdirSync(directory)
.map(relativePath => path.join(directory, relativePath))
.filter(path => fs.statSync(path).isDirectory())
}

function listMdFilePaths(directory) {
return fs.readdirSync(directory)
.map(relativePath => path.join(directory, relativePath))
.filter(pathname => !fs.statSync(pathname).isDirectory() && path.extname(pathname) === '.md')
.filter(pathname => {
for (const ignoreFile of ignoreFiles) {
if (pathname.includes(ignoreFile)) {
return false
}
}

tree += nodeName
}
})
fs.writeFile(sidebarPath, tree, 'utf8', err => {
if (err) {
logger.error(`Couldn't generate the sidebar file, error: ${err.message}`)
}
})
return true
})
}

function getDirFiles(dir, callback) {
fs.readdirSync(dir).forEach(function (file) {
let pathname = path.join(dir, file)
function generateSidebarContentOfDirectory(currentDirectory, indentCount) {
const directoryName = path.basename(path.resolve(currentDirectory))
return generateIndents(indentCount) + '- ' + directoryName
}

if (fs.statSync(pathname).isDirectory()) {
getDirFiles(pathname, callback)
} else if (path.extname(file) === '.md') {
callback(pathname)
}
})
function generateSidebarLinkOfFile(baseDirectory, filePath, indentCount) {
return generateIndents(indentCount) + '- ' + generateLinkOfFile(baseDirectory, filePath)
}

function generateIndents(indentCount) {
return indent.repeat(indentCount)
}

function generateRelativePath(baseDirectory, fullPath) {
return path.relative(baseDirectory, fullPath)
}

function generateLinkOfFile(baseDirectory, filePath) {
const name = path.basename(filePath, '.md')
const relativePath = generateRelativePath(baseDirectory, filePath)
const relativePathNormalize = relativePath.split(path.sep).join('/')
return ''.concat('[', name, ']', '(', relativePathNormalize, ')')
}

function writeSidebar(lines, sidebarPath) {
const content = lines.join(os.EOL)
fs.writeFileSync(sidebarPath, content, 'utf8')
}