From 6916ce9a548c4f0ccd80740a0d85c6e7c567ff84 Mon Sep 17 00:00:00 2001 From: Trevor Linton Date: Fri, 1 Feb 2019 11:54:56 -0700 Subject: [PATCH] feat: adds config option for sorting command output (#1256) --- docs/api.md | 9 +++++++-- lib/usage.js | 4 ++++ test/usage.js | 26 ++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/docs/api.md b/docs/api.md index d20aa0efd..e229d56da 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1151,8 +1151,13 @@ for details of this object .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). .pkgConf(key, [cwd]) diff --git a/lib/usage.js b/lib/usage.js index 9be8a995b..f6daeed5d 100644 --- a/lib/usage.js +++ b/lib/usage.js @@ -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( diff --git a/test/usage.js b/test/usage.js index cfa828f91..022825cbe 100644 --- a/test/usage.js +++ b/test/usage.js @@ -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 ', 'Get value for key', {}, noop) + .command('set [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 Get value for key', + ' usage list [pattern] List key-value pairs for pattern', + ' [default] [aliases: ls]', + ' usage set [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)