From 6d588bfe29fbc33cde914f79752c3d0a0f80c9bc Mon Sep 17 00:00:00 2001 From: Kare Morstol Date: Thu, 23 Oct 2014 01:41:53 +0200 Subject: [PATCH] Add "parameters" function for turning a sequence into valid parameters for a shell command, properly quoted. --- SwiftShell/Command.swift | 4 ++++ SwiftShellTests/Command_Tests.swift | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/SwiftShell/Command.swift b/SwiftShell/Command.swift index a13e35d..ed0190a 100644 --- a/SwiftShell/Command.swift +++ b/SwiftShell/Command.swift @@ -86,3 +86,7 @@ public func $ (shellcommand: String) -> String { return output.fileHandleForReading.read().trim() } +/** Turn a sequence into valid parameters for a shell command, properly quoted */ +public func parameters (sequence: S) -> String { + return sequence |> map {"\"\(toString($0))\""} |> join(" ") +} diff --git a/SwiftShellTests/Command_Tests.swift b/SwiftShellTests/Command_Tests.swift index 3cbe914..1ad9831 100644 --- a/SwiftShellTests/Command_Tests.swift +++ b/SwiftShellTests/Command_Tests.swift @@ -32,4 +32,20 @@ class Command_Tests: XCTestCase { let result = stream("line 1\nline 2\nline 3") |> SwiftShell.run("grep " + $("echo 2")) XCTAssertEqual( result.read(), "line 2\n") } + + func testParametersFromSequenceOfStrings () { + XCTAssertEqual( parameters(["one", "two", "three"]), "\"one\" \"two\" \"three\"" ) + } + + func testParametersFromSequenceOfStreams () { + var (writable, readable) = streams() + + let result = SequenceOf([stream("one"), stream("two"), stream("three")].generate()) |> parameters + + XCTAssertEqual( result, "\"one\" \"two\" \"three\"" ) + } + + func testParametersFromSequenceOfNumbers () { + XCTAssertEqual( parameters([1, 2, 3]), "\"1\" \"2\" \"3\"" ) + } }