Skip to content

Commit

Permalink
feat: add flagSortOrder to help options
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonnalley committed Dec 7, 2023
1 parent 379e940 commit 560b628
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/help/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
7 changes: 7 additions & 0 deletions src/interfaces/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
35 changes: 35 additions & 0 deletions test/help/format-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <value>] [-a <value>] [-b <value>]
FLAGS
-c, --cFlag=<value>
-a, --aFlag=<value>
-b, --bFlag=<value>`)
})
})

0 comments on commit 560b628

Please sign in to comment.