Skip to content

Allow single, attached value with .upToNextOption #610

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion Sources/ArgumentParser/Parsing/ArgumentSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -327,17 +327,20 @@ struct LenientParser {

case .upToNextOption:
// Use an attached value if it exists...
var foundAttachedValue = false
if let value = parsed.value {
// This was `--foo=bar` style:
try update(origin, parsed.name, value, &result)
usedOrigins.formUnion(origin)
foundAttachedValue = true
} else if argument.allowsJoinedValue,
let (origin2, value) = inputArguments.extractJoinedElement(at: originElement) {
// Found a joined argument
let origins = origin.inserting(origin2)
try update(origins, parsed.name, String(value), &result)
usedOrigins.formUnion(origins)
inputArguments.removeAll(in: usedOrigins)
foundAttachedValue = true
}

// Clear out the initial origin first, since it can include
Expand All @@ -350,7 +353,13 @@ struct LenientParser {
guard let first = inputArguments.elements.first,
first.isValue
else {
throw ParserError.missingValueForOption(origin, parsed.name)
// No independent values to be found, which is an error if there was
// no `--foo=bar`-style value already found.
if foundAttachedValue {
break
} else {
throw ParserError.missingValueForOption(origin, parsed.name)
}
}

// ...and then consume the arguments until hitting an option
Expand Down
18 changes: 18 additions & 0 deletions Tests/ArgumentParserEndToEndTests/RepeatingEndToEndTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,24 @@ extension RepeatingEndToEndTests {
XCTAssertEqual(qux.names, ["one", "two"])
XCTAssertNil(qux.extra)
}

AssertParse(Qux.self, ["--verbose", "--names=one"]) { qux in
XCTAssertTrue(qux.verbose)
XCTAssertEqual(qux.names, ["one"])
XCTAssertNil(qux.extra)
}

AssertParse(Qux.self, ["--verbose", "--names=one", "two"]) { qux in
XCTAssertTrue(qux.verbose)
XCTAssertEqual(qux.names, ["one", "two"])
XCTAssertNil(qux.extra)
}

AssertParse(Qux.self, ["--names=one", "--verbose", "two"]) { qux in
XCTAssertTrue(qux.verbose)
XCTAssertEqual(qux.names, ["one"])
XCTAssertEqual(qux.extra, "two")
}
}

func testParsing_repeatingStringUpToNext_Fails() throws {
Expand Down