Skip to content

Commit

Permalink
Parse parameters without values as booleans with a value of true
Browse files Browse the repository at this point in the history
  • Loading branch information
djbe committed Feb 14, 2017
1 parent 5159be2 commit dd774e2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
17 changes: 11 additions & 6 deletions Sources/Parameters.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,25 @@
import Foundation

public enum ParametersError: Error {
case invalidSyntax(value: String)
case invalidKey(key: String, value: String)
case invalidSyntax(value: Any)
case invalidKey(key: String, value: Any)
case invalidStructure(key: String, oldValue: Any, newValue: Any)
}

public enum Parameters {
typealias Parameter = (key: String, value: String)
typealias Parameter = (key: String, value: Any)
public typealias StringDict = [String: Any]

public static func parse(items: [String]) throws -> StringDict {
let parameters: [Parameter] = try items.map { item in
let parts = item.components(separatedBy: "=")
guard parts.count == 2 else { throw ParametersError.invalidSyntax(value: item) }
return (key: parts[0], value: parts[1])
if parts.count == 2 {
return (key: parts[0], value: parts[1])
} else if let part = parts.first, parts.count == 1 && validate(key: part) {
return (key: part, value: true)
} else {
throw ParametersError.invalidSyntax(value: item)

This comment has been minimized.

Copy link
@AliSoftware

AliSoftware Feb 14, 2017

Contributor

That means that --param x=y=z is invalid, so there's no way to give x the value y=z?

}
}

return try parameters.reduce(StringDict()) {
Expand All @@ -38,7 +43,7 @@ public enum Parameters {

// no sub keys, may need to convert to array if repeat key if possible
if parts.count == 1 {
if let current = result[key] as? [String] {
if let current = result[key] as? [Any] {
result[key] = current + [parameter.value]
} else if let current = result[key] as? String {
result[key] = [current, parameter.value]
Expand Down
5 changes: 3 additions & 2 deletions Tests/StencilSwiftKitTests/ParametersTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ import StencilSwiftKit

class ParametersTests: XCTestCase {
func testBasic() {
let items = ["a=1", "b=hello"]
let items = ["a=1", "b=hello", "c"]
let result = try! Parameters.parse(items: items)

XCTAssertEqual(result.count, 2, "2 parameters should have been parsed")
XCTAssertEqual(result.count, 3, "3 parameters should have been parsed")
XCTAssertEqual(result["a"] as? String, "1")
XCTAssertEqual(result["b"] as? String, "hello")
XCTAssertEqual(result["c"] as? Bool, true)
}

func testStructured() {
Expand Down

0 comments on commit dd774e2

Please sign in to comment.