-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessAdditions.swift
More file actions
66 lines (60 loc) · 2.33 KB
/
ProcessAdditions.swift
File metadata and controls
66 lines (60 loc) · 2.33 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
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
//
// ProcessAdditions.swift
// CaffeineKit
//
// Created by aaplmath on 8/16/18.
//
import Foundation
internal extension Process {
/// Generates a Process for the `caffeinate` executable with the specified `Caffeination.Opts`
static func caffeinate(opts: [Caffeination.Opt], allowingFinite: Bool, safetyCheck: Bool) -> Process {
let proc = Process()
if #available(OSX 10.13, *) {
proc.executableURL = Caffeination.caffeinatePath
} else {
proc.launchPath = Caffeination.caffeinatePath.path
}
proc.standardError = FileHandle.nullDevice
proc.arguments = [] // Enables all the force-unwrapping later on
// Log caffeinate output using Logger
if Logger.logLevel.rawValue >= LogLevel.error.rawValue {
if Logger.logLevel.rawValue >= LogLevel.info.rawValue {
let infoPipe = Pipe()
proc.standardOutput = infoPipe
infoPipe.fileHandleForReading.readabilityHandler = { pipe in
if let line = String(data: pipe.availableData, encoding: .utf8) {
Logger.log(.info, "[caffeinate] \(line)")
}
}
} else {
proc.standardOutput = FileHandle.nullDevice
}
let errPipe = Pipe()
proc.standardError = errPipe
errPipe.fileHandleForReading.readabilityHandler = { pipe in
if let line = String(data: pipe.availableData, encoding: .utf8) {
Logger.log(.error, "[caffeinate] \(line)")
}
}
} else {
proc.standardError = FileHandle.nullDevice
}
for opt in opts {
if !allowingFinite {
if case .timed = opt {
continue
} else if case .process = opt {
continue
}
}
proc.arguments!.append(contentsOf: opt.argumentList)
}
// Have caffeinate automatically terminate upon the app's termination as an added precaution
if safetyCheck {
if !proc.arguments!.contains("-w") {
proc.arguments! += ["-w", String(ProcessInfo.processInfo.processIdentifier)]
}
}
return proc
}
}