feat: Breaking out more dependencies.

This commit is contained in:
2024-12-11 09:23:34 -05:00
parent 92cd6afa2b
commit 9c784d4dcb
9 changed files with 62 additions and 313 deletions

View File

@@ -13,6 +13,7 @@ public extension DependencyValues {
public struct FileClient: Sendable {
public var copy: @Sendable (URL, URL) async throws -> Void
public var fileExists: @Sendable (URL) -> Bool = { _ in true }
public var findVaultFileInCurrentDirectory: @Sendable () async throws -> URL?
public var homeDirectory: @Sendable () -> URL = { URL(filePath: "~/") }
public var load: @Sendable (URL) async throws -> Data
public var write: @Sendable (Data, URL) async throws -> Void
@@ -27,6 +28,8 @@ extension FileClient: DependencyKey {
try await manager.copy($0, to: $1)
} fileExists: { url in
manager.fileExists(at: url)
} findVaultFileInCurrentDirectory: {
try await manager.findVaultFileInCurrentDirectory()
} homeDirectory: {
manager.homeDirectory()
} load: { url in
@@ -46,13 +49,41 @@ struct LiveFileClient: Sendable {
}
func fileExists(at url: URL) -> Bool {
manager.fileExists(atPath: url.absoluteString.replacing("file://", with: ""))
manager.fileExists(atPath: url.cleanFilePath)
}
func findVaultFileInCurrentDirectory() async throws -> URL? {
let urls = try manager.contentsOfDirectory(
at: URL(filePath: "./"),
includingPropertiesForKeys: nil
)
// Check the current directory
if let vault = urls.firstVaultFile { return vault }
let subfolders = urls.filter { isDirectory($0) }
for folder in subfolders {
let files = try manager.contentsOfDirectory(
at: folder,
includingPropertiesForKeys: nil
)
if let vault = files.firstVaultFile { return vault }
}
return nil
}
func homeDirectory() -> URL {
manager.homeDirectoryForCurrentUser
}
private func isDirectory(_ url: URL) -> Bool {
var isDirectory: ObjCBool = false
manager.fileExists(atPath: url.cleanFilePath, isDirectory: &isDirectory)
return isDirectory.boolValue
}
func load(from url: URL) async throws -> Data {
try Data(contentsOf: url)
}
@@ -61,3 +92,18 @@ struct LiveFileClient: Sendable {
try data.write(to: url)
}
}
private extension Array where Element == URL {
var firstVaultFile: URL? {
first { url in
let string = url.absoluteString
return string.hasSuffix("vault.yml") || string.hasSuffix("vault.yaml")
}
}
}
public extension URL {
var cleanFilePath: String {
absoluteString.replacing("file://", with: "")
}
}