Skip to content

Commit

Permalink
List valid options in error messages for enum array argument
Browse files Browse the repository at this point in the history
When an array of argument values fails to parse, no custom error message is
provided, and a list of valid candidate values is available, include the
list as part of the error message.

Addresses apple#401.
  • Loading branch information
konomae committed May 13, 2022
1 parent 060d523 commit 4077519
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 16 deletions.
7 changes: 6 additions & 1 deletion Sources/ArgumentParser/Parsable Properties/Argument.swift
Expand Up @@ -338,7 +338,12 @@ extension Argument {
helpDefaultValue = nil
}

let help = ArgumentDefinition.Help(options: [.isOptional, .isRepeating], help: help, key: key)
let help = ArgumentDefinition.Help(
allValues: Element.allValueStrings,
options: [.isOptional, .isRepeating],
help: help,
key: key
)
var arg = ArgumentDefinition(
kind: .positional,
help: help,
Expand Down
53 changes: 38 additions & 15 deletions Tests/ArgumentParserUnitTests/ErrorMessageTests.swift
Expand Up @@ -64,28 +64,39 @@ extension ErrorMessageTests {
}
}

fileprivate struct Foo: ParsableArguments {
enum Format: String, Equatable, Decodable, ExpressibleByArgument, CaseIterable {
case text
case json
case csv
}
fileprivate enum Format: String, Equatable, Decodable, ExpressibleByArgument, CaseIterable {
case text
case json
case csv
}

enum Name: String, Equatable, Decodable, ExpressibleByArgument, CaseIterable {
case bruce
case clint
case hulk
case natasha
case steve
case thor
case tony
}
fileprivate enum Name: String, Equatable, Decodable, ExpressibleByArgument, CaseIterable {
case bruce
case clint
case hulk
case natasha
case steve
case thor
case tony
}

fileprivate struct Foo: ParsableArguments {
@Option(name: [.short, .long])
var format: Format
@Option(name: [.short, .long])
var name: Name?
}

fileprivate struct EnumWithFewCasesArrayArgument: ParsableArguments {
@Argument
var formats: [Format]
}

fileprivate struct EnumWithManyCasesArrayArgument: ParsableArguments {
@Argument
var names: [Name]
}

extension ErrorMessageTests {
func testWrongEnumValue() {
AssertErrorMessage(Foo.self, ["--format", "png"], "The value 'png' is invalid for '--format <format>'. Please provide one of 'text', 'json' or 'csv'.")
Expand All @@ -112,6 +123,18 @@ extension ErrorMessageTests {
- thor
- tony
""")
AssertErrorMessage(EnumWithFewCasesArrayArgument.self, ["png"], "The value 'png' is invalid for '<formats>'. Please provide one of 'text', 'json' or 'csv'.")
AssertErrorMessage(EnumWithManyCasesArrayArgument.self, ["loki"],
"""
The value 'loki' is invalid for '<names>'. Please provide one of the following:
- bruce
- clint
- hulk
- natasha
- steve
- thor
- tony
""")
}
}

Expand Down

0 comments on commit 4077519

Please sign in to comment.