Skip to content

Instantly share code, notes, and snippets.

@kjessup
Created July 26, 2017 16:48
Show Gist options
  • Save kjessup/2d0a4627338ccdb9f2f61271eeea43a0 to your computer and use it in GitHub Desktop.
Save kjessup/2d0a4627338ccdb9f2f61271eeea43a0 to your computer and use it in GitHub Desktop.
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