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
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