Files
swift-hpa/Sources/FileClient/FileClient.swift

64 lines
1.6 KiB
Swift

import Dependencies
import DependenciesMacros
import Foundation
public extension DependencyValues {
var fileClient: FileClient {
get { self[FileClient.self] }
set { self[FileClient.self] = newValue }
}
}
@DependencyClient
public struct FileClient: Sendable {
public var copy: @Sendable (URL, URL) async throws -> Void
public var fileExists: @Sendable (URL) -> Bool = { _ in true }
public var homeDirectory: @Sendable () -> URL = { URL(filePath: "~/") }
public var load: @Sendable (URL) async throws -> Data
public var write: @Sendable (Data, URL) async throws -> Void
}
extension FileClient: DependencyKey {
public static let testValue: FileClient = Self()
public static var liveValue: Self {
let manager = LiveFileClient()
return .init {
try await manager.copy($0, to: $1)
} fileExists: { url in
manager.fileExists(at: url)
} homeDirectory: {
manager.homeDirectory()
} load: { url in
try await manager.load(from: url)
} write: { data, url in
try await manager.write(data, to: url)
}
}
}
struct LiveFileClient: Sendable {
private var manager: FileManager { FileManager.default }
func copy(_ url: URL, to toUrl: URL) async throws {
try manager.copyItem(at: url, to: toUrl)
}
func fileExists(at url: URL) -> Bool {
manager.fileExists(atPath: url.absoluteString.replacing("file://", with: ""))
}
func homeDirectory() -> URL {
manager.homeDirectoryForCurrentUser
}
func load(from url: URL) async throws -> Data {
try Data(contentsOf: url)
}
func write(_ data: Data, to url: URL) async throws {
try data.write(to: url)
}
}