import Foundation /// A throwaway folder, removed on deinit. final class TempDirectory { let root: URL init() throws { root = FileManager.default.temporaryDirectory .appendingPathComponent("helder-test-\(UUID().uuidString)") .resolvingSymlinksInPath() try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) } deinit { try? FileManager.default.removeItem(at: root) } func url(_ path: String) -> URL { root.appendingPathComponent(path) } /// Writes a file relative to the root, creating folders as needed. func write(_ path: String, _ contents: String) throws { try write(path, Data(contents.utf8)) } func write(_ path: String, _ data: Data) throws { let url = url(path) try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) try data.write(to: url) } func mkdir(_ path: String) throws { try FileManager.default.createDirectory(at: url(path), withIntermediateDirectories: true) } func read(_ path: String) throws -> String { try String(contentsOf: url(path), encoding: .utf8) } func exists(_ path: String) -> Bool { FileManager.default.fileExists(atPath: url(path).path) } }