-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHookInstaller.swift
More file actions
321 lines (266 loc) · 11.1 KB
/
HookInstaller.swift
File metadata and controls
321 lines (266 loc) · 11.1 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
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import Foundation
/// Manages installation and configuration of Claude Code hooks for "asking" state detection
class HookInstaller {
static let shared = HookInstaller()
private let fileManager = FileManager.default
// Paths
private var claudeDir: URL {
fileManager.homeDirectoryForCurrentUser.appendingPathComponent(".claude")
}
private var hooksDir: URL {
claudeDir.appendingPathComponent("hooks")
}
private var settingsPath: URL {
claudeDir.appendingPathComponent("settings.json")
}
// Hook filenames
private let stateHookFilename = "claude-state-hook.sh"
private let permissionHookFilename = "permission-hook.sh"
/// Comment marker to identify our hooks in settings.json
private let hookMarker = "GhosttyThemePicker"
// MARK: - Public Methods
/// Check if hooks are installed and configured
func areHooksInstalled() -> Bool {
// Check if both script files exist
let stateHookExists = fileManager.fileExists(atPath: hooksDir.appendingPathComponent(stateHookFilename).path)
let permissionHookExists = fileManager.fileExists(atPath: hooksDir.appendingPathComponent(permissionHookFilename).path)
guard stateHookExists && permissionHookExists else {
return false
}
// Check if hooks are configured in settings.json
guard let settings = loadSettings() else {
return false
}
return settingsContainHooks(settings)
}
/// Install hooks and configure settings.json
func installHooks() throws {
// Create directories if needed
try fileManager.createDirectory(at: hooksDir, withIntermediateDirectories: true)
// Copy hook scripts from app bundle
try installHookScript(named: stateHookFilename)
try installHookScript(named: permissionHookFilename)
// Update settings.json
try configureSettings()
print("Claude Code hooks installed successfully")
}
/// Remove hooks and clean up settings.json
func uninstallHooks() throws {
// Remove hook scripts
let stateHookPath = hooksDir.appendingPathComponent(stateHookFilename)
let permissionHookPath = hooksDir.appendingPathComponent(permissionHookFilename)
if fileManager.fileExists(atPath: stateHookPath.path) {
try fileManager.removeItem(at: stateHookPath)
}
if fileManager.fileExists(atPath: permissionHookPath.path) {
try fileManager.removeItem(at: permissionHookPath)
}
// Remove hooks from settings.json
try removeHooksFromSettings()
// Clean up state files
cleanupStateFiles()
print("Claude Code hooks uninstalled successfully")
}
// MARK: - Private Methods
private func installHookScript(named filename: String) throws {
// Get script from app bundle
guard let bundlePath = Bundle.main.path(forResource: filename, ofType: nil, inDirectory: "hooks") else {
// Try without directory (in case hooks are at root of bundle)
guard let bundlePath = Bundle.main.path(forResource: filename, ofType: nil) else {
throw HookInstallerError.scriptNotFoundInBundle(filename)
}
try installScript(from: bundlePath, filename: filename)
return
}
try installScript(from: bundlePath, filename: filename)
}
private func installScript(from bundlePath: String, filename: String) throws {
let destPath = hooksDir.appendingPathComponent(filename)
// Remove existing file if present
if fileManager.fileExists(atPath: destPath.path) {
try fileManager.removeItem(at: destPath)
}
// Copy from bundle
try fileManager.copyItem(atPath: bundlePath, toPath: destPath.path)
// Make executable (chmod 755)
try fileManager.setAttributes(
[.posixPermissions: 0o755],
ofItemAtPath: destPath.path
)
}
private func loadSettings() -> [String: Any]? {
guard fileManager.fileExists(atPath: settingsPath.path),
let data = try? Data(contentsOf: settingsPath),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return nil
}
return json
}
private func saveSettings(_ settings: [String: Any]) throws {
let data = try JSONSerialization.data(withJSONObject: settings, options: [.prettyPrinted, .sortedKeys])
try data.write(to: settingsPath)
}
private func settingsContainHooks(_ settings: [String: Any]) -> Bool {
guard let hooks = settings["hooks"] as? [String: Any] else {
return false
}
// Check for Stop hook with our marker
if let stopHooks = hooks["Stop"] as? [[String: Any]] {
let hasStateHook = stopHooks.contains { hook in
guard let hookList = hook["hooks"] as? [[String: Any]] else { return false }
return hookList.contains { h in
(h["command"] as? String)?.contains(stateHookFilename) == true
}
}
if !hasStateHook { return false }
} else {
return false
}
// Check for Notification hook with our marker
if let notificationHooks = hooks["Notification"] as? [[String: Any]] {
let hasPermissionHook = notificationHooks.contains { hook in
guard let hookList = hook["hooks"] as? [[String: Any]] else { return false }
return hookList.contains { h in
(h["command"] as? String)?.contains(permissionHookFilename) == true
}
}
if !hasPermissionHook { return false }
} else {
return false
}
return true
}
private func configureSettings() throws {
// Create ~/.claude directory if needed
try fileManager.createDirectory(at: claudeDir, withIntermediateDirectories: true)
// Load existing settings or create empty
var settings = loadSettings() ?? [:]
// Get or create hooks dictionary
var hooks = settings["hooks"] as? [String: Any] ?? [:]
// Configure Stop hook
let stateHookPath = "~/.claude/hooks/\(stateHookFilename)"
let stateHookConfig: [String: Any] = [
"matcher": "",
"hooks": [
[
"type": "command",
"command": stateHookPath,
"async": true
]
]
]
// Add or update Stop hooks
if var stopHooks = hooks["Stop"] as? [[String: Any]] {
// Remove any existing hooks with our script
stopHooks.removeAll { hook in
guard let hookList = hook["hooks"] as? [[String: Any]] else { return false }
return hookList.contains { h in
(h["command"] as? String)?.contains(stateHookFilename) == true
}
}
stopHooks.append(stateHookConfig)
hooks["Stop"] = stopHooks
} else {
hooks["Stop"] = [stateHookConfig]
}
// Configure Notification hook (permission_prompt)
let permissionHookPath = "~/.claude/hooks/\(permissionHookFilename)"
let permissionHookConfig: [String: Any] = [
"matcher": "permission_prompt",
"hooks": [
[
"type": "command",
"command": permissionHookPath,
"async": true
]
]
]
// Add or update Notification hooks
if var notificationHooks = hooks["Notification"] as? [[String: Any]] {
// Remove any existing hooks with our script
notificationHooks.removeAll { hook in
guard let hookList = hook["hooks"] as? [[String: Any]] else { return false }
return hookList.contains { h in
(h["command"] as? String)?.contains(permissionHookFilename) == true
}
}
notificationHooks.append(permissionHookConfig)
hooks["Notification"] = notificationHooks
} else {
hooks["Notification"] = [permissionHookConfig]
}
settings["hooks"] = hooks
try saveSettings(settings)
}
private func removeHooksFromSettings() throws {
guard var settings = loadSettings() else {
return // No settings file, nothing to remove
}
guard var hooks = settings["hooks"] as? [String: Any] else {
return // No hooks configured
}
// Remove our Stop hook
if var stopHooks = hooks["Stop"] as? [[String: Any]] {
stopHooks.removeAll { hook in
guard let hookList = hook["hooks"] as? [[String: Any]] else { return false }
return hookList.contains { h in
(h["command"] as? String)?.contains(stateHookFilename) == true
}
}
if stopHooks.isEmpty {
hooks.removeValue(forKey: "Stop")
} else {
hooks["Stop"] = stopHooks
}
}
// Remove our Notification hook
if var notificationHooks = hooks["Notification"] as? [[String: Any]] {
notificationHooks.removeAll { hook in
guard let hookList = hook["hooks"] as? [[String: Any]] else { return false }
return hookList.contains { h in
(h["command"] as? String)?.contains(permissionHookFilename) == true
}
}
if notificationHooks.isEmpty {
hooks.removeValue(forKey: "Notification")
} else {
hooks["Notification"] = notificationHooks
}
}
// Update or remove hooks section
if hooks.isEmpty {
settings.removeValue(forKey: "hooks")
} else {
settings["hooks"] = hooks
}
try saveSettings(settings)
}
private func cleanupStateFiles() {
let stateDir = fileManager.homeDirectoryForCurrentUser.appendingPathComponent(".claude-states")
guard fileManager.fileExists(atPath: stateDir.path) else {
return
}
// Remove all state files
if let files = try? fileManager.contentsOfDirectory(at: stateDir, includingPropertiesForKeys: nil) {
for file in files where file.lastPathComponent.hasPrefix("state-") {
try? fileManager.removeItem(at: file)
}
}
}
}
// MARK: - Error Types
enum HookInstallerError: LocalizedError {
case scriptNotFoundInBundle(String)
case failedToCreateDirectory(String)
case failedToCopyScript(String)
var errorDescription: String? {
switch self {
case .scriptNotFoundInBundle(let name):
return "Hook script '\(name)' not found in app bundle"
case .failedToCreateDirectory(let path):
return "Failed to create directory: \(path)"
case .failedToCopyScript(let name):
return "Failed to copy hook script: \(name)"
}
}
}