Skip to content

Commit

Permalink
Allow single, attached value with .upToNextOption (apple#610)
Browse files Browse the repository at this point in the history
Fixes an issue where a single attached value triggered an error on
`.upToNextOption` options.

Fixes apple#609.
  • Loading branch information
natecook1000 authored Dec 13, 2023
1 parent 14cba5d commit a3d53a7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
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

0 comments on commit a3d53a7

Please sign in to comment.