-
Notifications
You must be signed in to change notification settings - Fork 9
/
runfg.swift
executable file
·196 lines (159 loc) · 5.14 KB
/
runfg.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
#!/usr/bin/env swift
// Run directly:
// chmod +x runfg.swift
// ./runfg.swift
//
// Compile to static binary:
// swiftc runfg.swift -o runfg
// ./runfg
//
// Or download already compiled binary:
// curl https://files.alinpanaitiu.com/runfg > /usr/local/bin/runfg
// chmod +x /usr/local/bin/runfg
// runfg
// Usage examples:
// Optimize all images on the desktop: runfg imageoptim ~/Desktop
// Re-encode video with ffmpeg to squeeze more bytes: runfg ffmpeg -i big-video.mp4 smaller-video.mp4
// Compile project in background: runfg make -j 4
import Foundation
if CommandLine.arguments.count <= 1 {
print(CommandLine.arguments[0], "executable args...")
exit(1)
}
let SHELL = ProcessInfo.processInfo.environment["SHELL"] ?? "/bin/zsh"
let FM = FileManager()
@discardableResult func asyncNow(timeout: TimeInterval, _ action: @escaping () -> Void) -> DispatchTimeoutResult {
let task = DispatchWorkItem { action() }
DispatchQueue.global().async(execute: task)
let result = task.wait(timeout: DispatchTime.now() + timeout)
if result == .timedOut {
task.cancel()
}
return result
}
// MARK: - ProcessStatus
struct ProcessStatus {
var output: Data?
var error: Data?
var success: Bool
var o: String? {
output?.s?.trimmed
}
var e: String? {
error?.s?.trimmed
}
}
func stdout(of process: Process) -> Data? {
let stdout = process.standardOutput as! FileHandle
try? stdout.close()
guard let path = process.environment?["__swift_stdout"],
let stdoutFile = FileHandle(forReadingAtPath: path) else { return nil }
return try! stdoutFile.readToEnd()
}
func stderr(of process: Process) -> Data? {
let stderr = process.standardOutput as! FileHandle
try? stderr.close()
guard let path = process.environment?["__swift_stderr"],
let stderrFile = FileHandle(forReadingAtPath: path) else { return nil }
return try! stderrFile.readToEnd()
}
func shellProc(_ launchPath: String = "/bin/zsh", args: [String], env: [String: String]? = nil) -> Process? {
let outputDir = try! FM.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: FM.homeDirectoryForCurrentUser,
create: true
)
let stdoutFilePath = outputDir.appendingPathComponent("stdout").path
FM.createFile(atPath: stdoutFilePath, contents: nil, attributes: nil)
let stderrFilePath = outputDir.appendingPathComponent("stderr").path
FM.createFile(atPath: stderrFilePath, contents: nil, attributes: nil)
guard let stdoutFile = FileHandle(forWritingAtPath: stdoutFilePath),
let stderrFile = FileHandle(forWritingAtPath: stderrFilePath)
else {
return nil
}
let task = Process()
task.standardOutput = stdoutFile
task.standardError = stderrFile
task.launchPath = launchPath
task.arguments = args
var env = env ?? ProcessInfo.processInfo.environment
env["__swift_stdout"] = stdoutFilePath
env["__swift_stderr"] = stderrFilePath
task.environment = env
do {
try task.run()
} catch {
print("Error running \(launchPath) \(args): \(error)")
return nil
}
return task
}
func shell(
_ launchPath: String = "/bin/zsh",
command: String,
timeout: TimeInterval? = nil,
env _: [String: String]? = nil
) -> ProcessStatus {
shell(launchPath, args: ["-c", command], timeout: timeout)
}
func shell(
_ launchPath: String = "/bin/zsh",
args: [String],
timeout: TimeInterval? = nil,
env: [String: String]? = nil
) -> ProcessStatus {
guard let task = shellProc(launchPath, args: args, env: env) else {
return ProcessStatus(output: nil, error: nil, success: false)
}
guard let timeout else {
task.waitUntilExit()
return ProcessStatus(
output: stdout(of: task),
error: stderr(of: task),
success: task.terminationStatus == 0
)
}
let result = asyncNow(timeout: timeout) {
task.waitUntilExit()
}
if result == .timedOut {
task.terminate()
}
return ProcessStatus(
output: stdout(of: task),
error: stderr(of: task),
success: task.terminationStatus == 0
)
}
extension String {
@inline(__always) var trimmed: String {
trimmingCharacters(in: .whitespacesAndNewlines)
}
}
extension Data {
var s: String? { String(data: self, encoding: .utf8) }
}
var executable = (CommandLine.arguments[1] as NSString).expandingTildeInPath
if !FM.fileExists(atPath: executable) {
let which = shell(SHELL, command: "which '\(CommandLine.arguments[1])'")
guard which.success, let output = which.o else {
if let err = which.e {
print(err)
}
print("\(executable) not found")
exit(1)
}
executable = output
}
let p = Process()
p.qualityOfService = .userInteractive
p.executableURL = URL(fileURLWithPath: executable)
p.arguments = CommandLine.arguments.suffix(from: 2).map { $0 }
try! p.run()
signal(SIGINT) { _ in p.terminate() }
signal(SIGTERM) { _ in p.terminate() }
signal(SIGKILL) { _ in p.terminate() }
p.waitUntilExit()
exit(p.terminationStatus)