Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created August 17, 2021 15:41
Show Gist options
  • Save ollieatkinson/630723ae54696e902d943f571bd1be2d to your computer and use it in GitHub Desktop.
Save ollieatkinson/630723ae54696e902d943f571bd1be2d to your computer and use it in GitHub Desktop.
Simply execute shell commands from Swift
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