From 560b628e2b7712553fc4cf9a023b46a969256a27 Mon Sep 17 00:00:00 2001 From: Mike Donnalley Date: Thu, 7 Dec 2023 11:24:48 -0700 Subject: [PATCH] feat: add flagSortOrder to help options --- src/help/command.ts | 20 ++++++++++-------- src/interfaces/help.ts | 7 +++++++ test/help/format-command.test.ts | 35 ++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 9 deletions(-) diff --git a/src/help/command.ts b/src/help/command.ts index 4e2c5f1f6..725ec6fa8 100644 --- a/src/help/command.ts +++ b/src/help/command.ts @@ -218,15 +218,17 @@ export class CommandHelp extends HelpFormatter { generate(): string { const cmd = this.command - const flags = sortBy( - Object.entries(cmd.flags || {}) - .filter(([, v]) => !v.hidden) - .map(([k, v]) => { - v.name = k - return v - }), - (f) => [!f.char, f.char, f.name], - ) + const unsortedFlags = Object.entries(cmd.flags || {}) + .filter(([, v]) => !v.hidden) + .map(([k, v]) => { + v.name = k + return v + }) + + const flags = + this.opts.flagSortOrder === 'alphabetical' || !this.opts.flagSortOrder + ? sortBy(unsortedFlags, (f) => [!f.char, f.char, f.name]) + : unsortedFlags const args = Object.values(ensureArgObject(cmd.args)).filter((a) => !a.hidden) const output = compact( diff --git a/src/interfaces/help.ts b/src/interfaces/help.ts index f0ca5c0e7..74c510297 100644 --- a/src/interfaces/help.ts +++ b/src/interfaces/help.ts @@ -4,6 +4,13 @@ export interface HelpOptions { * Use docopts as the usage. Defaults to true. */ docopts?: boolean + /** + * Order in which to sort flags in help output. Defaults to `alphabetical`. + * + * `alphabetical`: Sort flags alphabetically. All flags with short characters will come first. + * `none`: Do not sort flags. They will appear in the order in which they were defined on the command. + */ + flagSortOrder?: 'alphabetical' | 'none' /** * If true, hide command aliases from the root help output. Defaults to false. */ diff --git a/test/help/format-command.test.ts b/test/help/format-command.test.ts index 730dea92e..72a6c6952 100644 --- a/test/help/format-command.test.ts +++ b/test/help/format-command.test.ts @@ -732,3 +732,38 @@ EXAMPLES }) }) }) + +describe.only('formatCommand with `none` flagSortOrder', () => { + let config: Config + let help: TestHelp + + before(async () => { + config = await Config.load(process.cwd()) + }) + + beforeEach(() => { + help = new TestHelp(config, {flagSortOrder: 'none'}) + }) + + it('should not sort flags', async () => { + const cmd = await makeLoadable( + makeCommandClass({ + id: 'apps:create', + flags: { + cFlag: flags.string({char: 'c'}), + aFlag: flags.string({char: 'a'}), + bFlag: flags.string({char: 'b'}), + }, + }), + ) + + const output = help.formatCommand(cmd) + expect(output).to.equal(`USAGE + $ oclif apps:create [-c ] [-a ] [-b ] + +FLAGS + -c, --cFlag= + -a, --aFlag= + -b, --bFlag=`) + }) +})