From de708331a80daf5b43d5d4f8c437ca74c4d56809 Mon Sep 17 00:00:00 2001 From: Kare Morstol Date: Thu, 3 Sep 2015 17:45:28 +0200 Subject: [PATCH] Add 'ShellError', which may be thrown from completed shell commands. --- SwiftShell/Command.swift | 22 +++++++++++++++++++++- SwiftShellTests/Command_Tests.swift | 6 ++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/SwiftShell/Command.swift b/SwiftShell/Command.swift index 1824347..8e505e1 100644 --- a/SwiftShell/Command.swift +++ b/SwiftShell/Command.swift @@ -42,6 +42,7 @@ extension ShellContextType { } } + extension ShellContextType { private func outputFromRun (task: NSTask) -> String { @@ -82,6 +83,22 @@ extension ShellContextType { } } + +/** Error type for completed shell commands. */ +public enum ShellError: ErrorType, Equatable { + + /** Exit code was not zero. */ + case ReturnedErrorCode (errorcode: Int32) +} + +public func == (e1: ShellError, e2: ShellError) -> Bool { + switch (e1, e2) { + case (.ReturnedErrorCode(let c1), .ReturnedErrorCode(let c2)): + return c1 == c2 + } +} + +/** Output from the 'runAsync' methods. */ public struct AsyncShellTask { public let stdout: NSFileHandle public let stderror: NSFileHandle @@ -104,10 +121,13 @@ public struct AsyncShellTask { /** Wait for this shell task to finish. - - throws: a TaskError if the return code is anything but 0. + - throws: a ShellError if the return code is anything but 0. */ public func finish() throws { task.waitUntilExit() + if task.terminationStatus != 0 { + throw ShellError.ReturnedErrorCode(errorcode: task.terminationStatus) + } } } diff --git a/SwiftShellTests/Command_Tests.swift b/SwiftShellTests/Command_Tests.swift index aea1531..6115c32 100644 --- a/SwiftShellTests/Command_Tests.swift +++ b/SwiftShellTests/Command_Tests.swift @@ -44,8 +44,10 @@ class RunAsync_Tests: XCTestCase { XCTAssertEqual( asynctask.stdout.read(), "" ) } + func testThrowsErrorOnExitcodeNotZero () { + let asynctask = main.runAsync(bash: "echo errormessage > /dev/stderr; exit 1" ) - XCTAssertEqual( asynctask.stderror.read(), "one two\n" ) - XCTAssertEqual( asynctask.stdout.read(), "" ) + AssertThrows(ShellError.ReturnedErrorCode(errorcode: 1)) { try asynctask.finish() } + XCTAssertEqual( asynctask.stderror.read(), "errormessage\n" ) } }