forked from nsomar/Swiftline
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCommandExecutor.swift
199 lines (150 loc) · 6.92 KB
/
CommandExecutor.swift
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import Foundation
typealias ExecutorReturnValue = (status: Int, standardOutput: String, standardError: String)
enum STDLIB {
#if os(Linux) || os(Android)
typealias _posix_spawn_file_actions_t = posix_spawn_file_actions_t
#else
typealias _posix_spawn_file_actions_t = posix_spawn_file_actions_t?
#endif
#if os(Linux) || os(Android)
static func _make_posix_spawn_file_actions_t() -> _posix_spawn_file_actions_t {
posix_spawn_file_actions_t()
}
#else
static func _make_posix_spawn_file_actions_t() -> _posix_spawn_file_actions_t {
nil
}
#endif
}
class CommandExecutor {
static var currentTaskExecutor: TaskExecutor = ActualTaskExecutor()
class func execute(_ commandParts: [String]) -> ExecutorReturnValue {
return currentTaskExecutor.execute(commandParts)
}
}
protocol TaskExecutor {
func execute(_ commandParts: [String]) -> ExecutorReturnValue
}
extension TaskExecutor {
func readPipes(stdoutPipe: Pipe, stderrPipe: Pipe) -> (stdout: String, stderr: String) {
let stdout = readPipe(stdoutPipe).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let stderr = readPipe(stderrPipe).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return (stdout, stderr)
}
}
class DryTaskExecutor: TaskExecutor {
func execute(_ commandParts: [String]) -> ExecutorReturnValue {
let command = commandParts.joined(separator: " ")
PromptSettings.print("Executed command '\(command)'")
return (0, "", "")
}
}
class ActualTaskExecutor: TaskExecutor {
func execute(_ commandParts: [String]) -> ExecutorReturnValue {
let group = DispatchGroup()
group.enter()
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/bin/env")
task.arguments = commandParts
let stdoutPipe = Pipe()
let stderrPipe = Pipe()
task.standardOutput = stdoutPipe
task.standardError = stderrPipe
task.terminationHandler = { _ in group.leave() }
do {
try task.run()
} catch {
group.leave()
}
group.wait()
let (stdout, stderr) = readPipes(stdoutPipe: stdoutPipe, stderrPipe: stderrPipe)
return (Int(task.terminationStatus), stdout, stderr)
}
static var environment: [UnsafeMutablePointer<CChar>?] {
let env = ActualTaskExecutor().execute(["env"])
guard env.status == 0 else { return [nil] }
let environment = env.standardOutput
.components(separatedBy: "\n")
.map { path in path.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: .newlines) }
.filter { path in !path.isEmpty }
return environment.map { $0.withCString(strdup) } + [nil]
}
}
class InteractiveTaskExecutor: TaskExecutor {
func execute(_ commandParts: [String]) -> ExecutorReturnValue {
let argv: [UnsafeMutablePointer<CChar>?] = commandParts.map { $0.withCString(strdup) }
defer { for case let arg? in argv { free(arg) } }
let outputPipe: [Int32] = [-1, -1]
var childFDActions = STDLIB._make_posix_spawn_file_actions_t()
posix_spawn_file_actions_init(&childFDActions)
posix_spawn_file_actions_adddup2(&childFDActions, outputPipe[1], 1)
posix_spawn_file_actions_adddup2(&childFDActions, outputPipe[1], 2)
posix_spawn_file_actions_addclose(&childFDActions, outputPipe[0])
posix_spawn_file_actions_addclose(&childFDActions, outputPipe[1])
var pid: pid_t = 0
let result = posix_spawn(&pid, argv[0], &childFDActions, nil, argv + [nil], ActualTaskExecutor.environment)
return (Int(result), "", "")
}
}
class LogTaskExecutor: TaskExecutor {
let logPath: String
init(logPath: String) {
self.logPath = logPath
}
func execute(_ commandParts: [String]) -> ExecutorReturnValue {
let argv: [UnsafeMutablePointer<CChar>?] = commandParts.map { $0.withCString(strdup) }
var pid: pid_t = 0
var childFDActions = STDLIB._make_posix_spawn_file_actions_t()
let outputPipe: Int32 = 69
let outerrPipe: Int32 = 70
defer {
for case let arg? in argv { free(arg) }
posix_spawn_file_actions_addclose(&childFDActions, outputPipe)
posix_spawn_file_actions_addclose(&childFDActions, outerrPipe)
posix_spawn_file_actions_destroy(&childFDActions)
}
posix_spawn_file_actions_init(&childFDActions)
posix_spawn_file_actions_addopen(&childFDActions, outputPipe, stdoutLogPath, O_CREAT | O_TRUNC | O_WRONLY, ~0)
posix_spawn_file_actions_addopen(&childFDActions, outerrPipe, stderrLogPath, O_CREAT | O_TRUNC | O_WRONLY, ~0)
posix_spawn_file_actions_adddup2(&childFDActions, outputPipe, 1)
posix_spawn_file_actions_adddup2(&childFDActions, outerrPipe, 2)
var result = posix_spawn(&pid, argv[0], &childFDActions, nil, argv + [nil], ActualTaskExecutor.environment)
guard result == 0 else { return (Int(result), "", "") }
waitpid(pid, &result, 0)
let (stdout, stderr) = read(outputPath: stdoutLogPath, outerrPath: stderrLogPath)
removeFiles(stdoutLogPath, stderrLogPath)
write(atPath: logPath, content: "\(stdout)\n\(stderr)")
return (Int(0), stdout, stderr)
}
private var stdoutLogPath: String { return "\(logPath)-stdout.log" }
private var stderrLogPath: String { return "\(logPath)-stderr.log" }
private func removeFiles(_ files: String...) {
files.forEach { file in
try? FileManager.default.removeItem(atPath: file)
}
}
private func read(outputPath: String, outerrPath: String) -> (stdout: String, stderr: String) {
let stdout = String(data: FileManager.default.contents(atPath: outputPath) ?? Data(), encoding: .utf8) ?? ""
let stderr = String(data: FileManager.default.contents(atPath: outerrPath) ?? Data(), encoding: .utf8) ?? ""
return (stdout, stderr)
}
private func write(atPath path: String, content: String) {
FileManager.default.createFile(atPath: path, contents: content.data(using: .utf8), attributes: nil)
}
}
class DummyTaskExecutor: TaskExecutor {
var commandsExecuted: [String] = []
let statusCodeToReturn: Int
let errorToReturn: String
let outputToReturn: String
init(status: Int, output: String, error: String) {
statusCodeToReturn = status
outputToReturn = output
errorToReturn = error
}
func execute(_ commandParts: [String]) -> ExecutorReturnValue {
let command = commandParts.joined(separator: " ")
commandsExecuted.append(command)
return (statusCodeToReturn, outputToReturn, errorToReturn)
}
}