From c7d428455c42e8039a6aedeb032b0685d7a47ebb Mon Sep 17 00:00:00 2001 From: Grégoire Duchêne Date: Sun, 2 Nov 2025 19:27:32 +0000 Subject: First version of the CLI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It’s pretty basic, and it only works on macOS for now. --- Sources/Watcher.swift | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Sources/Watcher.swift (limited to 'Sources/Watcher.swift') diff --git a/Sources/Watcher.swift b/Sources/Watcher.swift new file mode 100644 index 0000000..c7ca85a --- /dev/null +++ b/Sources/Watcher.swift @@ -0,0 +1,58 @@ +import Logging +import ServiceLifecycle +import SystemPackage +import _NIOFileSystem + +struct Watcher: Service { + let directory: FilePath + let logger: Logger + let suffix: String + + func run() async { + let sleepInhibitor = SleepInhibitor() + + while !Task.isCancelled { + let isDownloading: Bool + do { + isDownloading = try await FileSystem.shared.withDirectoryHandle(atPath: self.directory) { + try await $0.listContents().contains { + $0.name.extension?.hasSuffix(self.suffix) ?? false + } + } + } catch is CancellationError { + return + } catch { + self.logger.error("Failed to check directory: \(error)") + return + } + + switch (isDownloading, await sleepInhibitor.isInhibitingSleep) { + case (true, false): + self.logger.debug("Ongoing downloads found, inhibiting sleep") + do { + try await sleepInhibitor.create( + name: "caffeinate-downloads", + details: "There are files being downloaded" + ) + } catch { + self.logger.error("Failed to create assertion: \(error)") + } + + case (false, true): + self.logger.debug("No ongoing downloads found, allowing sleep") + do { + try await sleepInhibitor.release() + } catch { + self.logger.error("Failed to release assertion: \(error)") + } + + default: + break + } + + guard (try? await Task.sleep(for: .seconds(30))) != nil else { + return + } + } + } +} -- cgit v1.2.3-70-g09d2