Skip to content

Commit

Permalink
feat: adds config option for sorting command output (#1256)
Browse files Browse the repository at this point in the history
  • Loading branch information
trevorlinton authored and bcoe committed Feb 1, 2019
1 parent 7b200d2 commit 6916ce9
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
9 changes: 7 additions & 2 deletions docs/api.md
Expand Up @@ -1151,8 +1151,13 @@ for details of this object

<a name="parserConfiguration"></a>.parserConfiguration(obj)
------------
`parserConfiguration()` allows you to configure yargs. See [yargs-parser's configuration](https://github.com/yargs/yargs-parser#configuration) for
settings specific to `yargs-parser`.
`parserConfiguration()` allows you to configure advanced yargs features.

`obj` accepts the following configuration options:

* `sort-commands` when set to `true` (boolean) will sort the commands added, the default is `false`.

For additional configuration options, see [yargs-parser's configuration](https://github.com/yargs/yargs-parser#configuration).

<a name="pkg-conf"></a>
.pkgConf(key, [cwd])
Expand Down
4 changes: 4 additions & 0 deletions lib/usage.js
Expand Up @@ -204,6 +204,10 @@ module.exports = function usage (yargs, y18n) {
const context = yargs.getContext()
const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''

if (yargs.getParserConfiguration()['sort-commands'] === true) {
commands = commands.sort((a, b) => a[0].localeCompare(b[0]))
}

commands.forEach((command) => {
const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}` // drop $0 from default commands.
ui.span(
Expand Down
26 changes: 26 additions & 0 deletions test/usage.js
Expand Up @@ -2599,6 +2599,32 @@ describe('usage tests', () => {
])
})

it('should display top-level help with sorting with no command given if sorting enabled', () => {
const r = checkUsage(() => yargs('--help')
.command(['list [pattern]', 'ls', '*'], 'List key-value pairs for pattern', {}, noop)
.command('get <key>', 'Get value for key', {}, noop)
.command('set <key> [value]', 'Set value for key', {}, noop)
.parserConfiguration({'sort-commands': true})
.parse()
)

r.logs[0].split('\n').should.deep.equal([
'usage [pattern]',
'',
'List key-value pairs for pattern',
'',
'Commands:',
' usage get <key> Get value for key',
' usage list [pattern] List key-value pairs for pattern',
' [default] [aliases: ls]',
' usage set <key> [value] Set value for key',
'',
'Options:',
' --help Show help [boolean]',
' --version Show version number [boolean]'
])
})

it('should display default command as ./$0 if it has no aliases', () => {
const r = checkUsage(() => yargs('--help')
.command('* [pattern]', 'List key-value pairs for pattern', {}, noop)
Expand Down

0 comments on commit 6916ce9

Please sign in to comment.