-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathProcess.swift
More file actions
37 lines (33 loc) · 1.66 KB
/
Process.swift
File metadata and controls
37 lines (33 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import Foundation
import PromiseKit
import PMKFoundation
import Path
public typealias ProcessOutput = (status: Int32, out: String, err: String)
extension Process {
@discardableResult
static func sudo(_ executable: Path, workingDirectory: URL? = nil, _ arguments: String...) -> Promise<ProcessOutput> {
run(Path.root.usr.bin.sudo.url, workingDirectory: workingDirectory, [executable.string] + arguments)
}
@discardableResult
static func run(_ executable: Path, workingDirectory: URL? = nil, input: String? = nil, _ arguments: String...) -> Promise<ProcessOutput> {
return run(executable.url, workingDirectory: workingDirectory, input: input, arguments)
}
@discardableResult
static func run(_ executable: URL, workingDirectory: URL? = nil, input: String? = nil, _ arguments: [String]) -> Promise<ProcessOutput> {
let process = Process()
process.currentDirectoryURL = workingDirectory ?? executable.deletingLastPathComponent()
process.executableURL = executable
process.arguments = arguments
if let input = input {
let inputPipe = Pipe()
process.standardInput = inputPipe.fileHandleForReading
inputPipe.fileHandleForWriting.write(Data(input.utf8))
inputPipe.fileHandleForWriting.closeFile()
}
return process.launch(.promise).map { std in
let output = String(data: std.out.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
let error = String(data: std.err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
return (process.terminationStatus, output, error)
}
}
}