From 0c731073780b270e8be66844dfd155928c363f01 Mon Sep 17 00:00:00 2001 From: Tamas Lustyik Date: Wed, 10 Oct 2018 21:18:01 +0200 Subject: [PATCH 1/2] Watch bare double dash (--) and prevent subsequent tokens from getting parsed as options --- Sources/Commander/ArgumentParser.swift | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Sources/Commander/ArgumentParser.swift b/Sources/Commander/ArgumentParser.swift index e3453d4..432368a 100644 --- a/Sources/Commander/ArgumentParser.swift +++ b/Sources/Commander/ArgumentParser.swift @@ -58,7 +58,19 @@ public final class ArgumentParser : ArgumentConvertible, CustomStringConvertible /// Initialises the ArgumentParser with an array of arguments public init(arguments: [String]) { - self.arguments = arguments.map { argument in + let splitArguments = arguments.split(maxSplits: 1, omittingEmptySubsequences: false) { $0 == "--" } + + let unfixedArguments: [String] + let fixedArguments: [String] + if splitArguments.count == 2, let prefix = splitArguments.first, let suffix = splitArguments.last { + unfixedArguments = Array(prefix) + fixedArguments = Array(suffix) + } else { + unfixedArguments = arguments + fixedArguments = [] + } + + self.arguments = unfixedArguments.map { argument in if argument.first == "-" { let flags = argument[argument.index(after: argument.startIndex).. Date: Wed, 10 Oct 2018 21:41:10 +0200 Subject: [PATCH 2/2] Added some tests --- Tests/CommanderTests/ArgumentParserSpec.swift | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Tests/CommanderTests/ArgumentParserSpec.swift b/Tests/CommanderTests/ArgumentParserSpec.swift index e0916ee..f06de55 100644 --- a/Tests/CommanderTests/ArgumentParserSpec.swift +++ b/Tests/CommanderTests/ArgumentParserSpec.swift @@ -119,5 +119,30 @@ public func testArgumentParser() { try expect(values.count) == 0 } } + $0.describe("positional arguments") { + $0.before { + parser = ArgumentParser(arguments: ["-a", "value1", "--", "-b", "value2"]) + } + $0.it("should not count double dash into the arguments") { + try expect(parser.remainder.count) == 4 + _ = try parser.shiftValue(for: "a" as ArgumentParser.Flag) + try expect(parser.remainder.count) == 2 + } + $0.it("should not parse parameters as flags after the double dash") { + try expect(parser.hasFlag("a" as ArgumentParser.Flag)).to.beTrue() + try expect(parser.hasFlag("b" as ArgumentParser.Flag)).to.beFalse() + + _ = try parser.shiftValue(for: "a" as ArgumentParser.Flag) + let value = try parser.shiftValue(for: "b" as ArgumentParser.Flag) + try expect(value).to.beNil() + } + $0.it("should return parameters after the double dash as arguments") { + _ = try parser.shiftValue(for: "a" as ArgumentParser.Flag) + let value1 = parser.shift() + let value2 = parser.shift() + try expect(value1) == "-b" + try expect(value2) == "value2" + } + } } }