forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLaunchAgentManager.swift
More file actions
79 lines (72 loc) · 2.33 KB
/
LaunchAgentManager.swift
File metadata and controls
79 lines (72 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
67
68
69
70
71
72
73
74
75
76
77
78
79
import Foundation
struct LaunchAgentManager {
var serviceIdentifier: String {
Bundle.main
.object(forInfoDictionaryKey: "BUNDLE_IDENTIFIER_BASE") as! String +
".XPCService"
}
var location: String {
Bundle.main.executableURL?.deletingLastPathComponent()
.appendingPathComponent("CopilotForXcodeXPCService").path ?? ""
}
var launchAgentDirURL: URL {
FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Library/LaunchAgents")
}
var launchAgentPath: String {
launchAgentDirURL.appendingPathComponent("\(serviceIdentifier).plist").path
}
func setupLaunchAgent() throws {
let content = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>RunAtLoad</key>
<true/>
<key>Label</key>
<string>\(serviceIdentifier)</string>
<key>Program</key>
<string>\(location)</string>
<key>MachServices</key>
<dict>
<key>\(serviceIdentifier)</key>
<true/>
</dict>
</dict>
</plist>
"""
if !FileManager.default.fileExists(atPath: launchAgentDirURL.path) {
try FileManager.default.createDirectory(
at: launchAgentDirURL,
withIntermediateDirectories: false
)
}
FileManager.default.createFile(
atPath: launchAgentPath,
contents: content.data(using: .utf8)
)
launchctl("load", launchAgentPath)
}
func removeLaunchAgent() throws {
launchctl("unload", launchAgentPath)
try FileManager.default.removeItem(atPath: launchAgentPath)
}
}
private func launchctl(_ args: String...) {
let task = Process()
task.launchPath = "/bin/launchctl"
task.arguments = args
task.environment = [
"PATH": "/usr/bin",
]
let outpipe = Pipe()
task.standardOutput = outpipe
try? task.run()
task.waitUntilExit()
if let data = try? outpipe.fileHandleForReading.readToEnd(),
let text = String(data: data, encoding: .utf8)
{
print(text)
}
}