apple / apple/swift-argument-parser

Allow parsing of -Dkey=value style options

Open
#515 0 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Swift
Stars
3.8k
Forks
411
Avg merge
7d 13h
Merged PRs (30d)
17

Description

If I haven't overlooked something, it's currently not possible to define options in the style of make/gcc/clang definitions.

In theory it should be possible to define it like this:

```swift
@main
struct Foo: ParsableCommand {
@Option(name: .customShort("D", allowingJoined: true), parsing: .singleValue)
var defines: [String] = []

public func run() throws {
print(defines)
}
}
```

This works fine for calling the executable e.g. like so:

```
$ foo -Dbar -Dbaz
["bar", "baz"]
```

However, when the value of the option contains an =, this doesn't work anymore:

```
$ foo -Dbar=baz
Error: Unknown option '-Dbar'
```

I'd guess that after seeing an equals sign the single "D" isn't considered anymore. It would be great, if that behaviour could be changed.

Of course, it would be possible to go an extra step and fully parse such key-value pairs into a dictionary. I could imagine a syntax like this:

```swift
@main
struct Foo: ParsableCommand {
@Option(name: [.customShort("D", allowingJoined: true), .customLong("define")])
var defines: [String: String] = [:]

public func run() throws {
print(defines)
}
}
```

Where `Option` gets a new specialized init for `Value == [String: Element]` that then would work like that:

```
$ foo -Dbar=1 -D baz=2 --define qux=3
["bar": 1, "baz": 2, "qux": 3]
```

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the documented command-line cases for `-Dbar`, `-Dbar=baz`, separated `-D baz=2`, and `--define qux=3`, then trace the option parsing entry point that handles joined short-option values. Done means values containing `=` are accepted without an unknown-option error, while the existing joined and separated forms continue to work.

Written by the indexing model from the issue text.

Assessment

Tech stack
swift
Domain
cli
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.