Skip to content

Commit 003ad6f

Browse files
authoredMar 19, 2024··
fix: show options when required flag or arg is not given a value (#1017)
1 parent 1d0f9e9 commit 003ad6f

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed
 

‎src/parser/errors.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,12 @@ export class RequiredArgsError extends CLIParseError {
5858
let message = `Missing ${args.length} required arg${args.length === 1 ? '' : 's'}`
5959
const namedArgs = args.filter((a) => a.name)
6060
if (namedArgs.length > 0) {
61-
const list = renderList(namedArgs.map((a) => [a.name, a.description] as [string, string]))
61+
const list = renderList(
62+
namedArgs.map((a) => {
63+
const description = a.options ? `(${a.options.join('|')}) ${a.description}` : a.description
64+
return [a.name, description]
65+
}),
66+
)
6267
message += `:\n${list}`
6368
}
6469

‎src/parser/parse.ts

+4
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,10 @@ export class Parser<
188188

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

‎test/parser/parse.test.ts

+19-2
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,23 @@ describe('parse', () => {
146146
}
147147
})
148148

149+
it('throws error when no value provided to required flag with options', async () => {
150+
try {
151+
await parse(['--myflag', '--second', 'value'], {
152+
flags: {
153+
myflag: Flags.string({
154+
required: true,
155+
options: ['a', 'b'],
156+
}),
157+
second: Flags.string(),
158+
},
159+
})
160+
assert.fail('should have thrown')
161+
} catch (error) {
162+
expect((error as CLIError).message).to.include('Flag --myflag expects one of these values: a, b')
163+
}
164+
})
165+
149166
it('throws error when no value provided to required flag before a short char flag', async () => {
150167
try {
151168
await parse(['--myflag', '-s', 'value'], {
@@ -270,7 +287,7 @@ describe('parse', () => {
270287
await parse(['arg1'], {
271288
args: {
272289
arg1: Args.string({required: true}),
273-
arg2: Args.string({required: true, description: 'arg2 desc'}),
290+
arg2: Args.string({required: true, description: 'arg2 desc', options: ['a', 'b']}),
274291
arg3: Args.string({required: true, description: 'arg3 desc'}),
275292
},
276293
})
@@ -279,7 +296,7 @@ describe('parse', () => {
279296
}
280297

281298
expect(message).to.include(`Missing 2 required args:
282-
arg2 arg2 desc
299+
arg2 (a|b) arg2 desc
283300
arg3 arg3 desc
284301
See more help with --help`)
285302
})

0 commit comments

Comments
 (0)
Please sign in to comment.