-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathFileChangeWatcherService.swift
More file actions
206 lines (164 loc) · 7.55 KB
/
FileChangeWatcherService.swift
File metadata and controls
206 lines (164 loc) · 7.55 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
import Foundation
import System
import Logger
import CoreServices
import LanguageServerProtocol
import XcodeInspector
public class FileChangeWatcherService {
internal var watcher: DirectoryWatcherProtocol?
private(set) public var workspaceURL: URL
private(set) public var publisher: PublisherType
private(set) public var publishInterval: TimeInterval
// Dependencies injected for testing
internal let workspaceFileProvider: WorkspaceFileProvider
internal let watcherFactory: FileWatcherFactory
// Watching workspace metadata file
private var workspaceConfigFileWatcher: FileWatcherProtocol?
private var isMonitoringWorkspaceConfigFile = false
private let monitoringQueue = DispatchQueue(label: "com.github.copilot.workspaceMonitor", qos: .utility)
private let configFileEventQueue = DispatchQueue(label: "com.github.copilot.workspaceEventMonitor", qos: .utility)
public init(
_ workspaceURL: URL,
publisher: @escaping PublisherType,
publishInterval: TimeInterval = 3.0,
workspaceFileProvider: WorkspaceFileProvider = FileChangeWatcherWorkspaceFileProvider(),
watcherFactory: FileWatcherFactory? = nil
) {
self.workspaceURL = workspaceURL
self.publisher = publisher
self.publishInterval = publishInterval
self.workspaceFileProvider = workspaceFileProvider
self.watcherFactory = watcherFactory ?? DefaultFileWatcherFactory()
}
deinit {
stopWorkspaceConfigFileMonitoring()
self.watcher = nil
}
public func startWatching() {
guard workspaceURL.path != "/" else { return }
guard watcher == nil else { return }
let projects = workspaceFileProvider.getProjects(by: workspaceURL)
guard projects.count > 0 else { return }
watcher = watcherFactory.createDirectoryWatcher(watchedPaths: projects, changePublisher: publisher, publishInterval: publishInterval)
Logger.client.info("Started watching for file changes in \(projects)")
startWatchingProject()
}
internal func startWatchingProject() {
if self.workspaceFileProvider.isXCWorkspace(self.workspaceURL) {
guard !isMonitoringWorkspaceConfigFile else { return }
isMonitoringWorkspaceConfigFile = true
recreateConfigFileMonitor()
}
}
private func recreateConfigFileMonitor() {
let workspaceDataFile = workspaceURL.appendingPathComponent("contents.xcworkspacedata")
// Clean up existing monitor first
cleanupCurrentMonitor()
guard self.workspaceFileProvider.fileExists(atPath: workspaceDataFile.path) else {
Logger.client.info("[FileWatcher] contents.xcworkspacedata file not found at \(workspaceDataFile.path).")
return
}
// Create SingleFileWatcher for the workspace file
workspaceConfigFileWatcher = self.watcherFactory.createFileWatcher(
fileURL: workspaceDataFile,
dispatchQueue: configFileEventQueue,
onFileModified: { [weak self] in
self?.handleWorkspaceConfigFileChange()
self?.scheduleMonitorRecreation(delay: 1.0)
},
onFileDeleted: { [weak self] in
self?.handleWorkspaceConfigFileChange()
self?.scheduleMonitorRecreation(delay: 1.0)
},
onFileRenamed: nil
)
let _ = workspaceConfigFileWatcher?.startWatching()
}
private func handleWorkspaceConfigFileChange() {
guard let watcher = self.watcher else {
return
}
let workspaceDataFile = workspaceURL.appendingPathComponent("contents.xcworkspacedata")
// Check if file still exists
let fileExists = self.workspaceFileProvider.fileExists(atPath: workspaceDataFile.path)
if fileExists {
// File was modified, check for project changes
let watchingProjects = Set(watcher.paths())
let projects = Set(self.workspaceFileProvider.getProjects(by: self.workspaceURL))
/// find added projects
let addedProjects = projects.subtracting(watchingProjects)
if !addedProjects.isEmpty {
self.onProjectAdded(Array(addedProjects))
}
/// find removed projects
let removedProjects = watchingProjects.subtracting(projects)
if !removedProjects.isEmpty {
self.onProjectRemoved(Array(removedProjects))
}
} else {
Logger.client.info("[FileWatcher] contents.xcworkspacedata file was deleted")
}
}
private func scheduleMonitorRecreation(delay: TimeInterval) {
monitoringQueue.asyncAfter(deadline: .now() + delay) { [weak self] in
guard let self = self, self.isMonitoringWorkspaceConfigFile else { return }
self.recreateConfigFileMonitor()
}
}
private func cleanupCurrentMonitor() {
workspaceConfigFileWatcher?.stopWatching()
workspaceConfigFileWatcher = nil
}
private func stopWorkspaceConfigFileMonitoring() {
isMonitoringWorkspaceConfigFile = false
cleanupCurrentMonitor()
}
internal func onProjectAdded(_ projectURLs: [URL]) {
guard let watcher = watcher, projectURLs.count > 0 else { return }
watcher.addPaths(projectURLs)
Logger.client.info("Started watching for file changes in \(projectURLs)")
/// sync all the files as created in the project when added
for projectURL in projectURLs {
let files = workspaceFileProvider.getFilesInActiveWorkspace(
workspaceURL: projectURL,
workspaceRootURL: projectURL
)
publisher(files.map { .init(uri: $0.url.absoluteString, type: .created) })
}
}
internal func onProjectRemoved(_ projectURLs: [URL]) {
guard let watcher = watcher, projectURLs.count > 0 else { return }
watcher.removePaths(projectURLs)
Logger.client.info("Stopped watching for file changes in \(projectURLs)")
/// sync all the files as deleted in the project when removed
for projectURL in projectURLs {
let files = workspaceFileProvider.getFilesInActiveWorkspace(workspaceURL: projectURL, workspaceRootURL: projectURL)
publisher(files.map { .init(uri: $0.url.absoluteString, type: .deleted) })
}
}
}
@globalActor
public enum PoolActor: GlobalActor {
public actor Actor {}
public static let shared = Actor()
}
public class FileChangeWatcherServicePool {
public static let shared = FileChangeWatcherServicePool()
private var servicePool: [URL: FileChangeWatcherService] = [:]
private init() {}
@PoolActor
public func watch(for workspaceURL: URL, publisher: @escaping PublisherType) {
guard workspaceURL.path != "/" else { return }
var validWorkspaceURL: URL? = nil
if WorkspaceFile.isXCWorkspace(workspaceURL) {
validWorkspaceURL = workspaceURL
} else if WorkspaceFile.isXCProject(workspaceURL) {
validWorkspaceURL = WorkspaceFile.getWorkspaceByProject(workspaceURL)
}
guard let validWorkspaceURL else { return }
guard servicePool[workspaceURL] == nil else { return }
let watcherService = FileChangeWatcherService(validWorkspaceURL, publisher: publisher)
watcherService.startWatching()
servicePool[workspaceURL] = watcherService
}
}