Created
July 26, 2017 16:48
-
-
Save kjessup/2d0a4627338ccdb9f2f61271eeea43a0 to your computer and use it in GitHub Desktop.
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
func runProc(_ cmd: String, args: [String], envs: [String:String] = [:], quoteArgs: Bool = true, stderr: Bool = false, cd: String? = nil, read: ((String) -> ())? = nil) throws { | |
var ienvs = [("PATH", pathFromShell), | |
("HOME", ProcessInfo.processInfo.environment["HOME"]!), | |
("LANG", "en_CA.UTF-8")] | |
for e in envs { | |
ienvs.append(e) | |
} | |
let cmdPath = File(cmd).path | |
var newCmd: String | |
if let cd = cd { | |
newCmd = "cd '\(cd)' && '\(cmdPath)\'" | |
} else { | |
newCmd = "'\(cmdPath)\'" | |
} | |
for n in 1...args.count { | |
if quoteArgs { | |
newCmd.append(" \"${\(n)}\"") | |
} else { | |
newCmd.append(" ${\(n)}") | |
} | |
} | |
let shell = "/bin/sh" | |
let proc = try SysProcess(shell, args: ["--login", "-ci", newCmd, cmdPath] + args, env: ienvs) | |
let out: File? = stderr ? proc.stderr : proc.stdout | |
if let read = read { | |
while true { | |
do { | |
guard let s = try out?.readSomeBytes(count: 1024) , s.count > 0 else { | |
break | |
} | |
let str = UTF8Encoding.encode(bytes: s) | |
read(str.replacingOccurrences(of: "sh: no job control in this shell\n", with: "")) | |
} 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!.replacingOccurrences(of: "sh: no job control in this shell\n", with: "")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment