2025-01-11 01:26:26 +01:00
|
|
|
import Foundation
|
|
|
|
|
2025-01-11 03:24:22 +01:00
|
|
|
public struct FileService: FileServicing {
|
2025-01-11 01:26:26 +01:00
|
|
|
|
|
|
|
// MARK: Properties
|
|
|
|
|
|
|
|
private let fileManager: FileManager
|
|
|
|
|
|
|
|
// MARK: Initialisers
|
|
|
|
|
2025-01-11 03:24:22 +01:00
|
|
|
public init(fileManager: FileManager = .default) {
|
2025-01-11 01:26:26 +01:00
|
|
|
self.fileManager = fileManager
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Computed
|
|
|
|
|
2025-01-11 03:24:22 +01:00
|
|
|
public var currentFolder: URL {
|
2025-01-11 01:26:26 +01:00
|
|
|
get async {
|
2025-01-11 03:24:22 +01:00
|
|
|
.init(at: fileManager.currentDirectoryPath)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-01-11 04:44:02 +01:00
|
|
|
// MARK: Functions
|
2025-01-14 23:52:33 +01:00
|
|
|
|
|
|
|
public func copyItem(from source: URL, to destination: URL) async throws (FileServiceError) {
|
|
|
|
guard try await isItemExists(at: source) else {
|
|
|
|
throw FileServiceError.itemNotExists
|
|
|
|
}
|
|
|
|
guard try await !isItemExists(at: destination) else {
|
|
|
|
throw FileServiceError.itemAlreadyExists
|
|
|
|
}
|
|
|
|
|
|
|
|
do {
|
|
|
|
try fileManager.copyItem(at: source, to: destination)
|
|
|
|
} catch {
|
|
|
|
throw FileServiceError.itemNotCopied
|
|
|
|
}
|
|
|
|
}
|
2025-01-11 04:44:02 +01:00
|
|
|
|
2025-01-13 23:27:50 +01:00
|
|
|
public func createFolder(at location: URL) async throws (FileServiceError) {
|
|
|
|
guard try await !isItemExists(at: location) else {
|
|
|
|
throw FileServiceError.itemAlreadyExists
|
2025-01-11 05:08:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
do {
|
2025-01-13 23:27:50 +01:00
|
|
|
try fileManager.createDirectory(at: location, withIntermediateDirectories: true)
|
2025-01-11 05:08:06 +01:00
|
|
|
} catch {
|
|
|
|
throw FileServiceError.folderNotCreated
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-01-13 23:27:50 +01:00
|
|
|
public func deleteItem(at location: URL) async throws (FileServiceError) {
|
|
|
|
guard try await isItemExists(at: location) else {
|
|
|
|
throw FileServiceError.itemNotExists
|
2025-01-11 04:44:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
do {
|
2025-01-13 23:27:50 +01:00
|
|
|
try fileManager.removeItem(at: location)
|
2025-01-11 04:44:02 +01:00
|
|
|
} catch {
|
2025-01-13 23:27:50 +01:00
|
|
|
throw FileServiceError.itemNotDeleted
|
2025-01-11 04:44:02 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-01-13 23:27:50 +01:00
|
|
|
public func isItemExists(at location: URL) async throws (FileServiceError) -> Bool {
|
|
|
|
guard location.isFileURL else {
|
|
|
|
throw FileServiceError.itemNotFileURL
|
2025-01-11 03:24:22 +01:00
|
|
|
}
|
|
|
|
|
2025-01-13 23:27:50 +01:00
|
|
|
let filePath = location.pathString
|
2025-01-11 03:24:22 +01:00
|
|
|
|
|
|
|
return fileManager.fileExists(atPath: filePath)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|