Created
November 27, 2024 07:17
-
-
Save finestructure/8ff2c7d16ab05c73222f28920f74705d to your computer and use it in GitHub Desktop.
Tim's Process helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Via Tim Condon | |
@discardableResult | |
func shell(_ args: String..., returnStdOut: Bool = false, stdIn: Pipe? = nil) throws -> (Int32, Pipe) { | |
return try shell(args, returnStdOut: returnStdOut, stdIn: stdIn) | |
} | |
@discardableResult | |
func shell(_ args: [String], returnStdOut: Bool = false, stdIn: Pipe? = nil) throws -> (Int32, Pipe) { | |
let task = Process() | |
task.executableURL = URL(fileURLWithPath: "/usr/bin/env") | |
task.arguments = args | |
let pipe = Pipe() | |
if returnStdOut { | |
task.standardOutput = pipe | |
} | |
if let stdIn = stdIn { | |
task.standardInput = stdIn | |
} | |
try task.run() | |
task.waitUntilExit() | |
return (task.terminationStatus, pipe) | |
} | |
extension Pipe { | |
func string() -> String? { | |
let data = self.fileHandleForReading.readDataToEndOfFile() | |
let result: String? | |
if let string = String(data: data, encoding: String.Encoding.utf8) { | |
result = string | |
} else { | |
result = nil | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment