Skip to content

Commit

Permalink
Support paths relative to the user’s home directory
Browse files Browse the repository at this point in the history
This patch fixes a bug that would cause shelling out at a path containing
a tilde to fail. The reason was that ShellOut was wrapping all paths in
quotes, in order to escape spaces. With this, spaces are properly escaped
instead.
  • Loading branch information
JohnSundell committed Nov 4, 2017
1 parent 82ce581 commit 900c6ef
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Sources/ShellOut.swift
Expand Up @@ -31,7 +31,7 @@ import Foundation
outputHandle: FileHandle? = nil,
errorHandle: FileHandle? = nil) throws -> String {
let process = Process()
let command = "cd \"\(path)\" && \(command) \(arguments.joined(separator: " "))"
let command = "cd \(path.escapingSpaces) && \(command) \(arguments.joined(separator: " "))"
return try process.launchBash(with: command, outputHandle: outputHandle, errorHandle: errorHandle)
}

Expand Down Expand Up @@ -418,6 +418,10 @@ private extension Data {
}

private extension String {
var escapingSpaces: String {
return replacingOccurrences(of: " ", with: "\\ ")
}

func appending(argument: String) -> String {
return "\(self) \"\(argument)\""
}
Expand Down
13 changes: 13 additions & 0 deletions Tests/ShellOutTests/ShellOutTests.swift
Expand Up @@ -32,6 +32,19 @@ class ShellOutTests: XCTestCase {
XCTAssertEqual(textFileContent, "Hello")
}

func testSingleCommandAtPathContainingSpace() throws {
try shellOut(to: "mkdir -p \"ShellOut Test Folder\"", at: NSTemporaryDirectory())
try shellOut(to: "echo \"Hello\" > File", at: NSTemporaryDirectory() + "ShellOut Test Folder")

let output = try shellOut(to: "cat \(NSTemporaryDirectory())ShellOut\\ Test\\ Folder/File")
XCTAssertEqual(output, "Hello")
}

func testSingleCommandAtPathContainingTilde() throws {
let homeContents = try shellOut(to: "ls", at: "~")
XCTAssertFalse(homeContents.isEmpty)
}

func testSeriesOfCommands() throws {
let echo = try shellOut(to: ["echo \"Hello\"", "echo \"world\""])
XCTAssertEqual(echo, "Hello\nworld")
Expand Down

0 comments on commit 900c6ef

Please sign in to comment.