From 6f967c06830e5d25f790089cd5a0b0e8219cbab2 Mon Sep 17 00:00:00 2001 From: Kare Morstol Date: Wed, 5 Aug 2015 21:10:00 +0200 Subject: [PATCH] Add $ method to ShellContextType. --- SwiftShell/Command.swift | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/SwiftShell/Command.swift b/SwiftShell/Command.swift index 09cbd68..982e9d6 100644 --- a/SwiftShell/Command.swift +++ b/SwiftShell/Command.swift @@ -7,17 +7,42 @@ import Foundation -public func runLater (shellcommand: String) -> NSTask { - let task = NSTask() - task.arguments = ["-c", shellcommand] - task.launchPath = "/bin/bash" - - return task -} /** Print message to standard error and halt execution. */ @noreturn public func printErrorAndExit (errormessage: T, errorcode: Int32 = EXIT_FAILURE) { main.stderror.writeln("SwiftShell: \(errormessage)") exit(errorcode) } + +extension ShellContextType { + + func runLater (shellcommand: String, args: [String]) -> NSTask { + let task = NSTask() + task.arguments = args + task.launchPath = shellcommand + task.environment = main.env + + return task + } + + func runLater (bash bashcommand: String) -> NSTask { + return runLater("/bin/bash", args: ["-c", bashcommand]) + } + + /** Shortcut for in-line command, returns output as String. */ + public func $ (shellcommand: String, args: String ...) -> String { + let task = runLater(shellcommand, args: args) + + // avoids implicit reading of the main script's standardInput + task.standardInput = NSPipe () + + let output = NSPipe () + task.standardOutput = output + task.standardError = output + task.launch() + task.waitUntilExit() + + return output.fileHandleForReading.read(encoding: self.encoding) + } + }