Skip to content

Instantly share code, notes, and snippets.

@robertBojor
Created September 14, 2016 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertBojor/c8d856262c84bb8c0ff45eebd2ef0668 to your computer and use it in GitHub Desktop.
Save robertBojor/c8d856262c84bb8c0ff45eebd2ef0668 to your computer and use it in GitHub Desktop.
import PerfectLib
import Foundation
import Cocoa
#if os(Linux)
import SwiftGlibc
#else
import Darwin
#endif
/*
try runProc("/usr/local/bin/binary_here", args: args, envs: ["API_KEY":config.accessKey, "API_ACCESS_KEY":config.secret]) {
str in
// use str
}
*/
public func runProc(_ cmd: String, args: [String], read: ((String) -> ())? = nil) throws {
try runProc(cmd, args: args, envs: [String : String](), read: read)
}
public func runProc(_ cmd: String, args: [String], envs: [String:String], read: ((String) -> ())? = nil) throws {
var ienvs = [("PATH", "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local:/usr/local/Cellar:~/.swiftenv/"),
("HOME", ProcessInfo.processInfo.environment["HOME"]!),
("LANG", "en_CA.UTF-8")]
for e in envs {
ienvs.append(e)
}
var newCmd = "\"\(cmd)\""
for n in 0..<args.count {
newCmd.append(" $\(n)")
}
let proc = try SysProcess("/bin/bash", args: ["--login", "-c", newCmd] + args, env: ienvs)
if let read = read {
while true {
do {
guard let s = try proc.stdout?.readSomeBytes(count: 1024) , s.count > 0 else {
break
}
let str = UTF8Encoding.encode(bytes: s)
read(str)
} catch PerfectLib.PerfectError.fileError(let code, _) {
if code != EINTR {
break
}
}
}
}
let res = try proc.wait(hang: true)
if res != 0 {
let s = try proc.stderr?.readString()
throw PerfectError.systemError(Int32(res), s!)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment