swift-argument-parser icon indicating copy to clipboard operation
swift-argument-parser copied to clipboard

Ability for an input to work as both a @Flag and an @Option.

Open daltonclaybrook opened this issue 4 years ago • 2 comments

I'd like the ability for an input to be able to work as both a Flag and an Option in my CLI. For example, I would want both of the following examples to be possible:

$ example --build
# and
$ example --build Foo Bar

The first case would parse to build: [] and the second case to build: ["Foo", "Bar"]. I tried making this work in two ways. First I tried making an @Option with a type of [String]? = nil and using a custom transform closure. My assumption was that passing --build without a value would pass an empty string to the transform closure. Instead, the CLI emits the following error when running:

Error: Missing value for '--build <build>'

The second strategy I tried was creating two separate fields, making one a @Flag and one an @Option, and giving them the same name. This time, I got an assertion failure:

ArgumentParser/ParsableArguments.swift:243: Fatal error: Validation failed for `Example`:
- Multiple (2) `Option` or `Flag` arguments are named "--build".

The first strategy—the one that uses only a single @Option field—seems the most ergonomic to me. I could also picture using a new initializer parameter to @Option e.g. allowsMissingValue: Bool, etc. My apologies if this is already possible and I just didn't dig hard enough.

daltonclaybrook avatar Jul 09 '21 21:07 daltonclaybrook

It looks like this is the same issue as #307 and there's a PR up for it at #317, though I think @natecook1000 is still making up his mind about whether this feature is safe to add or not

kylemacomber avatar Jul 13 '21 17:07 kylemacomber

@kylemacomber Ah, got it! Feel free to close this issue if you think it is a duplicate.

daltonclaybrook avatar Jul 13 '21 17:07 daltonclaybrook