Skip to content

Instantly share code, notes, and snippets.

@profburke
Last active October 18, 2021 05:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save profburke/c6a39a034077584f8dbafe591bcb526d to your computer and use it in GitHub Desktop.
Save profburke/c6a39a034077584f8dbafe591bcb526d to your computer and use it in GitHub Desktop.
import Foundation
public enum ExecutionError: Error {
case SomethingHappened
}
func execute(command: String, args: [String]? = nil, input: String? = nil) throws -> String {
let task = Process()
var inpipe: Pipe?
task.launchPath = command
if args != nil {
task.arguments = args
}
if input != nil {
inpipe = Pipe()
task.standardInput = inpipe
}
let outpipe = Pipe()
task.standardOutput = outpipe
task.launch()
if let inpipe = inpipe,
let input = input {
let bytes: [UInt8] = Array(input.utf8)
let fh = inpipe.fileHandleForWriting
fh.write(Data(bytes: bytes))
fh.closeFile()
}
let output = outpipe.fileHandleForReading.readDataToEndOfFile().base64EncodedString()
return output
}
// NOTE: this does not return what you'd expect. The returned string is Base64-encoded data
// (because that's what I needed for a particular use case).
// So if you want to do something "normal", e.g.
//
// let result = execute(command: "/bin/ls", args: ["-a", "-l"])
//
// You'll then need to decode result as follows:
//
// let listing = String(data: Data(base64Encoded: res!)!, encoding: .utf8)!
//
// Needs some improvements. In particular, launch throws an error if the launchPath does
// not point to a valid executable. Do we want to catch it and try and do something
// like search a path?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment