Created
August 17, 2021 15:41
-
-
Save ollieatkinson/630723ae54696e902d943f571bd1be2d to your computer and use it in GitHub Desktop.
Simply execute shell commands from Swift
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
public struct Executable { | |
let url: URL | |
public init(_ filePath: String) { | |
url = URL(fileURLWithPath: filePath) | |
} | |
public init(_ url: URL) { | |
self.url = url | |
} | |
public func callAsFunction(_ arguments: String...) -> (stdout: String, stderr: String) { | |
let process = Process() | |
process.executableURL = url | |
process.arguments = arguments | |
let stdout = Pipe() | |
process.standardOutput = stdout | |
let stderr = Pipe() | |
process.standardError = stderr | |
process.launch() | |
process.waitUntilExit() | |
return ( | |
stdout: stdout.readStringToEndOfFile(), | |
stderr: stderr.readStringToEndOfFile() | |
) | |
} | |
} | |
extension Pipe { | |
func readStringToEndOfFile(trimming: CharacterSet = .whitespacesAndNewlines) -> String { | |
String(decoding: fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: trimming) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment