diff --git a/Sources/KamaalUtils/FileClerk.swift b/Sources/KamaalUtils/FileClerk.swift new file mode 100644 index 0000000..5ee9e5b --- /dev/null +++ b/Sources/KamaalUtils/FileClerk.swift @@ -0,0 +1,55 @@ +// +// FileClerk.swift +// +// +// Created by Kamaal M Farah on 06/01/2024. +// + +import Foundation + +public struct FileClerk { + private static let fileManager = FileManager.default + + private init() { } + + public static let libraryDirectory = fileManager.urls(for: .libraryDirectory, in: .userDomainMask).first + + @available(macOS 13.0, *) + public static func moveFolderContent(from sourceFolder: URL, to destinationFolder: URL) throws { + let sourceFolderContent = try fileManager.contentsOfDirectory( + at: sourceFolder, + includingPropertiesForKeys: nil, + options: [] + ) + for content in sourceFolderContent { + let destinationURL = destinationFolder.appending(path: content.lastPathComponent) + guard !fileManager.fileExists(atPath: destinationURL.path) else { continue } + + try fileManager.moveItem(at: content, to: destinationURL) + } + } + + public static func deleteItem(at url: URL) throws { + try fileManager.removeItem(at: url) + } + + public static func getOrCreateDirectory(at url: URL) throws -> URL { + guard !fileManager.fileExists(atPath: url.path) else { return url } + + try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) + return url + } + + public static func createFile(with data: Data, at url: URL) { + fileManager.createFile(atPath: url.path, contents: data) + } + + @available(macOS 13.0, *) + public static func getOrCreateSubfolders(atBase baseURL: URL, subFolderPaths: [String]) throws -> URL { + var currentPath = baseURL + for subFolderPath in subFolderPaths { + currentPath = try getOrCreateDirectory(at: currentPath.appending(path: subFolderPath)) + } + return currentPath + } +}