Repository Public License
1// ORIX Clean — Packages/ORIXCleanCore/Tests/ORIXCleanCoreTests/Fixtures.swift2// Description: Disposable directories and disk images for tests. Nothing here touches real user data.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import Darwin5import Foundation6@testable import ORIXCleanCore78final class Sandbox: @unchecked Sendable {9 let root: String10 init(_ label: String = "t") {11 let base = (NSTemporaryDirectory() as NSString).appendingPathComponent("orixclean-tests-\(label)-\(UUID().uuidString.prefix(8))")12 try! FileManager.default.createDirectory(atPath: base, withIntermediateDirectories: true)13 root = (base as NSString).resolvingSymlinksInPath14 }1516 deinit {17 _ = try? FileManager.default.subpathsOfDirectory(atPath: root).forEach { chmod(root + "/" + $0, 0o700) }18 try? FileManager.default.removeItem(atPath: root)19 }2021 func path(_ rel: String) -> String { root + "/" + rel }2223 @discardableResult24 func dir(_ rel: String) -> String {25 try! FileManager.default.createDirectory(atPath: path(rel), withIntermediateDirectories: true)26 return path(rel)27 }2829 @discardableResult30 func file(_ rel: String, size: Int, seed: UInt8 = 1) -> String {31 dir((rel as NSString).deletingLastPathComponent)32 var bytes = [UInt8](repeating: 0, count: size)33 var x = UInt32(seed) &* 2654435761 &+ 1234534 for i in 0 ..< size { x = x &* 1664525 &+ 1013904223; bytes[i] = UInt8(truncatingIfNeeded: x >> 24) }35 FileManager.default.createFile(atPath: path(rel), contents: Data(bytes))36 return path(rel)37 }3839 @discardableResult40 func text(_ rel: String, _ s: String) -> String {41 dir((rel as NSString).deletingLastPathComponent)42 FileManager.default.createFile(atPath: path(rel), contents: Data(s.utf8))43 return path(rel)44 }4546 func scan(_ rel: String = "", options: ScanOptions = ScanOptions()) throws -> ScanResult {47 try FileScanner(root: rel.isEmpty ? root : path(rel), options: options).run()48 }49}5051func allocated(_ path: String) -> Int64 {52 var st = stat()53 lstat(path, &st)54 return Int64(st.st_blocks) * 51255}5657@discardableResult58func shell(_ launch: String, _ args: [String]) -> (status: Int32, output: String) {59 let p = Process()60 p.executableURL = URL(fileURLWithPath: launch)61 p.arguments = args62 let pipe = Pipe()63 p.standardOutput = pipe64 p.standardError = pipe65 do { try p.run() } catch { return (-1, "\(error)") }66 let data = pipe.fileHandleForReading.readDataToEndOfFile()67 p.waitUntilExit()68 return (p.terminationStatus, String(decoding: data, as: UTF8.self))69}7071/// A small APFS disk image mounted at a private mount point.72final class TestVolume: @unchecked Sendable {73 let image: String74 let mountPoint: String75 private(set) var mounted = false7677 init?(sizeMB: Int = 24, readOnlyAfter populate: ((String) -> Void)? = nil, mountAt: String? = nil) {78 let base = (NSTemporaryDirectory() as NSString).appendingPathComponent("orixclean-vol-\(UUID().uuidString.prefix(8))")79 image = base + ".dmg"80 mountPoint = mountAt ?? ((base + "-mnt") as NSString).resolvingSymlinksInPath81 try? FileManager.default.createDirectory(atPath: mountPoint, withIntermediateDirectories: true)82 guard shell("/usr/bin/hdiutil", ["create", "-size", "\(sizeMB)m", "-fs", "APFS", "-volname", "ORIXTest", "-quiet", image]).status == 0 else { return nil }83 guard attach(readOnly: false) else { return nil }84 if let populate {85 populate(mountPoint)86 detach()87 guard attach(readOnly: true) else { return nil }88 }89 }9091 func attach(readOnly: Bool) -> Bool {92 var args = ["attach", image, "-nobrowse", "-mountpoint", mountPoint, "-quiet", "-owners", "on"]93 if readOnly { args.append("-readonly") }94 mounted = shell("/usr/bin/hdiutil", args).status == 095 return mounted96 }9798 func detach() {99 if mounted { shell("/usr/bin/hdiutil", ["detach", mountPoint, "-force", "-quiet"]); mounted = false }100 }101102 deinit {103 detach()104 try? FileManager.default.removeItem(atPath: image)105 try? FileManager.default.removeItem(atPath: mountPoint)106 }107}108109struct FakeTrasher: Trasher {110 var failing: Set<String> = []111 var error: NSError = NSError(domain: NSCocoaErrorDomain, code: NSFileWriteNoPermissionError)112 let bin: String113 func trash(_ url: URL) throws -> URL? {114 if failing.contains(url.path) { throw error }115 let dest = URL(fileURLWithPath: bin + "/" + UUID().uuidString + "-" + url.lastPathComponent)116 try FileManager.default.moveItem(at: url, to: dest)117 return dest118 }119120 func remove(_ url: URL) throws {121 if failing.contains(url.path) { throw error }122 try FileManager.default.removeItem(at: url)123 }124}125126func item(_ path: String, category: CleanupCategory = .other, risk: Risk = .low, verify: String? = nil, close: [String] = []) -> CleanupItem {127 CleanupItem(path: path, category: category, risk: risk, reason: "test", consequence: "test", measurement: Measure.item(path) ?? Measurement(),128 closeFirst: close, verifyAgainst: verify)129}130