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: auto generate sidebar #130

Merged
merged 4 commits into from
Jan 22, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Use `init` to generate your docs.
```shell
docsify init <path> [--local false] [--theme vue]

# docsify i <path> [--local false] [--theme vue]
# docsify i <path> [-l false] [-t vue]
```

`<path>` defaults to the current directory. Use relative paths like `./docs` (or `docs`).
Expand All @@ -75,7 +75,7 @@ Run a server on `localhost` with livereload.
```shell
docsify serve <path> [--open false] [--port 3000]

# docsify s <path> [--open false] [--port 3000]
# docsify s <path> [-o false] [-p 3000]
```

- `--open` option:
Expand All @@ -89,6 +89,22 @@ docsify serve <path> [--open false] [--port 3000]
- Default: `3000`
- Description: Choose a listen port, defaults to `3000`.

### `gen` command
sy-records marked this conversation as resolved.
Show resolved Hide resolved

Docsify's generators.

```shell
docsify generate <path> [--sidebar _sidebar.md]

# docsify g <path> [-s _sidebar.md]
```

- `--sidebar` option:
- Shorthand: `-s`
- Type: string
- Default: `_sidebar.md`
- Description: Generate sidebar file, defaults to `_sidebar.md`.

## Contributing

Please see the [Contributing Guidelines](./CONTRIBUTING.md)
Expand Down
28 changes: 16 additions & 12 deletions e2e/cli.test.js.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ Generated by [AVA](https://avajs.dev).
`Usage: docsify <init|serve> <path>␊
Commands:␊
docsify init [path] Creates new docs [aliases: i]␊
docsify serve [path] Run local server to preview site. [aliases: s]␊
docsify start <path> Server for SSR␊
docsify init [path] Creates new docs [aliases: i]␊
docsify serve [path] Run local server to preview site. [aliases: s]␊
docsify start <path> Server for SSR␊
docsify generate <path> Docsify's generators [aliases: g]␊
Global Options␊
--help, -h Show help [boolean]␊
Expand All @@ -35,9 +36,10 @@ Generated by [AVA](https://avajs.dev).
`Usage: docsify <init|serve> <path>␊
Commands:␊
docsify init [path] Creates new docs [aliases: i]␊
docsify serve [path] Run local server to preview site. [aliases: s]␊
docsify start <path> Server for SSR␊
docsify init [path] Creates new docs [aliases: i]␊
docsify serve [path] Run local server to preview site. [aliases: s]␊
docsify start <path> Server for SSR␊
docsify generate <path> Docsify's generators [aliases: g]␊
Global Options␊
--help, -h Show help [boolean]␊
Expand All @@ -57,9 +59,10 @@ Generated by [AVA](https://avajs.dev).
`Usage: docsify <init|serve> <path>␊
Commands:␊
docsify init [path] Creates new docs [aliases: i]␊
docsify serve [path] Run local server to preview site. [aliases: s]␊
docsify start <path> Server for SSR␊
docsify init [path] Creates new docs [aliases: i]␊
docsify serve [path] Run local server to preview site. [aliases: s]␊
docsify start <path> Server for SSR␊
docsify generate <path> Docsify's generators [aliases: g]␊
Global Options␊
--help, -h Show help [boolean]␊
Expand All @@ -79,9 +82,10 @@ Generated by [AVA](https://avajs.dev).
`Usage: docsify <init|serve> <path>␊
Commands:␊
docsify init [path] Creates new docs [aliases: i]␊
docsify serve [path] Run local server to preview site. [aliases: s]␊
docsify start <path> Server for SSR␊
docsify init [path] Creates new docs [aliases: i]␊
docsify serve [path] Run local server to preview site. [aliases: s]␊
docsify start <path> Server for SSR␊
docsify generate <path> Docsify's generators [aliases: g]␊
Global Options␊
--help, -h Show help [boolean]␊
Expand Down
Binary file modified e2e/cli.test.js.snap
Binary file not shown.
28 changes: 28 additions & 0 deletions e2e/commands/generate.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const test = require('ava')
const fs = require('fs')
const path = require('path')

const {run} = require('../helpers/test-utils.js')

const genPath = path.join(__dirname, 'generate-cmd')
const docsPath = path.join(genPath, 'docs')

test.before('create temp directory', () => {
// Cleanup if the directory already exists
if (fs.existsSync(genPath)) {
fs.rmdirSync(genPath, {recursive: true})
}

fs.mkdirSync(genPath)
})

test.after('cleanup', () => {
fs.rmdirSync(genPath, {recursive: true})
})

test('generate _sidebar.md', t => {
sy-records marked this conversation as resolved.
Show resolved Hide resolved
run(['init', 'docs'], {cwd: genPath})
run(['generate', 'docs'], {cwd: genPath})
// Check for existence
t.true(fs.existsSync(path.join(docsPath, '_sidebar.md')))
})
17 changes: 17 additions & 0 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,23 @@ require('yargs')
}),
handler: argv => run.start(argv.path, argv.config, argv.port)
})
.command({
command: 'generate <path>',
aliases: 'g',
desc: chalk.gray(y18n.__('generate')),
builder: yargs =>
yargs.options({
sidebar: {
alias: 's',
default: '_sidebar.md',
desc: chalk.gray(y18n.__('gen.sidebar')),
nargs: 1,
requiresArg: true,
type: 'string'
}
}),
handler: argv => run.generate(argv.path, argv.sidebar)
})
.help()
.option('help', {
alias: 'h',
Expand Down
79 changes: 79 additions & 0 deletions lib/commands/generate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
'use strict'

const fs = require('fs')
const os = require('os')
const {cwd, exists} = require('../util')
const chalk = require('chalk')
const path = require('path')
const ignoreFiles = ['_navbar', '_coverpage', '_sidebar']

// eslint-disable-next-line
module.exports = function (path = '', sidebar) {
const cwdPath = cwd(path || '.')

if (exists(cwdPath)) {
if (sidebar) {
const sidebarPath = cwdPath + '/' + sidebar || '_sidebar.md'

if (!exists(sidebarPath)) {
genSidebar(cwdPath, sidebarPath)
console.log(chalk.green(`Generate sidebar file '${sidebar}' success.`))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
console.log(chalk.green(`Generate sidebar file '${sidebar}' success.`))
console.log(chalk.green(`Successfully generated the sidebar file '${sidebar}'.`))

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is better to have a logger utility. There are a couple of places that require an update; feel free to address it in a future PR.

- console.error(chalk.red(msg))
+ logger.error(msg)
// logger.js
const error = (msg) => console.error(chalk.red(msg)); 

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the merge, I will submit a PR to amend this

return true
}

console.log(chalk.red(`${sidebarPath}`) + ' already exists.')
sy-records marked this conversation as resolved.
Show resolved Hide resolved
return false
Koooooo-7 marked this conversation as resolved.
Show resolved Hide resolved
}
}

console.log(chalk.red(`${cwdPath}`) + ' directory does not exist.')
sy-records marked this conversation as resolved.
Show resolved Hide resolved
}

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
}

if (splitPath.length > 1) {
if (splitPath[0] !== lastPath) {
lastPath = splitPath[0]
tree += os.EOL + '- ' + splitPath[0] + os.EOL
}

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

tree += nodeName
}
})
fs.writeFile(sidebarPath, tree, 'utf8', err => {
if (err) {
console.log(chalk.red(`Generate sidebar file error, message: ${err.message}`))
sy-records marked this conversation as resolved.
Show resolved Hide resolved
}
})
}

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)
}
})
}
3 changes: 2 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = {
init: require('./commands/init'),
serve: require('./commands/serve'),
start: require('./commands/start')
start: require('./commands/start'),
generate: require('./commands/generate')
}
2 changes: 2 additions & 0 deletions tools/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"serve.open": "Open docs in default browser. To explicitly set --open to false you may use --no-open.",
"serve.port": "Listen port.",
"serve.indexname": "Custom filename instead of index.html to serve by default",
"generate": "Docsify's generators",
"generate.sidebar": "Generate sidebar file",
"livereload.port": "livereload Listen port.",
"usage": "Usage",
"version": "Show version number"
Expand Down
2 changes: 2 additions & 0 deletions tools/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"serve.open": "自动打开浏览器",
"serve.port": "设置端口",
"serve.indexname": "Custom filename instead of index.html to serve by default",
"generate": "Docsify的生成器",
"generate.sidebar": "生成侧边栏文件",
"livereload.port": "设置livereload端口",
"usage": "例子",
"version": "当前版本号"
Expand Down