Skip to content

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

Open
@daltonclaybrook

Description

@daltonclaybrook

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions