Implement unwatching a path

This commit is contained in:
T. R. Bernstein
2026-03-11 18:40:08 +01:00
parent 564c409c15
commit 5247d898cd
3 changed files with 25 additions and 0 deletions

View File

@@ -21,6 +21,13 @@ public actor Inotify {
return wd
}
public func removeWatch(_ wd: Int32) throws {
guard inotify_rm_watch(self.fd, wd) == 0 else {
throw InotifyError.removeWatchFailed(watchDescriptor: wd, errno: cinotify_get_errno())
}
watches.removeValue(forKey: wd)
}
deinit {
cinotify_deinit(self.fd)
}

View File

@@ -3,6 +3,7 @@ import CInotify
public enum InotifyError: Error, Sendable, CustomStringConvertible {
case initFailed(errno: Int32)
case addWatchFailed(path: String, errno: Int32)
case removeWatchFailed(watchDescriptor: Int32, errno: Int32)
public var description: String {
switch self {
@@ -10,6 +11,8 @@ public enum InotifyError: Error, Sendable, CustomStringConvertible {
"inotify_init1 failed: \(readableErrno(code))"
case .addWatchFailed(let path, let code):
"inotify_add_watch failed for '\(path)': \(readableErrno(code))"
case .removeWatchFailed(let wd, let code):
"inotify_rm_watch failed for wd \(wd): \(readableErrno(code))"
}
}

View File

@@ -18,4 +18,19 @@ struct WatchTests {
try await watcher.addWatch(path: "/nonexistent-\(UUID())", mask: .allEvents)
}
}
@Test func removeWatchSucceeds() async throws {
try await withTempDir { dir in
let watcher = try Inotify()
let wd = try await watcher.addWatch(path: dir, mask: .allEvents)
try await watcher.removeWatch(wd)
}
}
@Test func removeInvalidWatchThrows() async throws {
let watcher = try Inotify()
await #expect(throws: InotifyError.self) {
try await watcher.removeWatch(9999)
}
}
}