Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change strategy of output. #3

Merged
merged 3 commits into from
May 31, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 70 additions & 23 deletions Sources/ShellOut.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import Foundation
* - parameter command: The command to run
* - parameter arguments: The arguments to pass to the command
* - parameter path: The path to execute the commands at (defaults to current folder)
* - parameter outputHandle: The `FileHandle` where STDOUT should be redirected to
* - parameter errorHandle: The `FileHandle` where STDERR should be redirected to
*
* - returns: The output of running the command
* - throws: `ShellOutError` in case the command couldn't be performed, or it returned an error
Expand All @@ -23,81 +25,126 @@ import Foundation
*/
@discardableResult public func shellOut(to command: String,
arguments: [String] = [],
at path: String = ".") throws -> String {
at path: String = ".",
outputHandle: FileHandle? = nil, errorHandle: FileHandle? = nil) throws -> String {
let process = Process()
let command = "cd \"\(path)\" && \(command) \(arguments.joined(separator: " "))"
return try process.launchBash(with: command)
return try process.launchBash(with: command, outputHandle: outputHandle, errorHandle: errorHandle)
}

/**
* Run a series of shell commands using Bash
*
* - parameter commands: The commands to run
* - parameter path: The path to execute the commands at (defaults to current folder)
* - parameter outputHandle: The `FileHandle` where STDOUT should be redirected to
* - parameter errorHandle: The `FileHandle` where STDERR should be redirected to
*
* - returns: The output of running the command
* - throws: `ShellOutError` in case the command couldn't be performed, or it returned an error
*
* Use this function to "shell out" in a Swift script or command line tool
* For example: `shellOut(to: ["mkdir NewFolder", "cd NewFolder"], at: "~/CurrentFolder")`
*/
@discardableResult public func shellOut(to commands: [String], at path: String = ".") throws -> String {
@discardableResult public func shellOut(to commands: [String], at path: String = ".", outputHandle: FileHandle? = nil, errorHandle: FileHandle? = nil) throws -> String {
let command = commands.joined(separator: " && ")
return try shellOut(to: command, at: path)
return try shellOut(to: command, at: path, outputHandle: outputHandle, errorHandle: errorHandle)
}

// Error type thrown by the `shellOut()` function, in case the given command failed
public struct ShellOutError: Swift.Error {
/// The buffer data retuned by `STDERR`.
public let stderr: Data
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this needed, since we already have message and output?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would imagine some output should just be some bytes and are not intended to be represented as string.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But string is so much easier to consume, especially since this package is mostly targeted towards scripting, where convenience is key.

/// The buffer data retuned by `STOUT`.
public let stdout: Data
/// The termination status of the command.
public let terminationStatus: Int32
/// The error message that was returned through `STDERR`
public let message: String
public var message: String {
return stderr.shellOutput() ?? ""
}
/// Any output that was put in `STDOUT` despite the error being thrown
public let output: String
public var output: String {
return stdout.shellOutput() ?? ""
}
}

// MARK: - Private

private extension Process {
@discardableResult func launchBash(with command: String) throws -> String {

private func closeHandle(_ handle: FileHandle?) {
if let handle = handle {
handle.closeFile()
}
}

@discardableResult func launchBash(with command: String, outputHandle: FileHandle? = nil, errorHandle: FileHandle? = nil) throws -> Data {
launchPath = "/bin/bash"
arguments = ["-c", command]

var stdoutData = Data()
var stderrData = Data()

let stdoutHandler: (FileHandle) -> Void = { handler in
let data = handler.availableData
stdoutData.append(data)
if let handler = outputHandle {
handler.write(data)
}
}

let stderrHandler: (FileHandle) -> Void = { handler in
let data = handler.availableData
stderrData.append(data)
if let handler = errorHandle {
handler.write(data)
}
}

let outputPipe = Pipe()
standardOutput = outputPipe
outputPipe.fileHandleForReading.readabilityHandler = stdoutHandler

let errorPipe = Pipe()
standardError = errorPipe
errorPipe.fileHandleForReading.readabilityHandler = stderrHandler

launch()

let output = outputPipe.read() ?? ""
let error = errorPipe.read()

waitUntilExit()

if let error = error {
if !error.isEmpty {
throw ShellOutError(message: error, output: output)
}
// This is needed to close the file handle at the end. See: `Pipe` documentation
closeHandle(outputHandle)
closeHandle(errorHandle)

if terminationStatus != 0 {
throw ShellOutError(stderr: stderrData, stdout: stdoutData, terminationStatus: terminationStatus)
}

return output
FileHandle.standardError.readabilityHandler = nil
FileHandle.standardOutput.readabilityHandler = nil

return stdoutData
}
}

private extension Pipe {
func read() -> String? {
let data = fileHandleForReading.readDataToEndOfFile()
@discardableResult func launchBash(with command: String, outputHandle: FileHandle? = nil, errorHandle: FileHandle? = nil) throws -> String {
return try launchBash(with: command, outputHandle: outputHandle, errorHandle: errorHandle).shellOutput() ?? ""
}

}

guard let output = String(data: data, encoding: .utf8) else {
private extension Data {
func shellOutput() -> String? {
guard let output = String(data: self, encoding: .utf8) else {
return nil
}

guard !output.hasSuffix("\n") else {
let outputLength = output.distance(from: output.startIndex, to: output.endIndex)
return output.substring(to: output.index(output.startIndex, offsetBy: outputLength - 1))
}

return output

}
}

3 changes: 2 additions & 1 deletion Tests/ShellOutTests/ShellOutTests+Linux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ extension ShellOutTests {
("testWithoutArguments", testWithoutArguments),
("testWithArguments", testWithArguments),
("testWithInlineArguments", testWithInlineArguments),
("testThrowingError", testThrowingError)
("testThrowingError", testThrowingError),
("testRedirection", testRedirection)
]
}
#endif
23 changes: 23 additions & 0 deletions Tests/ShellOutTests/ShellOutTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,31 @@ class ShellOutTests: XCTestCase {
} catch let error as ShellOutError {
XCTAssertTrue(error.message.contains("notADirectory"))
XCTAssertTrue(error.output.isEmpty)
XCTAssertTrue(error.terminationStatus != 0)
} catch {
XCTFail("Invalid error type: \(error)")
}
}

func testRedirection() {

let stdout = Pipe()
do {
try shellOut(to: "echo", arguments: ["Hello"], outputHandle: stdout.fileHandleForWriting)
let data = stdout.fileHandleForReading.readDataToEndOfFile()
XCTAssertTrue(data.count > 0)
} catch {
XCTFail("Invalid error type: \(error)")
}

let stderr = Pipe()
do {
try shellOut(to: "echo", arguments: ["Hello", ">>/dev/stderr"], errorHandle: stderr.fileHandleForWriting)
let data = stderr.fileHandleForReading.readDataToEndOfFile()
XCTAssertTrue(data.count > 0)
} catch {
XCTFail("Invalid error type: \(error)")
}
}

}