Skip to content

Commit

Permalink
fix: show options when required flag or arg is not given a value (#1017)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonnalley authored Mar 19, 2024
1 parent 1d0f9e9 commit 003ad6f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/parser/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,12 @@ export class RequiredArgsError extends CLIParseError {
let message = `Missing ${args.length} required arg${args.length === 1 ? '' : 's'}`
const namedArgs = args.filter((a) => a.name)
if (namedArgs.length > 0) {
const list = renderList(namedArgs.map((a) => [a.name, a.description] as [string, string]))
const list = renderList(
namedArgs.map((a) => {
const description = a.options ? `(${a.options.join('|')}) ${a.description}` : a.description
return [a.name, description]
}),
)
message += `:\n${list}`
}

Expand Down
4 changes: 4 additions & 0 deletions src/parser/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,10 @@ export class Parser<

// if the value ends up being one of the command's flags, the user didn't provide an input
if (typeof input !== 'string' || this.findFlag(input).name) {
if (flag.options) {
throw new CLIError(`Flag --${name} expects one of these values: ${flag.options.join(', ')}`)
}

throw new CLIError(`Flag --${name} expects a value`)
}

Expand Down
21 changes: 19 additions & 2 deletions test/parser/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,23 @@ describe('parse', () => {
}
})

it('throws error when no value provided to required flag with options', async () => {
try {
await parse(['--myflag', '--second', 'value'], {
flags: {
myflag: Flags.string({
required: true,
options: ['a', 'b'],
}),
second: Flags.string(),
},
})
assert.fail('should have thrown')
} catch (error) {
expect((error as CLIError).message).to.include('Flag --myflag expects one of these values: a, b')
}
})

it('throws error when no value provided to required flag before a short char flag', async () => {
try {
await parse(['--myflag', '-s', 'value'], {
Expand Down Expand Up @@ -270,7 +287,7 @@ describe('parse', () => {
await parse(['arg1'], {
args: {
arg1: Args.string({required: true}),
arg2: Args.string({required: true, description: 'arg2 desc'}),
arg2: Args.string({required: true, description: 'arg2 desc', options: ['a', 'b']}),
arg3: Args.string({required: true, description: 'arg3 desc'}),
},
})
Expand All @@ -279,7 +296,7 @@ describe('parse', () => {
}

expect(message).to.include(`Missing 2 required args:
arg2 arg2 desc
arg2 (a|b) arg2 desc
arg3 arg3 desc
See more help with --help`)
})
Expand Down

0 comments on commit 003ad6f

Please sign in to comment.