Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Wrap the tests' long lines at 120 columns
Țugui Dragoș936a96484b6c
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppCatalogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppCatalogTests.swiftindex d8fd124b..1860f00b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppCatalogTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppCatalogTests.swift@@ -6,7 +6,12 @@ struct AppCatalogTests {private let yesterday = Date(timeIntervalSince1970: 1_800_000_000)private let today = Date(timeIntervalSince1970: 1_800_086_400)- private func app(_ name: String, version: String = "1.0", lastUsed: Date? = nil, isRecorded: Bool = true) -> InstalledApp {+ private func app(+ _ name: String,+ version: String = "1.0",+ lastUsed: Date? = nil,+ isRecorded: Bool = true+ ) -> InstalledApp {InstalledApp(url: URL(filePath: "/Applications/\(name).app", directoryHint: .isDirectory),bundleIdentifier: "org.example.\(name)", name: name, version: version, lastUsedDate: lastUsed,diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppExtensionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppExtensionsTests.swiftindex 931caeb5..89a6d1ce 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppExtensionsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppExtensionsTests.swift@@ -75,7 +75,13 @@ struct AppExtensionsTests {// The same folder reached through a link is still this copy.let link = directory.url.appending(path: "Link.appex")try FileManager.default.createSymbolicLink(at: link, withDestinationURL: own)- #expect(!AppExtensions.runsAnotherCopy(of: identifier, than: link, in: listing("+", own.path(percentEncoded: false))))+ #expect(+ !AppExtensions.runsAnotherCopy(+ of: identifier,+ than: link,+ in: listing("+", own.path(percentEncoded: false))+ )+ )// Unless the user turned the extension on, the answer is no, even when the listed copy is another one.#expect(!runsAnother(listing("-", other.path(percentEncoded: false))))#expect(!runsAnother(listing(" ", other.path(percentEncoded: false))))@@ -102,7 +108,9 @@ struct AppExtensionsTests {*\t*\tTC3Q7MAJXF\tcom.adguard.mac.adguard.network-extension (2.19.0/2258)\tAdGuard Network Extension\t[activated enabled]\t*\t2MMRE5MTB8\tcom.obsproject.obs-studio.mac-camera-extension (32.2.2/31845296735)\tOBS Virtual Camera\t[activated waiting for user]"""- let parsed = rows.split(whereSeparator: \.isNewline).compactMap { AppExtensions.parseSystemExtension(String($0)) }+ let parsed = rows.split(whereSeparator: \.isNewline).compactMap {+ AppExtensions.parseSystemExtension(String($0))+ }#expect(parsed.count == 2, "the header row was read as an extension")#expect(parsed.first?.identifier == "com.adguard.mac.adguard.network-extension")@@ -121,7 +129,9 @@ struct AppExtensionsTests {*\t*\tTC3Q7MAJXF\tcom.example.filter (1.0/100)\tExample Filter\t[activated waiting to upgrade]\t\tTC3Q7MAJXF\tcom.example.filter (2.0/200)\tExample Filter\t[activated enabled]"""- let parsed = rows.split(whereSeparator: \.isNewline).compactMap { AppExtensions.parseSystemExtension(String($0)) }+ let parsed = rows.split(whereSeparator: \.isNewline).compactMap {+ AppExtensions.parseSystemExtension(String($0))+ }#expect(parsed.map(\.version) == ["1.0/100", "2.0/200"])let made = parsed.map { row in@@ -147,7 +157,10 @@ struct AppExtensionsTests {],["identifier": "com.example.broken"],]]- let url = try directory.file("db.plist", contents: PropertyListSerialization.data(fromPropertyList: database, format: .xml, options: 0))+ let url = try directory.file(+ "db.plist",+ contents: PropertyListSerialization.data(fromPropertyList: database, format: .xml, options: 0)+ )let records = AppExtensions.systemExtensionRecords(at: url)@@ -227,7 +240,10 @@ struct AppExtensionsTests {#expect(await AppExtensions.scan(exclusions: .none, run: appsOnly).unanswered == [.systemExtension])#expect(await AppExtensions.scan(exclusions: .none, run: systemOnly).unanswered == [.appExtension])- #expect(await AppExtensions.scan(exclusions: .none, run: { _, _ in nil }).unanswered == Set(AppExtension.Kind.allCases))+ #expect(+ await AppExtensions.scan(exclusions: .none, run: { _, _ in nil }).unanswered+ == Set(AppExtension.Kind.allCases)+ )#expect(await AppExtensions.scan(exclusions: .none, run: both).unanswered.isEmpty)}@@ -262,7 +278,9 @@ struct AppExtensionsTests {let scan = await AppExtensions.scan()let found = scan.extensions#expect(scan.unanswered.isEmpty, "this Mac's listing was not read whole")- #expect(found.allSatisfy { $0.url.map { !AppExtensions.isTheSystemsOwn($0.path(percentEncoded: false)) } ?? true })+ #expect(+ found.allSatisfy { $0.url.map { !AppExtensions.isTheSystemsOwn($0.path(percentEncoded: false)) } ?? true }+ )#expect(Set(found.map(\.id)).count == found.count, "the same extension was listed twice")}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swiftindex 7e13abee..61cc897b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift@@ -95,7 +95,10 @@ struct AppInspectorTests {try plist(["CFBundleIdentifier": "org.example.unindexed"], at: "Unindexed.app/Contents/Info.plist", in: directory)let bundle = directory.url.appending(path: "Unindexed.app")let written = Date(timeIntervalSince1970: 1_700_000_000)- try FileManager.default.setAttributes([.modificationDate: written], ofItemAtPath: bundle.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.modificationDate: written],+ ofItemAtPath: bundle.path(percentEncoded: false)+ )let app = try #require(AppInspector.inspect(bundle))@@ -216,12 +219,18 @@ struct AppInspectorTests {/// Copies `original`, an app Apple signed, and writes `identifier` into the copy's `Info.plist` when one is/// given. That breaks the signature, but what it says, Apple's team included, can still be read as a string.- private func copy(of original: String, claiming identifier: String?, in directory: borrowing TemporaryDirectory) throws -> URL {+ private func copy(+ of original: String,+ claiming identifier: String?,+ in directory: borrowing TemporaryDirectory+ ) throws -> URL {let copy = directory.url.appending(path: UUID().uuidString + ".app", directoryHint: .isDirectory)try FileManager.default.copyItem(at: URL(filePath: original), to: copy)if let identifier {let info = copy.appending(path: "Contents/Info.plist")- var contents = try #require(try PropertyListSerialization.propertyList(from: Data(contentsOf: info), format: nil) as? [String: Any])+ var contents = try #require(+ try PropertyListSerialization.propertyList(from: Data(contentsOf: info), format: nil) as? [String: Any]+ )contents["CFBundleIdentifier"] = identifiertry PropertyListSerialization.data(fromPropertyList: contents, format: .xml, options: 0).write(to: info)}@@ -255,7 +264,11 @@ struct AppInspectorTests {}@discardableResult- private func plist(_ dictionary: [String: String], at path: String, in directory: borrowing TemporaryDirectory) throws -> URL {+ private func plist(+ _ dictionary: [String: String],+ at path: String,+ in directory: borrowing TemporaryDirectory+ ) throws -> URL {let data = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: 0)let url = try directory.file(path)try data.write(to: url)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppMemoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppMemoryTests.swiftindex 1327888b..a4380c0f 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppMemoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppMemoryTests.swift@@ -100,7 +100,8 @@ struct AppMemoryTests {let remembered = await memory.remember([app("Arc", "company.thebrowser.Browser")])#expect(Set(remembered.map(\.bundleIdentifier)) == ["net.shinyfrog.bear", "dev.zed.Zed", "company.thebrowser.Browser"])- let kept = try FileManager.default.contentsOfDirectory(atPath: directory.url.path(percentEncoded: false)).filter { $0.contains("damaged") }+ let kept = try FileManager.default.contentsOfDirectory(atPath: directory.url.path(percentEncoded: false)).filter+ { $0.contains("damaged") }#expect(kept.count == 1, "the file as it was is not kept: \(kept)")}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppOrderTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppOrderTests.swiftindex 129ec562..df781062 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppOrderTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppOrderTests.swift@@ -5,7 +5,12 @@ import Testingstruct AppOrderTests {private let now = Date(timeIntervalSince1970: 1_800_000_000)- private func app(_ name: String, lastUsed: Date? = nil, isRecorded: Bool = true, added: Date? = nil) -> InstalledApp {+ private func app(+ _ name: String,+ lastUsed: Date? = nil,+ isRecorded: Bool = true,+ added: Date? = nil+ ) -> InstalledApp {InstalledApp(url: URL(filePath: "/Applications/\(name).app"), bundleIdentifier: "com.example.\(name)", name: name,lastUsedDate: lastUsed, isUseRecorded: isRecorded, dateAdded: addeddiff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swiftindex dd38e134..30ca299f 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift@@ -57,7 +57,12 @@ struct AppResetTests {try directory.file("Library/Preferences/com.example.app.plist", bytes: 4096)let exclusions = Exclusions(bundleIdentifiers: ["com.example.app"])- let reset = await AppReset.prepare(app(), installedApps: [app()], exclusions: exclusions, environment: home(directory))+ let reset = await AppReset.prepare(+ app(),+ installedApps: [app()],+ exclusions: exclusions,+ environment: home(directory)+ )#expect(reset.items.isEmpty)#expect(reset.suggestedSelection.isEmpty)@@ -253,7 +258,12 @@ struct AppResetTests {try directory.file("Library/Containers/com.example.app/Data/Library/Caches/cache", bytes: 400_000)try directory.file("Library/Containers/com.example.app/Data/Library/Logs/app.log", bytes: 4096)- let reset = await AppReset.prepare(app(), installedApps: [app()], exclusions: .none, environment: home(directory)) { url in+ let reset = await AppReset.prepare(+ app(),+ installedApps: [app()],+ exclusions: .none,+ environment: home(directory)+ ) { url inurl.lastPathComponent == "Caches" ? nil : await FileSize.contents(of: url)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackDuplicateTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackDuplicateTests.swiftindex 288db0b2..2f7774b9 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackDuplicateTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackDuplicateTests.swift@@ -15,11 +15,16 @@ struct AttackDuplicateTests {private func scan(_ directory: borrowing TemporaryDirectory, folders: [String]) async throws -> DuplicateScan {let home = directory.url.appending(path: "home", directoryHint: .isDirectory)- let options = DuplicateScanOptions(folders: folders.map { directory.url.appending(path: $0, directoryHint: .isDirectory) })+ let options = DuplicateScanOptions(+ folders: folders.map { directory.url.appending(path: $0, directoryHint: .isDirectory) }+ )return try await DuplicateFinder(homeDirectory: home).scan(options)}- private func service(_ directory: borrowing TemporaryDirectory, onTrash: @escaping @Sendable () -> Void = {}) throws -> TrashService {+ private func service(+ _ directory: borrowing TemporaryDirectory,+ onTrash: @escaping @Sendable () -> Void = {}+ ) throws -> TrashService {let trash = try directory.directory("FakeTrash")let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),@@ -71,7 +76,11 @@ struct AttackDuplicateTests {let found = try await scan(directory, folders: ["home"])let group = try #require(found.groups.first)- let result = await DuplicateRemoval.trash(Set(group.files.map(\.url)), from: found, using: try service(directory))+ let result = await DuplicateRemoval.trash(+ Set(group.files.map(\.url)),+ from: found,+ using: try service(directory)+ )#expect(result.trashed.isEmpty)#expect(result.failures.map(\.reason) == [.lastCopy, .lastCopy])@@ -105,7 +114,9 @@ struct AttackDuplicateTests {_ = await DuplicateRemoval.trash(selection, from: found, using: trashService)- let left = group.files.map(\.url).filter { FileManager.default.fileExists(atPath: $0.path(percentEncoded: false)) }+ let left = group.files.map(\.url).filter {+ FileManager.default.fileExists(atPath: $0.path(percentEncoded: false))+ }#expect(!left.isEmpty, "ATTACK SUCCEEDED: the group lost every copy")}@@ -145,7 +156,13 @@ struct AttackDuplicateTests {// Two rules stop it, and each is checked: the walk does not go into a library, and the guard refuses what// is inside one.#expect(DuplicateFinder.isAUserLibrary(directory.url.appending(path: "home/Movies/Old.\(kind)")))- #expect(!RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ #expect(+ !RemovalGuard(+ environment: SearchEnvironment(+ homeDirectory: home,+ rootDirectory: directory.url.appending(path: "root")+ )+ ).allowsRemoval(of: directory.url.appending(path: "home/Movies/Old.\(kind)/clip.mov")))}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swiftindex d91d6134..3560deec 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swift@@ -48,7 +48,12 @@ struct AttackPathProducerTests {leftoverPatterns: ["~/Library/mobile documents/iCloud~com~acme~Notes"])- let uninstallation = await Uninstallation.prepare(app, installedApps: [app], casks: [cask], environment: environment(directory))+ let uninstallation = await Uninstallation.prepare(+ app,+ installedApps: [app],+ casks: [cask],+ environment: environment(directory)+ )let named = uninstallation.scan.leftovers.map { $0.url.path(percentEncoded: false) }#expect(named.isEmpty, "the cask path was accepted: \(named)")@@ -90,7 +95,8 @@ struct AttackPathProducerTests {let offered = environments.flatMap(\.locations).map { $0.url.path(percentEncoded: false) }#expect(!offered.contains { $0.hasSuffix("/.config/gcloud/logs") }, "the developer page offers a path that lands in iCloud Drive")- guard let url = environments.flatMap(\.locations).first(where: { $0.url.lastPathComponent == "logs" })?.url else { return }+ guard let url = environments.flatMap(\.locations).first(where: { $0.url.lastPathComponent == "logs" })?.url+ else { return }let trash = try directory.directory("FakeTrash")let service = TrashService(environment: environment(directory)) { url inlet destination = trash.appending(path: url.lastPathComponent)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swiftindex 4274c89e..2b6bc49d 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift@@ -93,7 +93,9 @@ struct AttackRemovalGuardTests {#expect(inode(real.path(percentEncoded: false)) != nil)#expect(inode(real.path(percentEncoded: false))! == inode(disguised.path(percentEncoded: false))!)- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )#expect(!guardian.allowsRemoval(of: real), "canonical spelling must be refused")#expect(!guardian.allowsRemoval(of: disguised), "ATTACK SUCCEEDED: lower-cased iCloud Drive is allowed")}@@ -103,7 +105,9 @@ struct AttackRemovalGuardTests {let directory = try TemporaryDirectory()let home = directory.url.appending(path: "home", directoryHint: .isDirectory)try directory.directory("home/Library")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let disguises = ["Library/mobile documents/com~apple~CloudDocs/Thesis.pages",@@ -154,7 +158,9 @@ struct AttackRemovalGuardTests {#expect(FileManager.default.fileExists(atPath: disguised.path(percentEncoded: false)), "the kernel reaches the iCloud file")#expect(inode(real.path(percentEncoded: false))! == inode(disguised.path(percentEncoded: false))!)- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )#expect(!guardian.allowsRemoval(of: disguised), "ATTACK SUCCEEDED: `..` out of a link reaches iCloud Drive")}@@ -167,7 +173,9 @@ struct AttackRemovalGuardTests {try link("../Mobile Documents/com~apple~CloudDocs", at: home.appending(path: "Library/Caches/Vendor").path(percentEncoded: false))let disguised = home.appending(path: "Library/Caches/Vendor/Thesis.pages")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )#expect(!guardian.allowsRemoval(of: disguised), "ATTACK SUCCEEDED: a symlinked cache folder reaches iCloud Drive")}@@ -233,7 +241,9 @@ struct AttackRemovalGuardTests {let home = directory.url.appending(path: "home", directoryHint: .isDirectory)try directory.file("home/Library/Keychains/login.keychain-db")try directory.file("home/Library/Mobile Documents/com~apple~CloudDocs/Thesis.pages")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )#expect(!guardian.allowsRemoval(of: home.appending(path: "Library")), "ATTACK SUCCEEDED: the folder holding the keychains is allowed")#expect(!guardian.allowsRemoval(of: home), "ATTACK SUCCEEDED: the home folder is allowed")@@ -255,7 +265,9 @@ struct AttackRemovalGuardTests {try directory.file("home/.local/share/local/state.json")try directory.file("home/.kube/config")try directory.file("home/.zshrc")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )for item in [".local", ".config", ".cache", ".kube", ".kube/config", ".zshrc", ".gitconfig", ".npmrc"] {#expect(!guardian.allowsRemoval(of: home.appending(path: item)), "\(item) may be removed")@@ -278,7 +290,9 @@ struct AttackRemovalGuardTests {try directory.file("home/.electrum/blockchain_headers", bytes: 4_096)try directory.file("home/Library/Application Support/Bitcoin/wallets/wallet.dat")try directory.file("home/Library/Application Support/Bitcoin/blocks/blk00000.dat", bytes: 4_096)- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let homePath = home.path(percentEncoded: false)for key in ProtectedData.homeKeys + ProtectedData.walletKeys {@@ -306,7 +320,9 @@ struct AttackRemovalGuardTests {try directory.directory("home/Library/Messages")try directory.directory("home/Library/Caches")try link(cloud.path(percentEncoded: false), at: home.appending(path: "Library/Caches/Vendor").path(percentEncoded: false))- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let destinations = ["Library/Caches/Vendor/not-there-yet.pdf",@@ -328,7 +344,9 @@ struct AttackRemovalGuardTests {let home = directory.url.appending(path: "home", directoryHint: .isDirectory)try directory.file("home/Library/Application Support/Bitcoin/wallets/default/wallet.dat")try directory.file("home/Library/Messages/chat.db")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let folded = ["Library/Application Support/Bitcoin/walletſ",@@ -350,8 +368,13 @@ struct AttackRemovalGuardTests {let thesis = try directory.file("disk/me/Library/Mobile Documents/com~apple~CloudDocs/Thesis.pages")let cache = try directory.file("disk/me/Library/Caches/com.example.app/cache.db")let home = directory.url.appending(path: "home", directoryHint: .isDirectory)- try link(directory.url.appending(path: "disk/me").path(percentEncoded: false), at: directory.url.appending(path: "home").path(percentEncoded: false))- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ try link(+ directory.url.appending(path: "disk/me").path(percentEncoded: false),+ at: directory.url.appending(path: "home").path(percentEncoded: false)+ )+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )#expect(!guardian.allowsRemoval(of: thesis), "ATTACK SUCCEEDED: iCloud Drive is allowed under the name of the disk it is on")#expect(!guardian.allowsRemoval(of: home.appending(path: "Library/Mobile Documents/com~apple~CloudDocs/Thesis.pages")))@@ -371,7 +394,9 @@ struct AttackRemovalGuardTests {try directory.directory("home/Library/Application Support")let bitcoin = disk.appending(path: "Bitcoin", directoryHint: .isDirectory)try link(bitcoin.path(percentEncoded: false), at: home.appending(path: "Library/Application Support/Bitcoin").path(percentEncoded: false))- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )for item in [key, wallet, disk.appending(path: "Bitcoin/wallets"), bitcoin, disk] {#expect(!guardian.allowsRemoval(of: item), "ATTACK SUCCEEDED: \(item.path(percentEncoded: false)) may be removed under the name of its disk")@@ -388,7 +413,9 @@ struct AttackRemovalGuardTests {let harmless = try directory.file("elsewhere/note.txt")try link(harmless.path(percentEncoded: false), at: mail.appending(path: "V10").path(percentEncoded: false))try link(mail.path(percentEncoded: false), at: home.appending(path: "shortcut").path(percentEncoded: false))- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )#expect(!guardian.allowsRemoval(of: home.appending(path: "shortcut/V10")), "ATTACK SUCCEEDED: a file inside Mail can be removed through a link")}@@ -400,7 +427,9 @@ struct AttackRemovalGuardTests {let home = directory.url.appending(path: "home", directoryHint: .isDirectory)try directory.directory("home/Library/Group Containers")try directory.directory("home/Library/Containers")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let homePath = home.path(percentEncoded: false)let stores = [@@ -442,7 +471,9 @@ struct AttackRemovalGuardTests {try directory.file("home/Library/Containers/com.example.notes/Data/Library/Caches/cache.db")try directory.file("home/Library/Containers/com.example.empty/Data/Documents/.DS_Store")try directory.file("home/Library/Containers/com.example.empty/Data/Library/Caches/cache.db")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )for path in ["Library/Containers/com.example.notes", "Library/containers/COM.EXAMPLE.NOTES/data", "Library/Containers/com.example.notes/Data/Documents/thesis.txt"] {#expect(!guardian.allowsRemoval(of: home.appending(path: path)), "ATTACK SUCCEEDED: \(path) goes, and the thesis with it")@@ -466,7 +497,9 @@ struct AttackRemovalGuardTests {@Test func whatAnotherAccountKeeps() throws {let directory = try TemporaryDirectory()let home = directory.url.appending(path: "home", directoryHint: .isDirectory)- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )for path in ["/Users/somebody/Library/Keychains/login.keychain-db", "/Users/somebody/Library/Mail", "/Users/somebody/.ssh/id_ed25519", "/Users/somebody/Library"] {#expect(!guardian.allowsRemoval(of: URL(filePath: path)), "ATTACK SUCCEEDED: \(path) is allowed")@@ -482,7 +515,9 @@ struct AttackRemovalGuardTests {try directory.file("home/Movies/Archive/Family.photoslibrary/database/Photos.sqlite")try directory.file("home/Movies/Old/2019/Trip.tvlibrary/Library.db")try directory.file("home/Movies/Clips/holiday.mov")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )for path in ["Movies/Archive", "Movies/Old", "Movies/Old/2019", "Movies/Archive/Family.photoslibrary"] {#expect(!guardian.allowsRemoval(of: home.appending(path: path)), "ATTACK SUCCEEDED: \(path) goes, and a library with it")@@ -500,7 +535,9 @@ struct AttackRemovalGuardTests {try directory.file("home/Library/Caches/JetBrains/IntelliJIdea2026.2/caches/names.dat")try directory.file("home/Library/Caches/deno/location_data/abc/kv.sqlite3")try directory.file("home/Library/Caches/deno/deps/https/x.ts")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let kept = ["Library/Caches/JetBrains", "Library/Caches/JetBrains/IntelliJIdea2026.2",@@ -525,7 +562,9 @@ struct AttackRemovalGuardTests {let mail = try directory.directory("home/Library/Mail")let letter = try directory.file("home/Library/Mail/V10/letter.emlx")let cache = try directory.file("home/Library/Caches/com.example.app/cache.db")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let (device, number) = try #require(inode(mail.path(percentEncoded: false)))let library = try #require(inode(home.appending(path: "Library").path(percentEncoded: false)))@@ -560,7 +599,9 @@ struct AttackRemovalGuardTests {let directory = try TemporaryDirectory()let home = directory.url.appending(path: "home", directoryHint: .isDirectory)let letter = try directory.file("home/Library/Mail/\u{301}letter.emlx")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )#expect(!guardian.allowsRemoval(of: letter), "ATTACK SUCCEEDED: a letter in Mail whose name begins with a combining mark")#expect(!guardian.allowsRemoval(of: home.appending(path: "Library/Mail/\u{301}not there yet")), "ATTACK SUCCEEDED: Put Back into Mail")@@ -571,7 +612,9 @@ struct AttackRemovalGuardTests {let directory = try TemporaryDirectory()let home = directory.url.appending(path: "home", directoryHint: .isDirectory)try directory.directory("home/Library/Preferences/ByHost")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let homePath = home.path(percentEncoded: false)let global = [diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackScannerTests.swiftindex e59f806b..e42159fe 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackScannerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackScannerTests.swift@@ -102,7 +102,11 @@ struct AttackScannerTests {let directory = try TemporaryDirectory()try directory.file("home/Library/Group Containers/group.is.workflow.shortcuts/Shortcuts.sqlite")try directory.file("home/Library/Group Containers/group.com.gone.app/data.db")- let scanner = OrphanScanner(environment: environment(directory), isRegisteredApp: { _ in false }, systemApps: [])+ let scanner = OrphanScanner(+ environment: environment(directory),+ isRegisteredApp: { _ in false },+ systemApps: []+ )let found = await scanner.scan(installedApps: []).groups.map(\.identifier)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackSideEffectTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackSideEffectTests.swiftindex a88c65ce..25dbc929 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackSideEffectTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackSideEffectTests.swift@@ -25,9 +25,15 @@ struct AttackSideEffectTests {/// copies are real files that declare a job, so only where they sit can refuse them.@Test func trashingABackupCopyStopsTheLiveAgent() throws {let directory = try TemporaryDirectory()- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )func plist(_ path: String, label: String) throws -> URL {- try directory.file(path, contents: PropertyListSerialization.data(fromPropertyList: ["Label": label], format: .xml, options: 0))+ try directory.file(+ path,+ contents: PropertyListSerialization.data(fromPropertyList: ["Label": label], format: .xml, options: 0)+ )}let live = try plist("home/Library/LaunchAgents/com.vendor.updater.plist", label: "com.vendor.updater")let copies = [@@ -45,7 +51,10 @@ struct AttackSideEffectTests {/// that declares it must not stop the one macOS runs.@Test func movingACopyOfMacOSsOwnAgentStopsNothing() throws {let directory = try TemporaryDirectory()- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )let copy = try directory.file("home/Library/LaunchAgents/ssh.plist",contents: PropertyListSerialization.data(fromPropertyList: ["Label": "com.openssh.ssh-agent"], format: .xml, options: 0)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swiftindex 046b958b..f7b1d0ca 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift@@ -19,12 +19,31 @@ struct BackgroundItemActionsTests {let plist = URL(filePath: "/Users/x/Library/LaunchAgents/com.example.agent.plist")let marked = { (_: URL) in true }- #expect(BackgroundItemActions.plan(toStart: item(state: .notLoaded, plist: plist), isRefusedByLaunchd: marked) == .blockedByQuarantine)- #expect(BackgroundItemActions.plan(toStart: item(state: .loaded, plist: plist), isRefusedByLaunchd: marked) == .kickstart)- #expect(BackgroundItemActions.plan(toStart: item(state: .running(pid: 42), plist: plist), isRefusedByLaunchd: marked) == .kickstart)- #expect(BackgroundItemActions.plan(toStart: item(state: .notLoaded, plist: plist), isRefusedByLaunchd: { _ in false }) == .bootstrap(plist))+ #expect(+ BackgroundItemActions.plan(toStart: item(state: .notLoaded, plist: plist), isRefusedByLaunchd: marked)+ == .blockedByQuarantine+ )+ #expect(+ BackgroundItemActions.plan(toStart: item(state: .loaded, plist: plist), isRefusedByLaunchd: marked)+ == .kickstart+ )+ #expect(+ BackgroundItemActions.plan(+ toStart: item(state: .running(pid: 42), plist: plist),+ isRefusedByLaunchd: marked+ ) == .kickstart+ )+ #expect(+ BackgroundItemActions.plan(+ toStart: item(state: .notLoaded, plist: plist),+ isRefusedByLaunchd: { _ in false }+ ) == .bootstrap(plist)+ )// Nothing to load from: an app submitted this one, and launchctl is asked for it by name.- #expect(BackgroundItemActions.plan(toStart: item(state: .notLoaded, plist: nil), isRefusedByLaunchd: marked) == .kickstart)+ #expect(+ BackgroundItemActions.plan(toStart: item(state: .notLoaded, plist: nil), isRefusedByLaunchd: marked)+ == .kickstart+ )}/// Starting, stopping and switching a job go by its label, so a label macOS itself uses would reach macOS's own@@ -78,7 +97,12 @@ struct BackgroundItemActionsTests {let plist = URL(filePath: "/Users/x/Library/LaunchAgents/com.example.agent.plist")let steps = Mutex<[String]>([])func service(refusing: Bool) -> TrashService {- TrashService(environment: SearchEnvironment(homeDirectory: URL(filePath: "/Users/x"), rootDirectory: URL(filePath: "/"))) { url in+ TrashService(+ environment: SearchEnvironment(+ homeDirectory: URL(filePath: "/Users/x"),+ rootDirectory: URL(filePath: "/")+ )+ ) { url insteps.withLock { $0.append("move") }if refusing { throw TrashService.RefusedOnceHeld(refusal: .protectedLocation) }return url@@ -90,7 +114,10 @@ struct BackgroundItemActionsTests {}let moved = try await BackgroundItemActions.moveToTrash(- item(.userLibrary, state: .running(pid: 7), plist: plist), isHelperEnabled: false, trash: service(refusing: false), stop: stop+ item(.userLibrary, state: .running(pid: 7), plist: plist),+ isHelperEnabled: false,+ trash: service(refusing: false),+ stop: stop)#expect(moved.result.trashed.count == 1)#expect(moved.stillRunning == nil)@@ -100,7 +127,10 @@ struct BackgroundItemActionsTests {// it is written down like any other.steps.withLock { $0 = [] }let refused = try await BackgroundItemActions.moveToTrash(- item(.userLibrary, state: .running(pid: 7), plist: plist), isHelperEnabled: false, trash: service(refusing: true), stop: stop+ item(.userLibrary, state: .running(pid: 7), plist: plist),+ isHelperEnabled: false,+ trash: service(refusing: true),+ stop: stop)#expect(refused.result.trashed.isEmpty)#expect(refused.result.failures.map(\.reason) == [.guarded(.protectedLocation)])@@ -109,7 +139,10 @@ struct BackgroundItemActionsTests {// A job launchd does not hold has nothing to stop.steps.withLock { $0 = [] }_ = try await BackgroundItemActions.moveToTrash(- item(.userLibrary, state: .notLoaded, plist: plist), isHelperEnabled: false, trash: service(refusing: false), stop: stop+ item(.userLibrary, state: .notLoaded, plist: plist),+ isHelperEnabled: false,+ trash: service(refusing: false),+ stop: stop)#expect(steps.withLock { $0 } == ["move"])}@@ -151,7 +184,9 @@ struct BackgroundItemActionsTests {@Test func movesNothingFromTheSystemLibraryWithoutTheHelper() async {let plist = URL(filePath: "/Library/LaunchDaemons/com.example.agent.plist")let touched = Mutex(false)- let trash = TrashService(environment: SearchEnvironment(homeDirectory: URL(filePath: "/Users/x"), rootDirectory: URL(filePath: "/"))) { url in+ let trash = TrashService(+ environment: SearchEnvironment(homeDirectory: URL(filePath: "/Users/x"), rootDirectory: URL(filePath: "/"))+ ) { url intouched.withLock { $0 = true }return url}@@ -249,7 +284,10 @@ struct DeclaredBackgroundItemsTests {try directory.file("home/Library/LaunchAgents/unnamed.plist", contents: Data())try directory.file("home/Library/LaunchAgents/notes.txt")- let items = BackgroundItems.declared(in: environment(directory), ownership: BackgroundItemOwnership(installedApps: []))+ let items = BackgroundItems.declared(+ in: environment(directory),+ ownership: BackgroundItemOwnership(installedApps: [])+ )let jobs = items.filter { !$0.isUnreadable }let labels = ["com.apple.madeup.peeltest", "com.example.agent", "com.example.helper", "com.openssh.ssh-agent", shipped]@@ -273,7 +311,13 @@ struct DeclaredBackgroundItemsTests {let ownership = BackgroundItemOwnership(installedApps: [])let stray = try directory.file("home/Desktop/org.example.stray.plist", contents: job("org.example.stray", program: "/bin/sh"))func item(_ label: String, _ details: Launchctl.JobDetails, exclusions: Exclusions = .none) -> BackgroundItem? {- BackgroundItems.undeclaredItem((label, .agent, "gui/501/\(label)"), details: details, ownership: ownership, loaded: .init(), exclusions: exclusions)+ BackgroundItems.undeclaredItem(+ (label, .agent, "gui/501/\(label)"),+ details: details,+ ownership: ownership,+ loaded: .init(),+ exclusions: exclusions+ )}let loadedElsewhere = try #require(item("org.example.stray", .init(path: stray.path(percentEncoded: false), program: "/bin/sh")))@@ -286,7 +330,13 @@ struct DeclaredBackgroundItemsTests {#expect(nobodys.ownerBundleIdentifier == nil)#expect(item("com.openssh.ssh-agent", .init(path: "/System/Library/LaunchAgents/com.openssh.ssh-agent.plist", program: "/usr/bin/ssh-agent")) == nil)- #expect(item("org.example.stray", .init(path: stray.path(percentEncoded: false), program: "/bin/sh"), exclusions: Exclusions(paths: [stray])) == nil)+ #expect(+ item(+ "org.example.stray",+ .init(path: stray.path(percentEncoded: false), program: "/bin/sh"),+ exclusions: Exclusions(paths: [stray])+ ) == nil+ )}/// A job an app registered is known only while it is loaded, so after Disable and a restart it would leave the@@ -322,7 +372,10 @@ struct DeclaredBackgroundItemsTests {try directory.file("home/Library/LaunchAgents/org.example.gone.helper.plist", contents: job("org.example.gone.helper"))let app = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "org.example.app", name: "Example")- let items = BackgroundItems.declared(in: environment(directory), ownership: BackgroundItemOwnership(installedApps: [app]))+ let items = BackgroundItems.declared(+ in: environment(directory),+ ownership: BackgroundItemOwnership(installedApps: [app])+ )#expect(items.first { $0.label == "org.example.app.helper" }?.ownerURL == app.url)#expect(items.first { $0.label == "org.example.gone.helper" }?.ownerURL == nil)@@ -335,7 +388,10 @@ struct DeclaredBackgroundItemsTests {try directory.file("\(folder)/com.example.agent.plist", contents: job("com.example.agent"))}- let items = BackgroundItems.declared(in: environment(directory), ownership: BackgroundItemOwnership(installedApps: []))+ let items = BackgroundItems.declared(+ in: environment(directory),+ ownership: BackgroundItemOwnership(installedApps: [])+ )#expect(items.count == 2)#expect(Set(items.map(\.id)).count == 2)@@ -362,7 +418,11 @@ struct DeclaredBackgroundItemsTests {try directory.file("home/Library/LaunchAgents/named-after-something-else.plist", contents: job("com.example.agent"))let loaded = BackgroundItems.Loaded(user: ["com.example.agent": 91], userDisabled: ["com.example.agent": true])- let items = BackgroundItems.declared(in: environment(directory), ownership: BackgroundItemOwnership(installedApps: []), loaded: loaded)+ let items = BackgroundItems.declared(+ in: environment(directory),+ ownership: BackgroundItemOwnership(installedApps: []),+ loaded: loaded+ )#expect(items.first?.state == .running(pid: 91))#expect(items.first?.isDisabled == true)@@ -390,7 +450,11 @@ struct DeclaredBackgroundItemsTests {let directory = try TemporaryDirectory()try directory.file("home/Library/LaunchAgents/updater.plist", contents: job("com.example.agent"))let loaded = BackgroundItems.Loaded(user: ["com.example.agent": 91, "com.example.submitted": nil, "com.apple.Finder": 1])- let items = BackgroundItems.declared(in: environment(directory), ownership: BackgroundItemOwnership(installedApps: []), loaded: loaded)+ let items = BackgroundItems.declared(+ in: environment(directory),+ ownership: BackgroundItemOwnership(installedApps: []),+ loaded: loaded+ )let undeclared = BackgroundItems.undeclared(in: loaded, declared: items, userDomain: "gui/501")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemOwnershipTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemOwnershipTests.swiftindex 5dc5222b..ac0c16ef 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemOwnershipTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemOwnershipTests.swift@@ -22,8 +22,19 @@ struct BackgroundItemOwnershipTests {@Test func knowsTheJobTheHelperWillNotActOn() {func item(_ label: String, _ kind: BackgroundItem.Kind) -> BackgroundItem {BackgroundItem(- label: label, kind: kind, source: .app, plistURL: nil, program: nil, runsAtLoad: false, keepsAlive: false,- ownerBundleIdentifier: nil, ownerName: nil, ownerURL: nil, isOrphan: false, state: .loaded, isDisabled: false+ label: label,+ kind: kind,+ source: .app,+ plistURL: nil,+ program: nil,+ runsAtLoad: false,+ keepsAlive: false,+ ownerBundleIdentifier: nil,+ ownerName: nil,+ ownerURL: nil,+ isOrphan: false,+ state: .loaded,+ isDisabled: false)}let helper = item(HelperIdentity.helperIdentifier, .daemon)@@ -81,7 +92,12 @@ struct BackgroundItemOwnershipTests {installedApps: [InstalledApp(url: installed, bundleIdentifier: "com.example.app", name: "Example", teamIdentifier: "ABCDE12345"), app("com.other.tool", "Tool")],teamOfProgram: { Self.teams[$0] })- func owner(_ label: String, registeredBy: String? = nil, associated: [String] = [], program: String?) -> BackgroundItemOwnership.Owner? {+ func owner(+ _ label: String,+ registeredBy: String? = nil,+ associated: [String] = [],+ program: String?+ ) -> BackgroundItemOwnership.Owner? {ownership.owner(label: label, registeredBy: registeredBy, associated: associated, program: program)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swiftindex de7c86db..c40c40f5 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift@@ -7,7 +7,12 @@ struct BulkUninstallationTests {InstalledApp(url: URL(filePath: "/Applications/\(name).app"), bundleIdentifier: identifier, name: name)}- private func leftover(_ path: String, size: Int64, sharedWith: [String] = [], confidence: MatchConfidence = .certain) -> Leftover {+ private func leftover(+ _ path: String,+ size: Int64,+ sharedWith: [String] = [],+ confidence: MatchConfidence = .certain+ ) -> Leftover {Leftover(url: URL(filePath: path),kind: .applicationSupport,@@ -47,12 +52,17 @@ struct BulkUninstallationTests {var excludedApp = uninstallation(app("com.example.excluded", "Excluded"), [])excludedApp.isExcluded = truelet peel = uninstallation(app("com.tuguidragos.Peel", "Peel"), [leftover("/Users/x/Library/Caches/com.tuguidragos.Peel", size: 100)])- let bulk = BulkUninstallation(uninstallations: [needsHelper, uninstallation(chess, [chessData]), beyond, excludedApp, peel])+ let bulk = BulkUninstallation(uninstallations: [+ needsHelper, uninstallation(chess, [chessData]), beyond, excludedApp, peel,+ ])#expect(bulk.selectable(canUseHelper: false) == [own.url, chessData.url])#expect(bulk.selectable(canUseHelper: true) == [notes.url, own.url, chessData.url])for canUseHelper in [false, true] {- #expect(bulk.suggestedSelection(canUseHelper: canUseHelper).isSubset(of: bulk.selectable(canUseHelper: canUseHelper)))+ #expect(+ bulk.suggestedSelection(canUseHelper: canUseHelper)+ .isSubset(of: bulk.selectable(canUseHelper: canUseHelper))+ )}}@@ -64,7 +74,9 @@ struct BulkUninstallationTests {let mail = app("com.example.mail", "Mail")let own = leftover("/Users/x/Library/Caches/com.example.notes", size: 100)let shared = leftover("/Users/x/Library/Group Containers/group.com.example", size: 100)- let bulk = BulkUninstallation(uninstallations: [uninstallation(notes, [own, shared]), uninstallation(copy, [own]), uninstallation(mail, [shared])])+ let bulk = BulkUninstallation(uninstallations: [+ uninstallation(notes, [own, shared]), uninstallation(copy, [own]), uninstallation(mail, [shared]),+ ])#expect(bulk.staying(selected: [notes.url, copy.url, mail.url]).isEmpty)#expect(bulk.staying(selected: [notes.url, mail.url]) == [notes.bundleIdentifier])@@ -88,7 +100,9 @@ struct BulkUninstallationTests {let bulk = BulkUninstallation(uninstallations: [uninstallation(notes, [preferences]), uninstallation(mail, [])])#expect(!bulk.suggestedSelection(canUseHelper: true).contains(preferences.url))- let bothCopies = BulkUninstallation(uninstallations: [uninstallation(notes, [preferences]), uninstallation(copy, [preferences])])+ let bothCopies = BulkUninstallation(uninstallations: [+ uninstallation(notes, [preferences]), uninstallation(copy, [preferences]),+ ])#expect(bothCopies.suggestedSelection(canUseHelper: true).contains(preferences.url))}@@ -97,7 +111,14 @@ struct BulkUninstallationTests {@Test func listsWhatCouldNotBeMeasuredFirst() {let notes = app("com.example.notes", "Notes")var slow = leftover("/Users/x/Library/Application Support/Notes", size: 0)- slow = Leftover(url: slow.url, kind: slow.kind, match: slow.match, size: 0, isMeasured: false, requiresPrivileges: false)+ slow = Leftover(+ url: slow.url,+ kind: slow.kind,+ match: slow.match,+ size: 0,+ isMeasured: false,+ requiresPrivileges: false+ )let bulk = BulkUninstallation(uninstallations: [uninstallation(notes, [leftover("/Users/x/Library/Caches/com.example.notes", size: 900), slow]),])@@ -130,15 +151,28 @@ struct BulkUninstallationTests {let folder = "/Users/x/Library/Application Support/Shared Work"let named = Leftover(url: URL(filePath: folder), kind: .applicationSupport,- match: LeftoverMatch(reason: .homebrewCask, confidence: .certain, sharedWith: []), size: 100, isMeasured: true, requiresPrivileges: false+ match: LeftoverMatch(reason: .homebrewCask, confidence: .certain, sharedWith: []),+ size: 100,+ isMeasured: true,+ requiresPrivileges: false)let held = Leftover(url: URL(filePath: folder), kind: .applicationSupport,- match: LeftoverMatch(reason: .name, confidence: .likely, sharedWith: [], heldBack: .holdsRepository), size: 100, isMeasured: true, requiresPrivileges: false+ match: LeftoverMatch(reason: .name, confidence: .likely, sharedWith: [], heldBack: .holdsRepository),+ size: 100,+ isMeasured: true,+ requiresPrivileges: false)- for uninstallations in [[uninstallation(tool, [named]), uninstallation(editor, [held])], [uninstallation(editor, [held]), uninstallation(tool, [named])]] {- let item = try #require(BulkUninstallation(uninstallations: uninstallations).items.first { $0.url.path(percentEncoded: false) == folder })+ for uninstallations in [+ [uninstallation(tool, [named]), uninstallation(editor, [held])],+ [uninstallation(editor, [held]), uninstallation(tool, [named])],+ ] {+ let item = try #require(+ BulkUninstallation(uninstallations: uninstallations).items.first {+ $0.url.path(percentEncoded: false) == folder+ }+ )#expect(!item.isRecommended, "selected with \(uninstallations[0].app.name) first")#expect(item.match?.heldBack == .holdsRepository)#expect(item.match?.confidence == .likely)@@ -202,7 +236,8 @@ struct BulkUninstallationTests {let refused = Leftover(url: URL(filePath: "/Users/x/Library/Containers/com.example.gone"),kind: .containers,- match: LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: []).forReview(.holdsDocuments),+ match: LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: [])+ .forReview(.holdsDocuments),size: 700,isMeasured: true,requiresPrivileges: false@@ -210,7 +245,8 @@ struct BulkUninstallationTests {let unmeasured = Leftover(url: URL(filePath: "/Users/x/Library/Application Support/com.example.gone"),kind: .applicationSupport,- match: LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: []).forReview(.notMeasured),+ match: LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: [])+ .forReview(.notMeasured),size: 0,isMeasured: false,requiresPrivileges: falsediff --git a/Packages/PeelCore/Tests/PeelCoreTests/CappedSumTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CappedSumTests.swiftindex 24dc5f09..43d279f2 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CappedSumTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CappedSumTests.swift@@ -17,9 +17,13 @@ struct CappedSumTests {}@Test func combinesTotalsUpToTheLargestNumber() {- let whole = SizeTotal(combining: [SizeTotal(known: .max, isComplete: true), SizeTotal(known: 1, isComplete: true)])+ let whole = SizeTotal(combining: [+ SizeTotal(known: .max, isComplete: true), SizeTotal(known: 1, isComplete: true),+ ])#expect(whole == SizeTotal(known: .max, isComplete: true))- let part = SizeTotal(combining: [SizeTotal(known: 10, isComplete: true), SizeTotal(known: 5, isComplete: false)])+ let part = SizeTotal(combining: [+ SizeTotal(known: 10, isComplete: true), SizeTotal(known: 5, isComplete: false),+ ])#expect(part == SizeTotal(known: 15, isComplete: false))}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swiftindex db034dba..5797fb58 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift@@ -86,7 +86,9 @@ struct CarriedSelectionTests {let pass = await CarriedSelection.pass(parts) { part intried.append(part.page.scope)guard part.page.tool != "developer" else { return nil }- return TrashResult(trashed: part.sizes.keys.map { TrashedItem(originalURL: $0, trashedURL: $0, date: .now) })+ return TrashResult(+ trashed: part.sizes.keys.map { TrashedItem(originalURL: $0, trashedURL: $0, date: .now) }+ )}#expect(tried == ["Xcode", "Peel"])@@ -127,7 +129,9 @@ struct CarriedSelectionTests {let batch = UUID()var records: [RemovalRecord] = []_ = await CarriedSelection.pass(parts) { part in- let result = TrashResult(trashed: part.sizes.keys.map { TrashedItem(originalURL: $0, trashedURL: $0, date: .now) })+ let result = TrashResult(+ trashed: part.sizes.keys.map { TrashedItem(originalURL: $0, trashedURL: $0, date: .now) }+ )records += part.removalPart.records(of: result, sizes: part.measuredSizes, batch: batch)return result}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swiftindex eb1edb6a..aa9b070a 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift@@ -160,7 +160,13 @@ struct CaskEvidenceTests {#expect(evidence.items.filter(\.isInLibrary).count == 1)let matcher = LeftoverMatcher(app: app, installedApps: [app])- let leftovers = await Uninstallation.caskLeftovers(evidence, app: app, exclusions: .none, matcher: matcher, environment: environment(home))+ let leftovers = await Uninstallation.caskLeftovers(+ evidence,+ app: app,+ exclusions: .none,+ matcher: matcher,+ environment: environment(home)+ )#expect(leftovers.count == 2)#expect(leftovers.allSatisfy { $0.match.reason == .homebrewCask })#expect(leftovers.filter(\.match.isRecommended).count == 1)@@ -187,7 +193,11 @@ struct CaskEvidenceTests {let evidence = try #require(CaskEvidence.evidence(for: word, casks: [cask], home: home))let leftovers = await Uninstallation.caskLeftovers(- evidence, app: word, exclusions: .none, matcher: LeftoverMatcher(app: word, installedApps: [word]), environment: environment(home)+ evidence,+ app: word,+ exclusions: .none,+ matcher: LeftoverMatcher(app: word, installedApps: [word]),+ environment: environment(home))let found = Dictionary(uniqueKeysWithValues: leftovers.map { ($0.url.lastPathComponent, $0) })@@ -225,7 +235,11 @@ struct CaskEvidenceTests {let evidence = try #require(CaskEvidence.evidence(for: app, casks: [cask], home: home))let leftovers = await Uninstallation.caskLeftovers(- evidence, app: app, exclusions: .none, matcher: LeftoverMatcher(app: app, installedApps: [app]), environment: environment(home)+ evidence,+ app: app,+ exclusions: .none,+ matcher: LeftoverMatcher(app: app, installedApps: [app]),+ environment: environment(home))#expect(leftovers.first?.match.heldBack == .holdsRepository)@@ -248,7 +262,13 @@ struct CaskEvidenceTests {let evidence = try #require(CaskEvidence.evidence(for: app, casks: [cask], home: home))let matcher = LeftoverMatcher(app: app, installedApps: [app, other])- let leftovers = await Uninstallation.caskLeftovers(evidence, app: app, exclusions: .none, matcher: matcher, environment: environment(home))+ let leftovers = await Uninstallation.caskLeftovers(+ evidence,+ app: app,+ exclusions: .none,+ matcher: matcher,+ environment: environment(home)+ )#expect(leftovers.first?.match.sharedWith == ["com.vendor.shared"])#expect(leftovers.first?.match.isRecommended == false)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swiftindex 7016751f..62ddc148 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift@@ -75,7 +75,13 @@ struct CleanupTests {try await Output.$collected.withValue(collected) {try await cleanup(items: [(cache, 20)], service: try service(in: directory))- .run(question: "?", dryRun: true, yes: true, using: try service(in: directory), recordingIn: RemovalLog(url: history))+ .run(+ question: "?",+ dryRun: true,+ yes: true,+ using: try service(in: directory),+ recordingIn: RemovalLog(url: history)+ )}#expect(collected.notes.hasPrefix("Peel couldn't read its History at \(history.path(percentEncoded: false)), so nothing will be moved."))@@ -147,7 +153,14 @@ struct CleanupTests {let plan = cleanup(items: [(cache, 20)], service: service)await #expect(throws: ExitCode.failure) {- try await plan.run(question: "?", dryRun: false, yes: true, using: service, recordingIn: log, refusals: refusals) { _, urls in+ try await plan.run(+ question: "?",+ dryRun: false,+ yes: true,+ using: service,+ recordingIn: log,+ refusals: refusals+ ) { _, urls inTrashResult(failures: urls.map { TrashFailure(url: $0, reason: .changedSinceScan) })}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swiftindex 7d60b7dd..9376a00d 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift@@ -8,19 +8,55 @@ struct CloudStorageTests {#expect(CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: false, hasConflicts: false))#expect(CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: nil, hasConflicts: nil))- #expect(!CloudStorage.isSafeToFree(status: .current, isUploaded: false, isUploading: false, hasConflicts: false), "it wasn't uploaded yet")- #expect(!CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: true, hasConflicts: false), "it was still uploading")- #expect(!CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: false, hasConflicts: true), "it has a conflict to settle")- #expect(!CloudStorage.isSafeToFree(status: .downloaded, isUploaded: true, isUploading: false, hasConflicts: false), "an older copy is on this Mac")- #expect(!CloudStorage.isSafeToFree(status: .notDownloaded, isUploaded: true, isUploading: false, hasConflicts: false), "there is nothing here to free")+ #expect(+ !CloudStorage.isSafeToFree(status: .current, isUploaded: false, isUploading: false, hasConflicts: false),+ "it wasn't uploaded yet"+ )+ #expect(+ !CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: true, hasConflicts: false),+ "it was still uploading"+ )+ #expect(+ !CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: false, hasConflicts: true),+ "it has a conflict to settle"+ )+ #expect(+ !CloudStorage.isSafeToFree(status: .downloaded, isUploaded: true, isUploading: false, hasConflicts: false),+ "an older copy is on this Mac"+ )+ #expect(+ !CloudStorage.isSafeToFree(+ status: .notDownloaded,+ isUploaded: true,+ isUploading: false,+ hasConflicts: false+ ),+ "there is nothing here to free"+ )#expect(!CloudStorage.isSafeToFree(status: nil, isUploaded: nil, isUploading: nil, hasConflicts: nil))}/// On macOS 26, syncing can be paused for an item. A paused item with local edits is not uploading, yet it/// still reads as uploaded (`NSURL.h`: `NSURLUbiquitousItemIsSyncPausedKey`).@Test func leavesAloneAFileWhoseSyncIsPaused() {- #expect(!CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: false, hasConflicts: false, isSyncPaused: true))- #expect(CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: false, hasConflicts: false, isSyncPaused: false))+ #expect(+ !CloudStorage.isSafeToFree(+ status: .current,+ isUploaded: true,+ isUploading: false,+ hasConflicts: false,+ isSyncPaused: true+ )+ )+ #expect(+ CloudStorage.isSafeToFree(+ status: .current,+ isUploaded: true,+ isUploading: false,+ hasConflicts: false,+ isSyncPaused: false+ )+ )#expect(!CloudStorage.isSafeToFree(status: .current, isUploaded: true, isUploading: false, hasConflicts: false,uploadingError: CocoaError(.fileWriteNoPermission)@@ -124,7 +160,12 @@ struct CloudStorageTests {let directory = try TemporaryDirectory()try directory.directory("Library/Mobile Documents")try directory.setPermissions(0o000, of: "Library/Mobile Documents")- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: directory.url.appending(path: "Library/Mobile Documents").path(percentEncoded: false)) }+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: directory.url.appending(path: "Library/Mobile Documents").path(percentEncoded: false)+ )+ }let scan = await CloudStorage.downloaded(home: directory.url)@@ -184,7 +225,15 @@ struct CloudStorageTests {}let collector = CloudStorage.Collector()- CloudStorage.collect(home: directory.url, minimumSize: 1, exclusions: .none, into: collector, deadline: .now, countingFor: nil, unless: { false })+ CloudStorage.collect(+ home: directory.url,+ minimumSize: 1,+ exclusions: .none,+ into: collector,+ deadline: .now,+ countingFor: nil,+ unless: { false }+ )#expect(collector.collected.wasCutShort)#expect(collector.collected.files.isEmpty)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swiftindex 71148cfb..99c1b725 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift@@ -75,7 +75,12 @@ struct CommandLineTests {let installed = InstalledApp(url: bundle, bundleIdentifier: "com.example.app", name: "Example")#expect(try AppLookup.app(matching: link.path(percentEncoded: false), in: [installed]) == installed)- #expect(try AppLookup.app(matching: directory.url.appending(path: "applications/example.app").path(percentEncoded: false), in: [installed]) == installed)+ #expect(+ try AppLookup.app(+ matching: directory.url.appending(path: "applications/example.app").path(percentEncoded: false),+ in: [installed]+ ) == installed+ )}/// `peel` runs with the user's locale, and under Turkish rules `iina` does not match `IINA`. App names are@@ -227,7 +232,11 @@ struct CommandLineTests {}@Test func spellsAPathTheSameWayAsTheInventory() {- let app = InstalledApp(url: URL(filePath: NSHomeDirectory() + "/Applications/Editor.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.editor", name: "Editor")+ let app = InstalledApp(+ url: URL(filePath: NSHomeDirectory() + "/Applications/Editor.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.editor",+ name: "Editor"+ )let inventoried = Inventory.build(apps: [app]).entries[0].path#expect(Output.path(app.url) == inventoried)@@ -236,7 +245,12 @@ struct CommandLineTests {}@Test func writesEveryKeyOfEveryRecord() throws {- let known = InstalledApp(url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.editor", name: "Editor", version: "1.0")+ let known = InstalledApp(+ url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.editor",+ name: "Editor",+ version: "1.0"+ )let unknown = InstalledApp(url: URL(filePath: "/Applications/Widget.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.widget", name: "Widget")let json = try Output.jsonText([AppRecord(known), AppRecord(unknown)])let records = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]])@@ -272,8 +286,22 @@ struct CommandLineTests {@Test func writesAnUnknownSizeAsNull() throws {let match = LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: [])let folder = URL(filePath: "/Users/me/Library/Application Support/Editor")- let measured = Leftover(url: folder, kind: .applicationSupport, match: match, size: 4_096, isMeasured: true, requiresPrivileges: false)- let unmeasured = Leftover(url: folder, kind: .applicationSupport, match: match.forReview(.notMeasured), size: 0, isMeasured: false, requiresPrivileges: false)+ let measured = Leftover(+ url: folder,+ kind: .applicationSupport,+ match: match,+ size: 4_096,+ isMeasured: true,+ requiresPrivileges: false+ )+ let unmeasured = Leftover(+ url: folder,+ kind: .applicationSupport,+ match: match.forReview(.notMeasured),+ size: 0,+ isMeasured: false,+ requiresPrivileges: false+ )let json = try Output.jsonText([LeftoverRecord(measured), LeftoverRecord(unmeasured)])let records = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]])@@ -284,9 +312,21 @@ struct CommandLineTests {/// Another copy of the app shares its identifier, so the JSON names it by its place.@Test func namesAnotherCopyByItsPlace() throws {- let match = LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: [], otherCopies: [URL(filePath: "/Volumes/Disk/Editor.app")])+ let match = LeftoverMatch(+ reason: .bundleIdentifier,+ confidence: .certain,+ sharedWith: [],+ otherCopies: [URL(filePath: "/Volumes/Disk/Editor.app")]+ )let folder = URL(filePath: "/Users/me/Library/Application Support/Editor")- let leftover = Leftover(url: folder, kind: .applicationSupport, match: match, size: 4_096, isMeasured: true, requiresPrivileges: false)+ let leftover = Leftover(+ url: folder,+ kind: .applicationSupport,+ match: match,+ size: 4_096,+ isMeasured: true,+ requiresPrivileges: false+ )let json = try Output.jsonText([LeftoverRecord(leftover)])let records = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]])@@ -301,7 +341,9 @@ struct CommandLineTests {let report = LeftoversCommand.Report(app: app, appSize: nil, leftovers: [], unreadableLocations: [unread])- let json = try #require(JSONSerialization.jsonObject(with: Data(try Output.jsonText(report).utf8)) as? [String: Any])+ let json = try #require(+ JSONSerialization.jsonObject(with: Data(try Output.jsonText(report).utf8)) as? [String: Any]+ )#expect(json["unreadableLocations"] as? [String] == ["/Users/me/Library/Containers"])#expect(json["appSize"] is NSNull)}@@ -319,7 +361,9 @@ struct CommandLineTests {let result = TrashResult(trashed: [], failures: [TrashFailure(url: support, reason: .failed("disk full"))])let editor = InstalledApp(url: app, bundleIdentifier: "com.example.editor", name: "Editor")- let json = try Output.jsonText(UninstallCommand.report(app: editor, plan: plan, result: result, privacy: .reset, unreadable: []))+ let json = try Output.jsonText(+ UninstallCommand.report(app: editor, plan: plan, result: result, privacy: .reset, unreadable: [])+ )let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])let items = try #require(report["items"] as? [[String: Any]])@@ -336,7 +380,9 @@ struct CommandLineTests {#expect(report["needsReview"] as? Int == 2)#expect(report["unreadableLocations"] as? [String] == [])- let dryRun = try Output.jsonText(UninstallCommand.report(app: editor, plan: plan, result: nil, privacy: nil, unreadable: []))+ let dryRun = try Output.jsonText(+ UninstallCommand.report(app: editor, plan: plan, result: nil, privacy: nil, unreadable: [])+ )let planned = try #require(JSONSerialization.jsonObject(with: Data(dryRun.utf8)) as? [String: Any])#expect(planned["dryRun"] as? Bool == true)#expect(planned["moved"] as? [String] == [])@@ -350,7 +396,10 @@ struct CommandLineTests {struct Row: Encodable {let size: MeasuredSize}- let rows = [Row(size: MeasuredSize(4_096)), Row(size: MeasuredSize(nil)), Row(size: MeasuredSize(SizeTotal([10, nil])))]+ let rows = [+ Row(size: MeasuredSize(4_096)), Row(size: MeasuredSize(nil)),+ Row(size: MeasuredSize(SizeTotal([10, nil]))),+ ]let records = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(rows)) as? [[String: Any]])#expect(records[0]["size"] as? Int == 4_096)@@ -417,7 +466,14 @@ struct CommandLineTests {) -> Leftover {var match = LeftoverMatch(reason: .bundleIdentifier, confidence: confidence, sharedWith: sharedWith)if let heldBack { match = match.forReview(heldBack) }- return Leftover(url: url, kind: .caches, match: match, size: size, isMeasured: true, requiresPrivileges: requiresPrivileges)+ return Leftover(+ url: url,+ kind: .caches,+ match: match,+ size: size,+ isMeasured: true,+ requiresPrivileges: requiresPrivileges+ )}/// The notes shown before the user agrees to a removal. Each one names something that will still be on@@ -466,7 +522,12 @@ struct CommandLineTests {refusal: { _ in nil })- let notes = UninstallCommand.whatStays(plan, app: app, homebrew: CaskLookup.Answer(), scan: LeftoverScan(leftovers: [], unreadableLocations: []))+ let notes = UninstallCommand.whatStays(+ plan,+ app: app,+ homebrew: CaskLookup.Answer(),+ scan: LeftoverScan(leftovers: [], unreadableLocations: [])+ )#expect(notes.isEmpty)}@@ -511,7 +572,11 @@ struct CommandLineTests {#expect(plan.total == SizeTotal(known: 13_000, isComplete: true))#expect(plan.staying.isEmpty)- let alone = UninstallPlan.make(uninstallation(app: app, leftovers: [leftover(cache)]), keepLeftovers: true, refusal: { _ in nil })+ let alone = UninstallPlan.make(+ uninstallation(app: app, leftovers: [leftover(cache)]),+ keepLeftovers: true,+ refusal: { _ in nil }+ )#expect(alone.items.map(\.url) == [app.url])#expect(alone.needsReview == 0)}@@ -676,8 +741,18 @@ struct CommandLineTests {/// A check that failed is listed, in the table and in `--json`, so the report never reads as "every app is up to/// date", which a script would take as the all clear, while some apps did not answer.@Test func doesNotCallAFailedCheckAnAllClear() {- let editor = InstalledApp(url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.editor", name: "Editor", version: "1.0")- let notes = InstalledApp(url: URL(filePath: "/Applications/Notes.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.notes", name: "Notes", version: "2.0")+ let editor = InstalledApp(+ url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.editor",+ name: "Editor",+ version: "1.0"+ )+ let notes = InstalledApp(+ url: URL(filePath: "/Applications/Notes.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.notes",+ name: "Notes",+ version: "2.0"+ )let widget = InstalledApp(url: URL(filePath: "/Applications/Widget.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.widget", name: "Widget")let apps = [editor, notes, widget]@@ -720,8 +795,18 @@ struct CommandLineTests {/// The same rule the app follows: an app the user told Peel to leave alone is not checked, and a skipped/// version is not an update waiting.@Test func readsTheSameUpdateSettingsTheAppDoes() {- let editor = InstalledApp(url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.editor", name: "Editor", version: "1.0")- let notes = InstalledApp(url: URL(filePath: "/Applications/Notes.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.notes", name: "Notes", version: "2.0")+ let editor = InstalledApp(+ url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.editor",+ name: "Editor",+ version: "1.0"+ )+ let notes = InstalledApp(+ url: URL(filePath: "/Applications/Notes.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.notes",+ name: "Notes",+ version: "2.0"+ )let waiting = UpdateStatus.updateAvailable(version: "3.0", source: .developer, releaseNotes: nil)let preferences = UpdatePreferences(source: .homebrew,@@ -742,7 +827,10 @@ struct CommandLineTests {#expect(!preferences.isWaiting(waiting, for: editor))#expect(!preferences.isWaiting(waiting, for: notes))#expect(preferences.isWaiting(.updateAvailable(version: "4.0", source: .developer, releaseNotes: nil), for: editor))- #expect(UpdatesCommand.report(apps: [editor, notes], statuses: [:], preferences: preferences, all: true).rows.count == 1)+ #expect(+ UpdatesCommand.report(apps: [editor, notes], statuses: [:], preferences: preferences, all: true).rows.count+ == 1+ )}@Test func readsTheUpdateSettingsFromTheAppsOwnKeys() throws {@@ -765,10 +853,29 @@ struct CommandLineTests {/// match is only possible.@Test func saysWhyARowIsOnlyShown() {let folder = URL(filePath: "/Users/me/Library/Application Support/Editor")- func row(_ confidence: MatchConfidence, sharedWith: [String] = [], otherCopies: [URL] = [], heldBack: HoldBack? = nil) -> String {- var match = LeftoverMatch(reason: .bundleIdentifier, confidence: confidence, sharedWith: sharedWith, otherCopies: otherCopies)+ func row(+ _ confidence: MatchConfidence,+ sharedWith: [String] = [],+ otherCopies: [URL] = [],+ heldBack: HoldBack? = nil+ ) -> String {+ var match = LeftoverMatch(+ reason: .bundleIdentifier,+ confidence: confidence,+ sharedWith: sharedWith,+ otherCopies: otherCopies+ )if let heldBack { match = match.forReview(heldBack) }- return LeftoversCommand.summary(of: Leftover(url: folder, kind: .applicationSupport, match: match, size: 1, isMeasured: true, requiresPrivileges: false))+ return LeftoversCommand.summary(+ of: Leftover(+ url: folder,+ kind: .applicationSupport,+ match: match,+ size: 1,+ isMeasured: true,+ requiresPrivileges: false+ )+ )}#expect(row(.certain) == "bundle identifier")@@ -784,7 +891,10 @@ struct CommandLineTests {let orphans = OrphansCommand.helpMessage(columns: 200)#expect(orphans.contains("Move the named group to the Trash, leaving out what Peel holds back."))#expect(!orphans.contains("Move what Peel suggests"))- for help in [CachesCommand.helpMessage(columns: 200), ProjectsCommand.helpMessage(columns: 200), DuplicatesCommand.helpMessage(columns: 200)] {+ for help in [+ CachesCommand.helpMessage(columns: 200), ProjectsCommand.helpMessage(columns: 200),+ DuplicatesCommand.helpMessage(columns: 200),+ ] {#expect(help.contains("Move what Peel suggests to the Trash."))}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DefaultAppsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DefaultAppsTests.swiftindex 9f6ae318..5c353353 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/DefaultAppsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/DefaultAppsTests.swift@@ -56,8 +56,14 @@ struct DefaultAppsTests {/// include it, and reading them must change nothing.@Test func findsTheRoleOfWhateverOpensMailOnThisMac() async throws {let mailto = try #require(URL(string: "mailto:"))- guard let handler = await MainActor.run(body: { NSWorkspace.shared.urlForApplication(toOpen: mailto) }) else { return }- let subject = InstalledApp(url: handler, bundleIdentifier: "", name: handler.deletingPathExtension().lastPathComponent)+ guard let handler = await MainActor.run(body: { NSWorkspace.shared.urlForApplication(toOpen: mailto) }) else {+ return+ }+ let subject = InstalledApp(+ url: handler,+ bundleIdentifier: "",+ name: handler.deletingPathExtension().lastPathComponent+ )let roles = await DefaultApps.roles(of: subject)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swiftindex b84a6ecf..a464f9b3 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift@@ -18,7 +18,13 @@ struct DeveloperCachesTests {for path in paths {try directory.directory(path)}- let tool = DeveloperCaches.Definition(id: "tool", name: "Tool", systemImage: "hammer", appBundleIdentifiers: [], folders: paths.map { DeveloperCaches.Folder($0, .cache, source: "https://example.com") })+ let tool = DeveloperCaches.Definition(+ id: "tool",+ name: "Tool",+ systemImage: "hammer",+ appBundleIdentifiers: [],+ folders: paths.map { DeveloperCaches.Folder($0, .cache, source: "https://example.com") }+ )let unanswered = Unanswered()let stop = try await unanswered.stop {@@ -39,7 +45,11 @@ struct DeveloperCachesTests {try directory.setPermissions(0o000, of: ".npm/_cacache")defer { try? directory.setPermissions(0o755, of: ".npm/_cacache") }- let environments = await DeveloperCaches.scan(DeveloperCaches.definitions, homeDirectory: directory.url, exclusions: .none) { url in+ let environments = await DeveloperCaches.scan(+ DeveloperCaches.definitions,+ homeDirectory: directory.url,+ exclusions: .none+ ) { url inurl.lastPathComponent == "_npx" ? nil : await FileSize.contents(of: url)}@@ -87,7 +97,10 @@ struct DeveloperCachesTests {@Test func findsWhatItListsInsideAFolderSpelledAnotherWay() throws {let directory = try TemporaryDirectory()try directory.directory("home/Library/Caches/Coursier/v1")- try FileManager.default.createSymbolicLink(at: directory.url.appending(path: "link"), withDestinationURL: directory.url.appending(path: "home"))+ try FileManager.default.createSymbolicLink(+ at: directory.url.appending(path: "link"),+ withDestinationURL: directory.url.appending(path: "home")+ )let home = directory.url.appending(path: "home", directoryHint: .isDirectory)let left = DeveloperCaches.FoldersLeftToDeveloper(home: home).inside@@ -226,7 +239,11 @@ struct DeveloperCachesTests {try directory.file(".npm/_npx/package/index.js", bytes: 8_000)try directory.file("Library/Developer/Xcode/DerivedData/ModuleCache.noindex/module.pcm", bytes: 20_000)- let environments = await DeveloperCaches.scan(DeveloperCaches.definitions, homeDirectory: directory.url, exclusions: .none) { url in+ let environments = await DeveloperCaches.scan(+ DeveloperCaches.definitions,+ homeDirectory: directory.url,+ exclusions: .none+ ) { url inurl.lastPathComponent == "_npx" ? nil : await FileSize.contents(of: url)}@@ -417,7 +434,9 @@ struct DeveloperCachesTests {/// A path inside another would count the same bytes twice, and moving the outer folder would take the inner.@Test func noPathIsInsideAnother() {- let paths = DeveloperCaches.definitions.flatMap { definition in definition.folders.map { ($0.path, definition.id) } }+ let paths = DeveloperCaches.definitions.flatMap { definition in+ definition.folders.map { ($0.path, definition.id) }+ }for (path, owner) in paths {for (other, otherOwner) in paths where other != path {#expect(!path.hasPrefix(other + "/"), "\(owner) lists \(path) inside \(otherOwner)'s \(other)")@@ -439,7 +458,10 @@ struct DeveloperCachesTests {try directory.file("Library/Caches/deno/latest.txt", bytes: 64)let deno = DeveloperCaches.definitions.filter { $0.id == "deno" }- let offered = Set(await DeveloperCaches.scan(deno, homeDirectory: directory.url).flatMap(\.locations).map(\.url.lastPathComponent))+ let offered = Set(+ await DeveloperCaches.scan(deno, homeDirectory: directory.url).flatMap(\.locations)+ .map(\.url.lastPathComponent)+ )#expect(offered == ["remote", "npm", "deps", "gen", "registries", "dl", "check_cache_v2", "dep_analysis_cache_v1"])}@@ -495,7 +517,9 @@ struct DeveloperCachesTests {)let environments = await DeveloperCaches.scan(in: environment)let home = directory.url.path(percentEncoded: false)- let found = Set(environments.flatMap(\.locations).map { String($0.url.path(percentEncoded: false).dropFirst(home.count)) })+ let found = Set(+ environments.flatMap(\.locations).map { String($0.url.path(percentEncoded: false).dropFirst(home.count)) }+ )#expect(found == expected, "missing \(expected.subtracting(found).sorted()), extra \(found.subtracting(expected).sorted())")#expect(environments.count == DeveloperCaches.definitions.count)#expect(environments.flatMap(\.locations).allSatisfy { ($0.size ?? 0) >= 400_000 })@@ -671,7 +695,8 @@ struct DeveloperCachesTests {try directory.file("Library/Developer/Xcode/UserData/Previews/other/state", bytes: 400_000)let xcode = DeveloperCaches.definitions.filter { $0.id == "xcode" }- let offered = await DeveloperCaches.scan(xcode, homeDirectory: directory.url).flatMap(\.locations).map(\.url.lastPathComponent)+ let offered = await DeveloperCaches.scan(xcode, homeDirectory: directory.url).flatMap(\.locations)+ .map(\.url.lastPathComponent)#expect(offered == ["Simulator Devices"])}@@ -1208,7 +1233,8 @@ struct DeveloperCachesTests {try FileManager.default.createSymbolicLink(at: directory.url.appending(path: ".virtualenvs/fast"), withDestinationURL: elsewhere)let wrapper = DeveloperCaches.definitions.filter { $0.id == "virtualenvwrapper" }- let offered = await DeveloperCaches.scan(wrapper, homeDirectory: directory.url).flatMap(\.locations).map(\.url.lastPathComponent)+ let offered = await DeveloperCaches.scan(wrapper, homeDirectory: directory.url).flatMap(\.locations)+ .map(\.url.lastPathComponent)#expect(offered == ["web"])}@@ -1222,7 +1248,8 @@ struct DeveloperCachesTests {try directory.file(".nx/sockets/daemon", bytes: 16)let nx = DeveloperCaches.definitions.filter { $0.id == "nx" }- let offered = await DeveloperCaches.scan(nx, homeDirectory: directory.url).flatMap(\.locations).map(\.url.lastPathComponent)+ let offered = await DeveloperCaches.scan(nx, homeDirectory: directory.url).flatMap(\.locations)+ .map(\.url.lastPathComponent)#expect(offered == ["5d41402abc4b2a76"])}@@ -1236,7 +1263,10 @@ struct DeveloperCachesTests {try directory.file(".bun/install/cache/[email protected]@@@1/package.json", bytes: 400_000)if storeIsALink {let elsewhere = try directory.directory("Volumes/Fast/bun-links")- try FileManager.default.createSymbolicLink(at: directory.url.appending(path: ".bun/install/cache/links"), withDestinationURL: elsewhere)+ try FileManager.default.createSymbolicLink(+ at: directory.url.appending(path: ".bun/install/cache/links"),+ withDestinationURL: elsewhere+ )} else if hasStore {try directory.file(".bun/install/cache/links/[email protected]/node_modules/react/index.js", bytes: 4_096)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DigestMemoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DigestMemoryTests.swiftindex 387bf900..26f8d2c3 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/DigestMemoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/DigestMemoryTests.swift@@ -10,7 +10,8 @@ struct DigestMemoryTests {private func scan(_ directory: borrowing TemporaryDirectory, memory: DigestMemory) async throws -> DuplicateScan {let home = directory.url.appending(path: "home", directoryHint: .isDirectory)- return try await DuplicateFinder(homeDirectory: home, digestMemory: memory).scan(DuplicateScanOptions(folders: [home]))+ return try await DuplicateFinder(homeDirectory: home, digestMemory: memory)+ .scan(DuplicateScanOptions(folders: [home]))}private func names(_ scan: DuplicateScan) -> [[String]] {@@ -49,7 +50,11 @@ struct DigestMemoryTests {try directory.file("home/Pictures/second.bin", contents: contents)let excluded = try directory.file("home/Desktop/excluded.bin", contents: contents)let home = directory.url.appending(path: "home", directoryHint: .isDirectory)- let finder = DuplicateFinder(homeDirectory: home, exclusions: Exclusions(paths: [excluded]), digestMemory: memory)+ let finder = DuplicateFinder(+ homeDirectory: home,+ exclusions: Exclusions(paths: [excluded]),+ digestMemory: memory+ )let result = try await finder.scan(DuplicateScanOptions(folders: [home]))@@ -67,7 +72,8 @@ struct DigestMemoryTests {try directory.file("home/Pictures/second.bin", contents: contents)let home = directory.url.appending(path: "home", directoryHint: .isDirectory)- let result = try await DuplicateFinder(homeDirectory: home, exclusions: .notYetRead, digestMemory: memory).scan(DuplicateScanOptions(folders: [home]))+ let result = try await DuplicateFinder(homeDirectory: home, exclusions: .notYetRead, digestMemory: memory)+ .scan(DuplicateScanOptions(folders: [home]))#expect(result.groups.isEmpty)#expect(memory.load().sample(of: try #require(FileIdentity.of(first))) == nil, "a file was read")@@ -118,7 +124,9 @@ struct DigestMemoryTests {var times = [original.st_atimespec, original.st_mtimespec]#expect(utimensat(AT_FDCWD, path, ×, 0) == 0)let after = try #require(FileIdentity.of(second))- #expect(after.link == before.link && after.size == before.size && after.modificationTime == before.modificationTime)+ #expect(+ after.link == before.link && after.size == before.size && after.modificationTime == before.modificationTime+ )#expect(names(try await scan(directory, memory: memory)).isEmpty)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swiftindex 97146090..22586868 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift@@ -36,7 +36,9 @@ struct DuplicateFinderTests {configure: (inout DuplicateScanOptions) -> Void = { _ in }) async throws -> DuplicateScan {let home = directory.url.appending(path: "home", directoryHint: .isDirectory)- var options = DuplicateScanOptions(folders: folders.map { directory.url.appending(path: $0, directoryHint: .isDirectory) })+ var options = DuplicateScanOptions(+ folders: folders.map { directory.url.appending(path: $0, directoryHint: .isDirectory) }+ )configure(&options)return try await DuplicateFinder(homeDirectory: home).scan(options)}@@ -82,7 +84,10 @@ struct DuplicateFinderTests {]var asked: [String] = []- let movable = try DuplicateFinder.movable(groups, names: [refused.identity.link: [refused, try candidate("linked")]]) { url in+ let movable = try DuplicateFinder.movable(+ groups,+ names: [refused.identity.link: [refused, try candidate("linked")]]+ ) { url inasked.append(url.lastPathComponent)return !["refused", "partner"].contains(url.lastPathComponent)}@@ -148,7 +153,9 @@ struct DuplicateFinderTests {try directory.file("home/Documents/note.txt", contents: Data("hello".utf8))let result = try await scan(directory)let photos = try #require(result.groups.first { $0.files.count == 3 }).files.map(\.url)- let note = try #require(result.groups.flatMap(\.files).first { $0.url.path(percentEncoded: false).contains("/Notes/") }).url+ let note = try #require(+ result.groups.flatMap(\.files).first { $0.url.path(percentEncoded: false).contains("/Notes/") }+ ).urllet excluded = await result.excluded(by: Exclusions(paths: [photos[0], note.deletingLastPathComponent()]))let remaining = result.removing(excluded)@@ -321,7 +328,11 @@ struct DuplicateFinderTests {#expect(result.groups.count == 1)#expect(result.groups.first?.files.count == 2)- #expect(result.groups.first?.files.contains { $0.url.lastPathComponent == "copy.bin" && $0.url.path(percentEncoded: false).contains("/home/Pictures/") } == true)+ #expect(+ result.groups.first?.files.contains {+ $0.url.lastPathComponent == "copy.bin" && $0.url.path(percentEncoded: false).contains("/home/Pictures/")+ } == true+ )#expect(result.folderGroups.map { $0.folders.map(\.url.lastPathComponent) } == [])}@@ -534,16 +545,25 @@ struct DuplicateFinderTests {func aCopyOnADiskThatSharesNothingFreesAllItTakes(fileSystem: String) async throws {let directory = try TemporaryDirectory()let home = try directory.directory("home")- let volume = try ScratchVolume(fileSystem: fileSystem, mountedAt: home.appending(path: "Stick", directoryHint: .isDirectory))+ let volume = try ScratchVolume(+ fileSystem: fileSystem,+ mountedAt: home.appending(path: "Stick", directoryHint: .isDirectory)+ )let photo = randomData(count: 1_048_576)for (path, contents) in [("one/photo.bin", photo), ("two/photo.bin", photo), ("two/other.bin", randomData(count: 4_096))] {let url = volume.url.appending(path: path)- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )try contents.write(to: url)}for folder in ["a", "b"] {let url = volume.url.appending(path: "\(folder)/scan.bin")- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )try photo.prefix(524_288).write(to: url)}@@ -573,7 +593,9 @@ struct DuplicateRemovalTests {}/// Creates and scans two identical files. The first is the copy Peel suggests keeping.- private func duplicates(in directory: borrowing TemporaryDirectory) async throws -> (scan: DuplicateScan, kept: URL, copy: URL) {+ private func duplicates(+ in directory: borrowing TemporaryDirectory+ ) async throws -> (scan: DuplicateScan, kept: URL, copy: URL) {let contents = Data((0..<5_000).map { _ in UInt8.random(in: 0...255) })try directory.file("home/Documents/kept.bin", contents: contents)try directory.file("home/Documents/kept copy.bin", contents: contents)@@ -643,7 +665,11 @@ struct DuplicateRemovalTests {// What Finder does when a file is tagged, and what a sync client does for its own bookkeeping.let value = Data("peel".utf8)- try #require(value.withUnsafeBytes { setxattr(kept.path(percentEncoded: false), "com.peel.test", $0.baseAddress, $0.count, 0, 0) } == 0)+ try #require(+ value.withUnsafeBytes {+ setxattr(kept.path(percentEncoded: false), "com.peel.test", $0.baseAddress, $0.count, 0, 0)+ } == 0+ )let result = await DuplicateRemoval.trash([copy], from: scan, using: try service(in: directory))diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionCommandTests.swiftindex 5e61dcea..cf7b0005 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionCommandTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionCommandTests.swift@@ -25,7 +25,11 @@ struct ExclusionCommandTests {try await (command(["exclusions", "add"] + arguments) as ExclusionsCommand.AddCommand).run(in: store, among: apps)}- private func remove(_ arguments: [String], in store: ExclusionStore, among apps: [InstalledApp]? = nil) async throws {+ private func remove(+ _ arguments: [String],+ in store: ExclusionStore,+ among apps: [InstalledApp]? = nil+ ) async throws {try await (command(["exclusions", "remove"] + arguments) as ExclusionsCommand.RemoveCommand).run(in: store, among: apps)}@@ -162,7 +166,12 @@ struct ExclusionCommandTests {let folder = try directory.directory("Peel")let store = store(in: directory)try directory.setPermissions(0o500, of: folder)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: folder.path(percentEncoded: false)) }+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: folder.path(percentEncoded: false)+ )+ }await #expect(throws: CommandFailure.self) {try await add(["/Users/me/thing"], in: store)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swiftindex bf78d2b0..bb914999 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift@@ -113,7 +113,10 @@ struct ExclusionsTests {let kept = try directory.file("home/Library/Application Support/Example/keep.db")try directory.file("home/Library/Application Support/Example/cache.db")let folder = kept.deletingLastPathComponent()- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )let trash = try directory.directory("Trash")let service = TrashService(environment: environment, exclusions: Exclusions(paths: [kept])) { url inlet destination = trash.appending(path: url.lastPathComponent)@@ -209,7 +212,12 @@ struct ExclusionsTests {let store = ExclusionStore(url: folder.appending(path: "exclusions.json"))await store.save(Exclusions(paths: [URL(filePath: "/Users/x/Kept")]))try directory.setPermissions(0o500, of: folder)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: folder.path(percentEncoded: false)) }+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o700],+ ofItemAtPath: folder.path(percentEncoded: false)+ )+ }let outcome = await store.change { $0.paths.insert(URL(filePath: "/Users/x/Added")) }@@ -245,7 +253,10 @@ struct ExclusionsTests {@Test func movesNothingWhileTheListCannotBeRead() async throws {let directory = try TemporaryDirectory()let item = try directory.file("home/Library/Caches/com.example.app/cache.db").deletingLastPathComponent()- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )let service = TrashService(environment: environment, exclusions: .unreadable) { $0 }let result = await service.trash([item])@@ -273,7 +284,10 @@ struct ExclusionsTests {@Test func movesNothingBeforeTheListIsRead() async throws {let directory = try TemporaryDirectory()let item = try directory.file("home/Library/Caches/com.example.app/cache.db").deletingLastPathComponent()- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )let service = TrashService(environment: environment, exclusions: .notYetRead) { $0 }let result = await service.trash([item])@@ -292,7 +306,8 @@ struct ExclusionsTests {#expect(await store.save(Exclusions(bundleIdentifiers: ["com.example.app"])))#expect(await store.load().bundleIdentifiers == ["com.example.app"])- let kept = try FileManager.default.contentsOfDirectory(atPath: directory.url.path(percentEncoded: false)).filter { $0.contains("damaged") }+ let kept = try FileManager.default.contentsOfDirectory(atPath: directory.url.path(percentEncoded: false)).filter+ { $0.contains("damaged") }#expect(kept.count == 1)#expect(try String(contentsOf: directory.url.appending(path: try #require(kept.first)), encoding: .utf8) == "not json")}@@ -301,7 +316,10 @@ struct ExclusionsTests {let directory = try TemporaryDirectory()let kept = try directory.file("home/Library/Caches/com.example.keep/cache.db").deletingLastPathComponent()let removable = try directory.file("home/Library/Caches/com.example.other/cache.db").deletingLastPathComponent()- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )let trash = try directory.directory("Trash")let service = TrashService(environment: environment, exclusions: Exclusions(paths: [kept])) { url inlet destination = trash.appending(path: url.lastPathComponent)@@ -334,7 +352,10 @@ struct ExclusionsReachEveryScannerTests {""".utf8))let listed = await BackgroundItems.scan(environment: environment(in: directory))- let kept = await BackgroundItems.scan(environment: environment(in: directory), exclusions: Exclusions(paths: [plist]))+ let kept = await BackgroundItems.scan(+ environment: environment(in: directory),+ exclusions: Exclusions(paths: [plist])+ )#expect(listed.contains { $0.label == "com.example.keepme" })#expect(!kept.contains { $0.label == "com.example.keepme" }, "the scanner spells the path with /private and the exclusion does not")@@ -359,7 +380,11 @@ struct ExclusionsReachEveryScannerTests {}let listed = await PackageReceipts.receipts(installing: app, exclusions: .none, pkgutil: pkgutil)- let excluded = await PackageReceipts.receipts(installing: app, exclusions: Exclusions(paths: [app]), pkgutil: pkgutil)+ let excluded = await PackageReceipts.receipts(+ installing: app,+ exclusions: Exclusions(paths: [app]),+ pkgutil: pkgutil+ )#expect(listed.first?.items.count == 1)#expect(excluded.first?.items.isEmpty == true)@@ -372,9 +397,18 @@ struct ExclusionsReachEveryScannerTests {try directory.file("home/Library/Caches/com.example.app/cache.db")let app = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "com.example.app", name: "Example")- let plan = await Uninstallation.prepare(app, installedApps: [app], exclusions: Exclusions(paths: [kept]), environment: environment(in: directory))+ let plan = await Uninstallation.prepare(+ app,+ installedApps: [app],+ exclusions: Exclusions(paths: [kept]),+ environment: environment(in: directory)+ )- let holder = try #require(plan.scan.leftovers.first { $0.url.lastPathComponent == "com.example.app" && $0.kind == .applicationSupport })+ let holder = try #require(+ plan.scan.leftovers.first {+ $0.url.lastPathComponent == "com.example.app" && $0.kind == .applicationSupport+ }+ )#expect(holder.match.heldBack == .holdsAnExclusion)#expect(!holder.match.isRecommended)let suggested = plan.suggestedSelection(canUseHelper: true).map { $0.path(percentEncoded: false) }diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swiftindex c8d27d43..a1cd797b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift@@ -49,7 +49,12 @@ struct FileCommandTests {systemImage: "hammer",appBundleIdentifiers: apps,locations: try locations.map { path, kind in- DeveloperEnvironment.Location(url: try directory.file("home/\(path)/blob", bytes: 30).deletingLastPathComponent(), kind: kind, size: 30, source: "https://example.com/\(path)")+ DeveloperEnvironment.Location(+ url: try directory.file("home/\(path)/blob", bytes: 30).deletingLastPathComponent(),+ kind: kind,+ size: 30,+ source: "https://example.com/\(path)"+ )})}@@ -102,7 +107,12 @@ struct FileCommandTests {let collected = Output.Collected()try await Output.$collected.withValue(collected) {try await (command(["caches", "--remove", "-y"]) as CachesCommand)- .clean([open, closed], using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)+ .clean(+ [open, closed],+ using: try service(in: directory),+ recordingIn: logs.removals,+ refusals: logs.refusals+ )}#expect(await moved(logs) == ["cargo"])#expect(collected.notes.contains("Quit Finder first"))@@ -149,7 +159,12 @@ struct FileCommandTests {let fresh = try artifact("build", lastActivity: .now)try await (command(["projects", "~/Developer", "--remove", "-y"]) as ProjectsCommand)- .clean([stale, fresh], using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)+ .clean(+ [stale, fresh],+ using: try service(in: directory),+ recordingIn: logs.removals,+ refusals: logs.refusals+ )#expect(await moved(logs) == ["DerivedData"])#expect(FileManager.default.fileExists(atPath: fresh.url.path(percentEncoded: false)))@@ -222,7 +237,12 @@ struct FileCommandTests {// MARK: Orphaned files- private func orphan(_ name: String, in directory: borrowing TemporaryDirectory, heldBack: HoldBack? = nil, requiresPrivileges: Bool = false) throws -> OrphanItem {+ private func orphan(+ _ name: String,+ in directory: borrowing TemporaryDirectory,+ heldBack: HoldBack? = nil,+ requiresPrivileges: Bool = false+ ) throws -> OrphanItem {OrphanItem(url: try directory.file("home/Library/Application Support/\(name)/blob", bytes: 10).deletingLastPathComponent(),kind: .applicationSupport,@@ -265,7 +285,15 @@ struct FileCommandTests {let scan = OrphanScan(groups: [wanted, other], unreadableLocations: [])try await (command(["orphans", "--remove", "COM.EXAMPLE.GONE", "-y"]) as OrphansCommand)- .clean("COM.EXAMPLE.GONE", in: scan, apps: [], scanner: scanner(in: directory), using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)+ .clean(+ "COM.EXAMPLE.GONE",+ in: scan,+ apps: [],+ scanner: scanner(in: directory),+ using: try service(in: directory),+ recordingIn: logs.removals,+ refusals: logs.refusals+ )#expect(await moved(logs) == ["com.example.gone"])#expect(FileManager.default.fileExists(atPath: wanted.items[1].url.path(percentEncoded: false)))@@ -308,7 +336,15 @@ struct FileCommandTests {try await Output.$collected.withValue(collected) {try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand)- .clean("com.example.gone", in: scan, apps: [], scanner: scanner(in: directory), using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)+ .clean(+ "com.example.gone",+ in: scan,+ apps: [],+ scanner: scanner(in: directory),+ using: try service(in: directory),+ recordingIn: logs.removals,+ refusals: logs.refusals+ )}#expect(await moved(logs).isEmpty)@@ -331,7 +367,15 @@ struct FileCommandTests {try await Output.$collected.withValue(collected) {try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand)- .clean("com.example.gone", in: scan, apps: [], scanner: scanner(in: directory), using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)+ .clean(+ "com.example.gone",+ in: scan,+ apps: [],+ scanner: scanner(in: directory),+ using: try service(in: directory),+ recordingIn: logs.removals,+ refusals: logs.refusals+ )}#expect(await moved(logs) == ["com.example.gone"])@@ -455,7 +499,9 @@ struct FileCommandTests {])let unread = SearchLocation(kind: .containers, url: URL(filePath: "/Users/me/Library/Containers", directoryHint: .isDirectory))- let json = try Output.jsonText(OrphansCommand.report(for: OrphanScan(groups: [group], unreadableLocations: [unread])))+ let json = try Output.jsonText(+ OrphansCommand.report(for: OrphanScan(groups: [group], unreadableLocations: [unread]))+ )let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])let files = try #require((report["groups"] as? [[String: Any]])?.first?["files"] as? [[String: Any]])diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileLockTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileLockTests.swiftindex 71c961ec..dd5c5f5b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FileLockTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileLockTests.swift@@ -28,7 +28,9 @@ struct FileLockTests {@Test func theTerminalCannotStopAProcessThatHoldsTheLock() throws {let directory = try TemporaryDirectory()- let ignored = FileLock.whileHeld(beside: directory.url.appending(path: "Peel/removals.json")) { SignalDisposition.isIgnored(SIGTSTP) }+ let ignored = FileLock.whileHeld(beside: directory.url.appending(path: "Peel/removals.json")) {+ SignalDisposition.isIgnored(SIGTSTP)+ }#expect(ignored)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swiftindex 6020e9a4..37bd84bb 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift@@ -54,7 +54,13 @@ struct FileSizeTests {try handle.close()}let project = directory.url.appending(path: "project", directoryHint: .isDirectory)- #expect(clonefile(stored.path(percentEncoded: false), project.appending(path: "clone.bin").path(percentEncoded: false), 0) == 0)+ #expect(+ clonefile(+ stored.path(percentEncoded: false),+ project.appending(path: "clone.bin").path(percentEncoded: false),+ 0+ ) == 0+ )try FileManager.default.linkItem(at: shared, to: project.appending(path: "linked.bin"))try FileManager.default.linkItem(at: own, to: project.appending(path: "own again.bin"))@@ -241,7 +247,9 @@ struct FileSizeTests {let read = ScanCount()let isAnswered = Mutex(false)let patient = Task {- let contents = await ScanCount.$current.withValue(read) { await FileSize.contents(of: folder, within: 60) }+ let contents = await ScanCount.$current.withValue(read) {+ await FileSize.contents(of: folder, within: 60)+ }isAnswered.withLock { $0 = true }return contents}@@ -478,9 +486,15 @@ struct FileSizeTests {let log = try directory.file("support/logs/agent.log")let lastYear = Date(timeIntervalSinceNow: -365 * 24 * 60 * 60)let lastMonth = Date(timeIntervalSinceNow: -30 * 24 * 60 * 60)- try FileManager.default.setAttributes([.modificationDate: lastMonth], ofItemAtPath: log.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.modificationDate: lastMonth],+ ofItemAtPath: log.path(percentEncoded: false)+ )for old in [log.deletingLastPathComponent(), folder] {- try FileManager.default.setAttributes([.modificationDate: lastYear], ofItemAtPath: old.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.modificationDate: lastYear],+ ofItemAtPath: old.path(percentEncoded: false)+ )}let newest = try #require(await FileSize.contents(of: folder)?.newestChange)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FolderDuplicateTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FolderDuplicateTests.swiftindex 81fd864d..fc12fe34 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FolderDuplicateTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FolderDuplicateTests.swift@@ -14,13 +14,17 @@ struct FolderDuplicateTests {configure: (inout DuplicateScanOptions) -> Void = { _ in }) async throws -> DuplicateScan {let home = directory.url.appending(path: "home", directoryHint: .isDirectory)- var options = DuplicateScanOptions(folders: folders.map { directory.url.appending(path: $0, directoryHint: .isDirectory) })+ var options = DuplicateScanOptions(+ folders: folders.map { directory.url.appending(path: $0, directoryHint: .isDirectory) }+ )configure(&options)return try await DuplicateFinder(homeDirectory: home).scan(options)}private func names(_ scan: DuplicateScan) -> [[String]] {- scan.folderGroups.map { $0.folders.map { $0.url.pathComponents.drop { $0 != "home" }.dropFirst().joined(separator: "/") } }+ scan.folderGroups.map {+ $0.folders.map { $0.url.pathComponents.drop { $0 != "home" }.dropFirst().joined(separator: "/") }+ }}/// Makes two folders that hold the same files under the same names, and nothing else.@@ -388,7 +392,9 @@ struct FolderDuplicateRemovalTests {}/// Makes two identical folders and scans them. `kept` is the one the scan suggests keeping.- private func duplicates(in directory: borrowing TemporaryDirectory) async throws -> (scan: DuplicateScan, kept: URL, copy: URL) {+ private func duplicates(+ in directory: borrowing TemporaryDirectory+ ) async throws -> (scan: DuplicateScan, kept: URL, copy: URL) {let contents = Data((0..<5_000).map { _ in UInt8.random(in: 0...255) })try directory.file("home/Documents/Trip/photo.jpg", contents: contents)try directory.file("home/Pictures/Trip/photo.jpg", contents: contents)@@ -403,7 +409,12 @@ struct FolderDuplicateRemovalTests {let directory = try TemporaryDirectory()let (scan, kept, copy) = try await duplicates(in: directory)- let result = await DuplicateRemoval.trash([], folders: [kept, copy], from: scan, using: try service(in: directory))+ let result = await DuplicateRemoval.trash(+ [],+ folders: [kept, copy],+ from: scan,+ using: try service(in: directory)+ )#expect(result.trashed.isEmpty)#expect(Set(result.failures.map(\.reason)) == [.lastCopy])diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FoundLastTimeTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FoundLastTimeTests.swiftindex 377e1b9a..fb58ae9b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FoundLastTimeTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FoundLastTimeTests.swift@@ -15,7 +15,10 @@ struct FoundLastTimeTests {let read = FoundLastTime(data: found.data)#expect(read == found)- #expect(read.findings["orphans"] == FoundLastTime.Finding(count: 7, size: SizeTotal(known: 1_200_000, isComplete: true), date: monday))+ #expect(+ read.findings["orphans"]+ == FoundLastTime.Finding(count: 7, size: SizeTotal(known: 1_200_000, isComplete: true), date: monday)+ )#expect(read.findings["applications"] == FoundLastTime.Finding(count: 3, size: nil, date: tuesday))}@@ -47,7 +50,15 @@ struct FoundLastTimeTests {let read = FoundLastTime(data: Data(json.utf8))- #expect(read.findings == ["space": FoundLastTime.Finding(count: 2, size: SizeTotal(known: 10, isComplete: true), date: Date(timeIntervalSinceReferenceDate: 0))])+ #expect(+ read.findings == [+ "space": FoundLastTime.Finding(+ count: 2,+ size: SizeTotal(known: 10, isComplete: true),+ date: Date(timeIntervalSinceReferenceDate: 0)+ )+ ]+ )#expect(FoundLastTime(data: Data("not a list".utf8)).findings.isEmpty)#expect(FoundLastTime(data: nil).findings.isEmpty)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/GitSettingsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/GitSettingsTests.swiftindex f7bd77d8..98e2bb3c 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/GitSettingsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/GitSettingsTests.swift@@ -130,11 +130,26 @@ struct GitSettingsTests {let developer = folder.appending(path: "Developer", directoryHint: .isDirectory)let homebrew = folder.appending(path: "homebrew", directoryHint: .isDirectory)for git in [developer.appending(path: "usr/bin/git"), homebrew.appending(path: "bin/git")] {- try FileManager.default.createDirectory(at: git.deletingLastPathComponent(), withIntermediateDirectories: true)- #expect(FileManager.default.createFile(atPath: git.path(percentEncoded: false), contents: Data(), attributes: [.posixPermissions: 0o755]))+ try FileManager.default.createDirectory(+ at: git.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ #expect(+ FileManager.default.createFile(+ atPath: git.path(percentEncoded: false),+ contents: Data(),+ attributes: [.posixPermissions: 0o755]+ )+ )}- #expect(GitConfig.find(developerFolder: developer, homebrewPrefix: homebrew, home: folder)?.executable == developer.appending(path: "usr/bin/git"))- #expect(GitConfig.find(developerFolder: nil, homebrewPrefix: homebrew, home: folder)?.executable == homebrew.appending(path: "bin/git"))+ #expect(+ GitConfig.find(developerFolder: developer, homebrewPrefix: homebrew, home: folder)?.executable+ == developer.appending(path: "usr/bin/git")+ )+ #expect(+ GitConfig.find(developerFolder: nil, homebrewPrefix: homebrew, home: folder)?.executable+ == homebrew.appending(path: "bin/git")+ )#expect(GitConfig.find(developerFolder: folder.appending(path: "Missing"), homebrewPrefix: nil, home: folder) == nil)}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swiftindex 5312bc18..71bcb5cb 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift@@ -17,7 +17,10 @@ struct HelperLedgerTests {)}- private func ledger(in directory: borrowing TemporaryDirectory, maximumEntries: Int = 20_000) throws -> HelperLedger {+ private func ledger(+ in directory: borrowing TemporaryDirectory,+ maximumEntries: Int = 20_000+ ) throws -> HelperLedger {try #require(HelperLedger(at: directory.url.appending(path: "private/moved.plist"), maximumEntries: maximumEntries))}@@ -26,7 +29,12 @@ struct HelperLedgerTests {}/// Moves a file the way the helper does: written down first, then renamed into the Trash.- private func move(_ relative: String, with ledger: HelperLedger, policy: PrivilegedPathPolicy, in directory: borrowing TemporaryDirectory) throws -> String {+ private func move(+ _ relative: String,+ with ledger: HelperLedger,+ policy: PrivilegedPathPolicy,+ in directory: borrowing TemporaryDirectory+ ) throws -> String {try directory.file(relative)let item = try policy.open(path(relative, in: directory)).get()#expect(ledger.record([item], movedBy: getuid()))@@ -156,7 +164,9 @@ struct HelperLedgerTests {#expect(aside.count == 1, "the damaged ledger was written over")let kept = try aside.map { try Data(contentsOf: directory.url.appending(path: "private/\($0)")) }#expect(kept == [Data("damaged".utf8)])- #expect(try ledger.origin(of: try #require(policy.openInTrash(trashedPath, trash: trash)), movedBy: getuid()) != nil)+ #expect(+ try ledger.origin(of: try #require(policy.openInTrash(trashedPath, trash: trash)), movedBy: getuid()) != nil+ )}@Test func oneEntryItCannotReadCostsThatEntryOnly() throws {@@ -167,7 +177,9 @@ struct HelperLedgerTests {let trashedPath = try move("root/Library/Caches/com.example.plist", with: ledger, policy: policy, in: directory)let url = directory.url.appending(path: "private/moved.plist")- var entries = try #require(try PropertyListSerialization.propertyList(from: Data(contentsOf: url), format: nil) as? [Any])+ var entries = try #require(+ try PropertyListSerialization.propertyList(from: Data(contentsOf: url), format: nil) as? [Any]+ )entries.append(["path": 1])try PropertyListSerialization.data(fromPropertyList: entries, format: .binary, options: 0).write(to: url)@@ -228,7 +240,9 @@ struct HelperLedgerTests {let trash = try #require(policy.openTrash(ownedBy: getuid()))let paths = try ["a.plist", "b.plist", "c.plist"].map { try move("root/Library/Caches/\($0)", with: ledger, policy: policy, in: directory) }- let origins = try paths.map { try ledger.origin(of: try #require(policy.openInTrash($0, trash: trash)), movedBy: getuid()) }+ let origins = try paths.map {+ try ledger.origin(of: try #require(policy.openInTrash($0, trash: trash)), movedBy: getuid())+ }#expect(origins.map { $0 != nil } == [false, true, true])let attributes = try FileManager.default.attributesOfItem(atPath: path("private/moved.plist", in: directory))diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HelperReplyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HelperReplyTests.swiftindex df3a9894..926dd360 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HelperReplyTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HelperReplyTests.swift@@ -7,7 +7,11 @@ import Testing/// The helper's trash method as a dishonest helper would answer it: the same selector, with replies of any kind.@objc private protocol LooseTrashReplies {@objc(moveItemsToTrashWithVersion:atPaths:withReply:)- func moveItemsToTrash(version: Int, atPaths paths: [String], withReply reply: @escaping (NSDictionary, NSDictionary) -> Void)+ func moveItemsToTrash(+ version: Int,+ atPaths paths: [String],+ withReply reply: @escaping (NSDictionary, NSDictionary) -> Void+ )}private final class Answers: NSObject, LooseTrashReplies, NSXPCListenerDelegate {@@ -17,7 +21,11 @@ private final class Answers: NSObject, LooseTrashReplies, NSXPCListenerDelegateself.moved = moved}- func moveItemsToTrash(version: Int, atPaths paths: [String], withReply reply: @escaping (NSDictionary, NSDictionary) -> Void) {+ func moveItemsToTrash(+ version: Int,+ atPaths paths: [String],+ withReply reply: @escaping (NSDictionary, NSDictionary) -> Void+ ) {reply(moved, [:] as NSDictionary)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swiftindex b66956ec..6242d006 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift@@ -96,7 +96,10 @@ struct HistoryCommandTests {}/// What `arguments` print, read the way a person or a script would read it.- private func printed(_ arguments: [String], from logs: (removals: RemovalLog, refusals: RefusalLog)) async throws -> String {+ private func printed(+ _ arguments: [String],+ from logs: (removals: RemovalLog, refusals: RefusalLog)+ ) async throws -> String {let collected = Output.Collected()try await Output.$collected.withValue(collected) {try await (command(arguments) as HistoryCommand).run(in: logs.removals, refusals: logs.refusals)@@ -216,7 +219,11 @@ struct HistoryCommandTests {let known = try removal(in: directory).recordlet unknown = RemovalRecord(batch: known.batch,- item: TrashedItem(originalURL: directory.url.appending(path: "home/Documents/notes.txt"), trashedURL: try directory.file("home/.Trash/notes.txt", bytes: 3), date: .now),+ item: TrashedItem(+ originalURL: directory.url.appending(path: "home/Documents/notes.txt"),+ trashedURL: try directory.file("home/.Trash/notes.txt", bytes: 3),+ date: .now+ ),size: nil,source: "Editor",tool: "applications"@@ -238,10 +245,23 @@ struct HistoryCommandTests {let measured = TrashedItem(originalURL: URL(filePath: "/Users/me/a.txt"), trashedURL: URL(filePath: "/Users/me/.Trash/a.txt"), date: .now)let unmeasured = TrashedItem(originalURL: URL(filePath: "/Users/me/b"), trashedURL: URL(filePath: "/Users/me/.Trash/b"), date: .now)- #expect(await Removals.record(TrashResult(trashed: [measured, unmeasured]), from: "Editor", sizes: [measured.originalURL: 5], tool: "applications", in: logs.removals, refusals: logs.refusals))+ #expect(+ await Removals.record(+ TrashResult(trashed: [measured, unmeasured]),+ from: "Editor",+ sizes: [measured.originalURL: 5],+ tool: "applications",+ in: logs.removals,+ refusals: logs.refusals+ )+ )let records = try #require(await logs.removals.load().records)- #expect(Dictionary(uniqueKeysWithValues: records.map { ($0.originalURL.lastPathComponent, $0.size) }) == ["a.txt": 5, "b": nil])+ #expect(+ Dictionary(uniqueKeysWithValues: records.map { ($0.originalURL.lastPathComponent, $0.size) }) == [+ "a.txt": 5, "b": nil,+ ]+ )}/// `--limit` counts removals, as the app lists refusals one removal to an entry, and `--json` writes each removal@@ -295,7 +315,12 @@ struct HistoryCommandTests {let logs = logs(in: directory)let file = try directory.file("Peel/removals.json", contents: Data("not json".utf8))try directory.setPermissions(0, of: file)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: file.path(percentEncoded: false)) }+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o644],+ ofItemAtPath: file.path(percentEncoded: false)+ )+ }await #expect(throws: CommandFailure.self) {try await (command(["history"]) as HistoryCommand).run(in: logs.removals, refusals: logs.refusals)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HomeTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HomeTests.swiftindex 04c3bcc8..ce9617d9 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HomeTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HomeTests.swift@@ -29,7 +29,13 @@ struct GreetingTests {#expect(Greeting.change(after: date(3), calendar: calendar) == date(5))#expect(Greeting.change(after: date(5), calendar: calendar) == date(12))#expect(Greeting.change(after: date(12, 30), calendar: calendar) == date(18))- #expect(Greeting.change(after: date(19), calendar: calendar) == calendar.date(byAdding: .day, value: 1, to: date(5))!)+ #expect(+ Greeting.change(after: date(19), calendar: calendar) == calendar.date(+ byAdding: .day,+ value: 1,+ to: date(5)+ )!+ )}}@@ -47,7 +53,10 @@ struct DeviceInfoTests {/// What is free is the room macOS would make for an important file, which counts what it can purge. A volume/// that does not report that answers zero, and its plain free space is then what is free.@Test func freeSpaceIsThePlainFreeSpaceWhereTheVolumeDoesNotSayMore() {- #expect(DeviceInfo.storage(total: 245_107_195_904, available: 48_015_052_800, important: 58_789_408_280).free == 58_789_408_280)+ #expect(+ DeviceInfo.storage(total: 245_107_195_904, available: 48_015_052_800, important: 58_789_408_280).free+ == 58_789_408_280+ )#expect(DeviceInfo.storage(total: 536_829_952, available: 459_358_208, important: 0).free == 459_358_208)#expect(DeviceInfo.storage(total: nil, available: nil, important: nil) == DeviceInfo.Storage(total: 0, free: 0))}@@ -66,8 +75,14 @@ struct DeviceInfoTests {}@Test func leavesOutAZeroPatchVersion() {- #expect(DeviceInfo.versionString(OperatingSystemVersion(majorVersion: 26, minorVersion: 7, patchVersion: 0)) == "26.7")- #expect(DeviceInfo.versionString(OperatingSystemVersion(majorVersion: 26, minorVersion: 7, patchVersion: 1)) == "26.7.1")+ #expect(+ DeviceInfo.versionString(OperatingSystemVersion(majorVersion: 26, minorVersion: 7, patchVersion: 0))+ == "26.7"+ )+ #expect(+ DeviceInfo.versionString(OperatingSystemVersion(majorVersion: 26, minorVersion: 7, patchVersion: 1))+ == "26.7.1"+ )}@Test func readsTheModelNameFromSystemProfiler() {@@ -172,7 +187,10 @@ struct AccessTests {struct PrivacyDatabaseTests {private func database(at url: URL, rows: [(service: String, client: String, type: Int32, auth: Int32)]) throws {var handle: OpaquePointer?- try #require(sqlite3_open_v2(url.path(percentEncoded: false), &handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nil) == SQLITE_OK)+ try #require(+ sqlite3_open_v2(url.path(percentEncoded: false), &handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nil)+ == SQLITE_OK+ )defer { sqlite3_close(handle) }try #require(sqlite3_exec(handle, "CREATE TABLE access (service TEXT, client TEXT, client_type INTEGER, auth_value INTEGER)", nil, nil, nil) == SQLITE_OK)for row in rows {@@ -210,7 +228,13 @@ struct PrivacyDatabaseTests {#expect(PrivacyDatabase.decision(on: AppManagement.service, for: "com.example.App", in: missing) == .unknown)let notADatabase = try directory.file("other.db", contents: Data("not a database".utf8))- #expect(PrivacyDatabase.decision(on: AppManagement.service, for: "com.example.App", in: notADatabase.path(percentEncoded: false)) == .unknown)+ #expect(+ PrivacyDatabase.decision(+ on: AppManagement.service,+ for: "com.example.App",+ in: notADatabase.path(percentEncoded: false)+ ) == .unknown+ )}/// The root helper needs no permission of Peel's, so a bundle it moved proves nothing about App Management.@@ -227,7 +251,10 @@ struct PrivacyDatabaseTests {@Test func knowsItsOwnCommandLineTool() throws {let directory = try TemporaryDirectory()let embedded = try directory.file("Peel.app/Contents/Helpers/peel", bytes: 16)- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: embedded.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: embedded.path(percentEncoded: false)+ )let link = directory.url.appending(path: "peel").path(percentEncoded: false)let bundle = directory.url.appending(path: "Peel.app", directoryHint: .isDirectory)func standing() -> CommandLineTool.Standing {@@ -235,11 +262,18 @@ struct PrivacyDatabaseTests {}#expect(standing() == .missing)- try FileManager.default.createSymbolicLink(atPath: link, withDestinationPath: embedded.path(percentEncoded: false))+ try FileManager.default.createSymbolicLink(+ atPath: link,+ withDestinationPath: embedded.path(percentEncoded: false)+ )#expect(standing() == .installed)try FileManager.default.removeItem(atPath: link)- try FileManager.default.createSymbolicLink(atPath: link, withDestinationPath: directory.url.appending(path: "Gone.app/Contents/Helpers/peel").path(percentEncoded: false))+ try FileManager.default.createSymbolicLink(+ atPath: link,+ withDestinationPath: directory.url.appending(path: "Gone.app/Contents/Helpers/peel")+ .path(percentEncoded: false)+ )#expect(standing() == .otherPeel, "a link to a Peel that is gone read as installed")try FileManager.default.removeItem(atPath: link)@@ -248,7 +282,10 @@ struct PrivacyDatabaseTests {try FileManager.default.removeItem(atPath: link)let stranger = try directory.file("stranger", bytes: 16)- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: stranger.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: stranger.path(percentEncoded: false)+ )try FileManager.default.copyItem(atPath: stranger.path(percentEncoded: false), toPath: link)#expect(standing() == .somethingElse, "somebody else's executable read as Peel's tool")}@@ -269,7 +306,10 @@ struct PrivacyDatabaseTests {@Test func findsTheCommandWhereHomebrewLinkedIt() throws {let directory = try TemporaryDirectory()let embedded = try directory.file("Peel.app/Contents/Helpers/peel", bytes: 16)- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: embedded.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: embedded.path(percentEncoded: false)+ )let peels = directory.url.appending(path: "usr-local-bin-peel").path(percentEncoded: false)let homebrews = directory.url.appending(path: "opt-homebrew-bin-peel").path(percentEncoded: false)func isOnThePath() -> Bool {@@ -277,7 +317,10 @@ struct PrivacyDatabaseTests {}#expect(!isOnThePath())- try FileManager.default.createSymbolicLink(atPath: homebrews, withDestinationPath: embedded.path(percentEncoded: false))+ try FileManager.default.createSymbolicLink(+ atPath: homebrews,+ withDestinationPath: embedded.path(percentEncoded: false)+ )#expect(isOnThePath(), "Homebrew's link was not counted")#expect(CommandLineTool.paths == ["/usr/local/bin/peel", "/opt/homebrew/bin/peel"])}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swiftindex 835f9aa4..d09523ca 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift@@ -57,7 +57,10 @@ struct HomebrewTests {/// Formulae and casks are upgraded in two calls, and the second is made even when the first never finished,/// as when it ran out of time: the casks were otherwise never tried, and the report left them out.@Test func upgradesTheCasksEvenWhenTheFormulaeNeverFinished() async {- let packages = [HomebrewPackage(name: "wget", kind: .formula, installedVersion: "1.0"), HomebrewPackage(name: "firefox", kind: .cask, installedVersion: "1.0")]+ let packages = [+ HomebrewPackage(name: "wget", kind: .formula, installedVersion: "1.0"),+ HomebrewPackage(name: "firefox", kind: .cask, installedVersion: "1.0"),+ ]let asked = Mutex<[String]>([])do {@@ -101,7 +104,10 @@ struct HomebrewTests {/// A stop is the person's: once the formulae were stopped, the casks are not started.@Test func aStoppedUpgradeStartsNothingMore() async {- let packages = [HomebrewPackage(name: "wget", kind: .formula, installedVersion: "1.0"), HomebrewPackage(name: "firefox", kind: .cask, installedVersion: "1.0")]+ let packages = [+ HomebrewPackage(name: "wget", kind: .formula, installedVersion: "1.0"),+ HomebrewPackage(name: "firefox", kind: .cask, installedVersion: "1.0"),+ ]let asked = Mutex<[String]>([])let run = Task { () -> String? in@@ -218,7 +224,9 @@ struct HomebrewTests {"""let packages = try #require(Homebrew.parseInstalled(Data(json.utf8)))let needs = { (name: String) in- packages.first { $0.name == name }.map { [$0.upgradeNeedsAnAdministrator, $0.uninstallNeedsAnAdministrator] }+ packages.first { $0.name == name }.map {+ [$0.upgradeNeedsAnAdministrator, $0.uninstallNeedsAnAdministrator]+ }}#expect(needs("meeting") == [true, true], "an installer package and `pkgutil` both run with sudo")@@ -276,10 +284,42 @@ struct HomebrewTests {func retirement(_ name: String) -> HomebrewRetirement? { packages.first { $0.name == name }?.retirement }func day(_ text: String) -> Date { try! Date(text, strategy: .iso8601.year().month().day()) }- #expect(retirement("aces_container") == HomebrewRetirement(stage: .deprecated, reason: .repositoryArchived, disableDate: day("2027-06-05"), replacement: .formula("openimageio")))- #expect(retirement("aescrypt-packetizer") == HomebrewRetirement(stage: .disabled, reason: .written("switched to a commercial license in v4"), disableDate: day("2026-03-17"), replacement: nil))- #expect(retirement("1kc-razer") == HomebrewRetirement(stage: .disabled, reason: .failsGatekeeperCheck, disableDate: day("2026-09-01"), replacement: .cask("razer-synapse")))- #expect(retirement("active-trader-pro") == HomebrewRetirement(stage: .deprecated, reason: .discontinued, disableDate: day("2026-12-17"), replacement: nil))+ #expect(+ retirement("aces_container")+ == HomebrewRetirement(+ stage: .deprecated,+ reason: .repositoryArchived,+ disableDate: day("2027-06-05"),+ replacement: .formula("openimageio")+ )+ )+ #expect(+ retirement("aescrypt-packetizer")+ == HomebrewRetirement(+ stage: .disabled,+ reason: .written("switched to a commercial license in v4"),+ disableDate: day("2026-03-17"),+ replacement: nil+ )+ )+ #expect(+ retirement("1kc-razer")+ == HomebrewRetirement(+ stage: .disabled,+ reason: .failsGatekeeperCheck,+ disableDate: day("2026-09-01"),+ replacement: .cask("razer-synapse")+ )+ )+ #expect(+ retirement("active-trader-pro")+ == HomebrewRetirement(+ stage: .deprecated,+ reason: .discontinued,+ disableDate: day("2026-12-17"),+ replacement: nil+ )+ )#expect(retirement("abricate") == nil, "a deprecation dated ahead has not happened yet")#expect(retirement("sample") == nil)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HushLoginTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HushLoginTests.swiftindex 97155502..03920bdb 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HushLoginTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HushLoginTests.swift@@ -37,7 +37,9 @@ struct HushLoginTests {defer { try? FileManager.default.removeItem(at: home) }#expect(HushLogin.turnOn(in: home))- let attributes = try FileManager.default.attributesOfItem(atPath: HushLogin.url(in: home).path(percentEncoded: false))+ let attributes = try FileManager.default.attributesOfItem(+ atPath: HushLogin.url(in: home).path(percentEncoded: false)+ )#expect(attributes[.type] as? FileAttributeType == .typeRegular)#expect(attributes[.size] as? Int == 0)let permissions = try #require(attributes[.posixPermissions] as? Int)@@ -50,11 +52,16 @@ struct HushLoginTests {defer { try? FileManager.default.removeItem(at: home) }let file = HushLogin.url(in: home)try Data("kept".utf8).write(to: file)- let before = try FileManager.default.attributesOfItem(atPath: file.path(percentEncoded: false))[.systemFileNumber] as? Int+ let before =+ try FileManager.default.attributesOfItem(atPath: file.path(percentEncoded: false))[.systemFileNumber]+ as? Int#expect(HushLogin.turnOn(in: home))#expect(try Data(contentsOf: file) == Data("kept".utf8))- #expect(try FileManager.default.attributesOfItem(atPath: file.path(percentEncoded: false))[.systemFileNumber] as? Int == before)+ #expect(+ try FileManager.default.attributesOfItem(atPath: file.path(percentEncoded: false))[.systemFileNumber]+ as? Int == before+ )}@Test func turningOnNeverWritesThroughALink() throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swiftindex d050c12e..db11a064 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift@@ -19,7 +19,14 @@ struct InstallersTests {let unanswered = Unanswered()let stop = try await unanswered.stop {- _ = await Installers.scan(installedApps: [], home: directory.url, root: directory.url, exclusions: .none, minimumSize: 0, measure: unanswered.walk)+ _ = await Installers.scan(+ installedApps: [],+ home: directory.url,+ root: directory.url,+ exclusions: .none,+ minimumSize: 0,+ measure: unanswered.walk+ )}#expect(stop.took < .seconds(1))@@ -389,7 +396,13 @@ struct InstallersTests {try directory.directory("Applications")let asked = Mutex<[String]>([])- let scan = await Installers.scan(installedApps: [], home: directory.url, root: directory.url, exclusions: .none, minimumSize: 100_000) { url in+ let scan = await Installers.scan(+ installedApps: [],+ home: directory.url,+ root: directory.url,+ exclusions: .none,+ minimumSize: 100_000+ ) { url inasked.withLock { $0.append(url.lastPathComponent) }return await FileSize.contents(of: url)}@@ -409,7 +422,13 @@ struct InstallersTests {let home = directory.urllet scan = Task {- await Installers.scan(installedApps: [], home: home, root: home, exclusions: .none, minimumSize: 100_000) { _ in+ await Installers.scan(+ installedApps: [],+ home: home,+ root: home,+ exclusions: .none,+ minimumSize: 100_000+ ) { _ inmeasured.withLock { $0 += 1 }while !Task.isCancelled { await Task.yield() }return FolderContents(size: 400_000, holdsRepository: false)@@ -431,7 +450,13 @@ struct InstallersTests {try directory.file("Library/Application Support/MobileSync/Backup/quick/blob", bytes: 400_000)try directory.directory("Applications")- let scan = await Installers.scan(installedApps: [], home: directory.url, root: directory.url, exclusions: .none, minimumSize: 100_000) { url in+ let scan = await Installers.scan(+ installedApps: [],+ home: directory.url,+ root: directory.url,+ exclusions: .none,+ minimumSize: 100_000+ ) { url inurl.lastPathComponent == "slow" ? nil : await FileSize.contents(of: url)}@@ -448,7 +473,13 @@ struct InstallersTests {try directory.file("Downloads/Suite.mpkg/Contents/Packages/one.pkg", bytes: 16)try directory.directory("Applications")- let scan = await Installers.scan(installedApps: [], home: directory.url, root: directory.url, exclusions: .none, minimumSize: 100_000) { _ in nil }+ let scan = await Installers.scan(+ installedApps: [],+ home: directory.url,+ root: directory.url,+ exclusions: .none,+ minimumSize: 100_000+ ) { _ in nil }#expect(scan.items(in: .appInstaller).map(\.name) == ["Suite.mpkg"])#expect(scan.items.first?.size == nil)@@ -470,7 +501,10 @@ struct InstallersTests {try (PropertyListSerialization.data(fromPropertyList: ["IsEncrypted": true], format: .xml, options: 0)).write(to: backup.appending(path: "Manifest.plist"))- let items = await Installers.backups(in: directory.url.appending(path: "Backup", directoryHint: .isDirectory), measure: LeftoverScanner.walk)+ let items = await Installers.backups(+ in: directory.url.appending(path: "Backup", directoryHint: .isDirectory),+ measure: LeftoverScanner.walk+ )let item = try #require(items.first)#expect(item.name == "Zoë's iPhone")@@ -480,7 +514,10 @@ struct InstallersTests {let tablet = try directory.directory("Backup/00008112-00AB")try (PropertyListSerialization.data(fromPropertyList: ["Product Type": "iPad13,4", "Product Version": "26.1"], format: .xml, options: 0)).write(to: tablet.appending(path: "Info.plist"))- let tablets = await Installers.backups(in: directory.url.appending(path: "Backup", directoryHint: .isDirectory), measure: LeftoverScanner.walk)+ let tablets = await Installers.backups(+ in: directory.url.appending(path: "Backup", directoryHint: .isDirectory),+ measure: LeftoverScanner.walk+ )#expect(tablets.first { $0.url.lastPathComponent == "00008112-00AB" }?.notes == [.name("iPad13,4"), .name("iPadOS 26.1")])#expect(item.date == Date(timeIntervalSince1970: 1_700_000_000))#expect(item.isReadOnly)@@ -501,14 +538,22 @@ struct InstallersTests {)#expect(kept.items.isEmpty)- let tooSmall = await Installers.scan(installedApps: [], home: directory.url, root: directory.url, minimumSize: 1_000_000)+ let tooSmall = await Installers.scan(+ installedApps: [],+ home: directory.url,+ root: directory.url,+ minimumSize: 1_000_000+ )#expect(tooSmall.items.isEmpty)}/// `/Library/Updates` belongs to Software Update, and a backup is never Peel's to move.@Test func theGuardRefusesStagedSystemUpdates() throws {let directory = try TemporaryDirectory()- let environment = SearchEnvironment(homeDirectory: directory.url, rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url,+ rootDirectory: directory.url.appending(path: "root")+ )let guardian = RemovalGuard(environment: environment)#expect(!guardian.allowsRemoval(of: URL(filePath: "/Library/Updates")))diff --git a/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swiftindex 38034318..01f2a86a 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift@@ -7,7 +7,9 @@ struct IntelInspectorTests {private func fatHeader(_ cpuTypes: [UInt32]) -> Data {var bytes: [UInt8] = []func append(_ value: UInt32) {- bytes += [UInt8(value >> 24 & 0xFF), UInt8(value >> 16 & 0xFF), UInt8(value >> 8 & 0xFF), UInt8(value & 0xFF)]+ bytes += [+ UInt8(value >> 24 & 0xFF), UInt8(value >> 16 & 0xFF), UInt8(value >> 8 & 0xFF), UInt8(value & 0xFF),+ ]}append(0xCAFE_BABE)append(UInt32(cpuTypes.count))@@ -50,7 +52,14 @@ struct IntelInspectorTests {let installed = appslet stop = try await unanswered.stop {- _ = await IntelInspector.scan(installedApps: installed, plugins: [], backgroundItems: [], exclusions: .none, environment: environment, measure: unanswered.measure)+ _ = await IntelInspector.scan(+ installedApps: installed,+ plugins: [],+ backgroundItems: [],+ exclusions: .none,+ environment: environment,+ measure: unanswered.measure+ )}#expect(stop.took < .seconds(1))@@ -62,7 +71,10 @@ struct IntelInspectorTests {let name = (path as NSString).lastPathComponentlet executableName = (name as NSString).deletingPathExtensionlet executable = try directory.file("\(path)/Contents/MacOS/\(executableName)", contents: fatHeader(cpuTypes))- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: executable.path(percentEncoded: false)+ )try directory.file("\(path)/Contents/Info.plist", contents: Data("<plist></plist>".utf8))return directory.url.appending(path: path, directoryHint: .isDirectory)}@@ -163,9 +175,14 @@ struct IntelInspectorTests {let plainHelper = try directory.file("Universal.app/Contents/Helpers/updater", contents: intelHeader(fileType: 2))- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: plainHelper.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: plainHelper.path(percentEncoded: false)+ )- let found = IntelInspector.intelOnlyBundles(inside: directory.url.appending(path: "Universal.app", directoryHint: .isDirectory))+ let found = IntelInspector.intelOnlyBundles(+ inside: directory.url.appending(path: "Universal.app", directoryHint: .isDirectory)+ )#expect(Set(found.map(\.lastPathComponent)) == ["Launcher.app", "Old.appex", "updater"])}@@ -220,9 +237,14 @@ struct IntelInspectorTests {_ = try bundle(directory, "Electron.app/Contents/Library/LaunchServices/com.example.helper.app", cpuTypes: [intel])// A library is loaded into the app, never run on its own.let library = try directory.file("Electron.app/Contents/Frameworks/libswiftCore.dylib", contents: fatHeader([intel]))- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: library.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: library.path(percentEncoded: false)+ )- let found = IntelInspector.intelOnlyBundles(inside: directory.url.appending(path: "Electron.app", directoryHint: .isDirectory))+ let found = IntelInspector.intelOnlyBundles(+ inside: directory.url.appending(path: "Electron.app", directoryHint: .isDirectory)+ )#expect(Set(found.map(\.lastPathComponent)) == ["Electron Helper (GPU).app", "Installer.xpc", "com.example.helper.app"])}@@ -235,10 +257,18 @@ struct IntelInspectorTests {_ = try bundle(directory, "Updater.app", cpuTypes: [intel, appleSilicon])_ = try bundle(directory, "Updater.app/Contents/Frameworks/Sparkle.framework/Versions/B/XPCServices/Installer.xpc", cpuTypes: [intel])let framework = directory.url.appending(path: "Updater.app/Contents/Frameworks/Sparkle.framework")- try FileManager.default.createSymbolicLink(atPath: framework.appending(path: "Versions/Current").path(percentEncoded: false), withDestinationPath: "B")- try FileManager.default.createSymbolicLink(atPath: framework.appending(path: "XPCServices").path(percentEncoded: false), withDestinationPath: "Versions/Current/XPCServices")+ try FileManager.default.createSymbolicLink(+ atPath: framework.appending(path: "Versions/Current").path(percentEncoded: false),+ withDestinationPath: "B"+ )+ try FileManager.default.createSymbolicLink(+ atPath: framework.appending(path: "XPCServices").path(percentEncoded: false),+ withDestinationPath: "Versions/Current/XPCServices"+ )- let found = IntelInspector.intelOnlyBundles(inside: directory.url.appending(path: "Updater.app", directoryHint: .isDirectory))+ let found = IntelInspector.intelOnlyBundles(+ inside: directory.url.appending(path: "Updater.app", directoryHint: .isDirectory)+ )#expect(found.filter { $0.lastPathComponent == "Installer.xpc" }.count == 1, "listed under \(found.map { $0.path(percentEncoded: false) })")}@@ -247,7 +277,10 @@ struct IntelInspectorTests {@Test func reportsOneProgramOnceHoweverManyJobsRunIt() async throws {let directory = try TemporaryDirectory()let program = try directory.file("usr/local/bin/agent", contents: fatHeader([intel]))- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: program.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: program.path(percentEncoded: false)+ )func job(_ label: String) -> BackgroundItem {BackgroundItem(label: label, kind: .agent, source: .userLibrary, plistURL: nil,@@ -305,7 +338,8 @@ struct IntelInspectorTests {#expect(SizeTotal(scan.findings.map(\.size)).known > 0)// An app that did not answer in time is still Intel only: it is listed, with a size nobody knows.- let slow = await IntelInspector.scan(installedApps: [app], plugins: [], backgroundItems: [], exclusions: .none) { _ in nil }+ let slow = await IntelInspector.scan(installedApps: [app], plugins: [], backgroundItems: [], exclusions: .none)+ { _ in nil }#expect(slow.findings.map(\.kind) == [.app])#expect(slow.findings.first?.size == nil)#expect(!SizeTotal(slow.findings.map(\.size)).isComplete)@@ -322,7 +356,10 @@ struct IntelInspectorTests {// Real Intel only binaries, executable, so they would be reported if the folder were searched.for path in ["Universal.app/Contents/Frameworks/libswiftCore.dylib", "Universal.app/Contents/Frameworks/Vendor.framework/Vendor"] {let library = try directory.file(path, contents: fatHeader([intel]))- try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: library.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: library.path(percentEncoded: false)+ )}let found = IntelInspector.intelOnlyBundles(inside: app)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/InventoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/InventoryTests.swiftindex 3bd173f4..c70ebfc2 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/InventoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/InventoryTests.swift@@ -37,7 +37,10 @@ struct InventoryTests {casks: [cask])- let sources = Dictionary(inventory.entries.map { ($0.name, $0.source) }, uniquingKeysWith: { first, _ in first })+ let sources = Dictionary(+ inventory.entries.map { ($0.name, $0.source) },+ uniquingKeysWith: { first, _ in first }+ )#expect(sources["Bear"] == "Homebrew")#expect(sources["Shazam"] == "App Store")#expect(sources["AdGuard"] == "Sparkle")@@ -77,7 +80,15 @@ struct InventoryTests {let quarantined = try directory.directory("Applications/Quarantined.app")let local = try directory.directory("Applications/Local.app")try directory.directory("Applications/Plain.app")- try setAttribute("com.apple.metadata:kMDItemWhereFroms", PropertyListSerialization.data(fromPropertyList: ["https://example.com/Tagged-2.dmg?token=secret#top", "https://example.com/"], format: .binary, options: 0), on: tagged)+ try setAttribute(+ "com.apple.metadata:kMDItemWhereFroms",+ PropertyListSerialization.data(+ fromPropertyList: ["https://example.com/Tagged-2.dmg?token=secret#top", "https://example.com/"],+ format: .binary,+ options: 0+ ),+ on: tagged+ )try setAttribute("com.apple.metadata:kMDItemWhereFroms", PropertyListSerialization.data(fromPropertyList: ["file:///Users/me/Tagged.dmg"], format: .binary, options: 0), on: local)try setAttribute("com.apple.quarantine", Data("0083;66f0f0f0;Safari;7F3A6E0C-1B2D-4C5E-8F90-A1B2C3D4E5F6".utf8), on: quarantined)let events = directory.url.appending(path: "QuarantineEventsV2")@@ -86,7 +97,11 @@ struct InventoryTests {"INSERT INTO LSQuarantineEvent (LSQuarantineEventIdentifier, LSQuarantineDataURLString, LSQuarantineOriginURLString) VALUES ('7F3A6E0C-1B2D-4C5E-8F90-A1B2C3D4E5F6', 'https://downloads.example.org/Quarantined.zip?Expires=1', 'https://example.org/download')",])let apps = ["Tagged", "Quarantined", "Local", "Plain"].map { name in- InstalledApp(url: directory.url.appending(path: "Applications/\(name).app", directoryHint: .isDirectory), bundleIdentifier: "com.example.\(name.lowercased())", name: name)+ InstalledApp(+ url: directory.url.appending(path: "Applications/\(name).app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.\(name.lowercased())",+ name: name+ )}let inventory = Inventory.build(apps: apps, origins: DownloadOrigins(events: events))@@ -121,7 +136,9 @@ struct InventoryTests {}private func setAttribute(_ name: String, _ value: Data, on url: URL) throws {- let status = value.withUnsafeBytes { setxattr(url.path(percentEncoded: false), name, $0.baseAddress, value.count, 0, XATTR_NOFOLLOW) }+ let status = value.withUnsafeBytes {+ setxattr(url.path(percentEncoded: false), name, $0.baseAddress, value.count, 0, XATTR_NOFOLLOW)+ }#expect(status == 0)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/KnownCasksTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/KnownCasksTests.swiftindex 47d39d5f..742a615f 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/KnownCasksTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/KnownCasksTests.swift@@ -133,7 +133,13 @@ struct KnownCasksTests {#expect(artifact.appNames == ["Firefox.app"])#expect(artifact.appTargets == ["/Applications/Firefox.app"])- let cask = HomebrewPackage(name: "firefox", kind: .cask, installedVersion: "130.0", appNames: artifact.appNames, appTargets: artifact.appTargets)+ let cask = HomebrewPackage(+ name: "firefox",+ kind: .cask,+ installedVersion: "130.0",+ appNames: artifact.appNames,+ appTargets: artifact.appTargets+ )let brewed = app("Firefox", "org.mozilla.firefox")let copy = InstalledApp(url: URL(filePath: "/Users/me/Applications/Firefox.app", directoryHint: .isDirectory), bundleIdentifier: "org.mozilla.firefox", name: "Firefox")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swiftindex ebdce92d..5ba8357c 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift@@ -72,7 +72,13 @@ struct LeftoverMatcherTests {let sketchpad = app("org.example.Sketchpad", name: "Sketchpad")let folder = URL(filePath: "/Users/x/Library/Application Support/Sketchpad")func claim(besides rivals: [InstalledApp]) throws -> LeftoverMatch {- try #require(LeftoverMatcher(app: sketchpad, installedApps: [sketchpad] + rivals).match(fileName: "Sketchpad", kind: .applicationSupport, at: folder))+ try #require(+ LeftoverMatcher(app: sketchpad, installedApps: [sketchpad] + rivals).match(+ fileName: "Sketchpad",+ kind: .applicationSupport,+ at: folder+ )+ )}func agent(at url: URL) -> InstalledApp {InstalledApp(url: url, bundleIdentifier: "org.example.agent", name: "SketchpadAgent")@@ -81,7 +87,12 @@ struct LeftoverMatcherTests {InstalledApp(url: url, bundleIdentifier: sketchpad.bundleIdentifier, name: "Sketchpad")}- #expect(try claim(besides: [agent(at: folder.appending(path: "SketchpadAgent.app")), update(at: folder.appending(path: "Updates/Sketchpad.app"))]).isRecommended)+ #expect(+ try claim(besides: [+ agent(at: folder.appending(path: "SketchpadAgent.app")),+ update(at: folder.appending(path: "Updates/Sketchpad.app")),+ ]).isRecommended+ )#expect(try claim(besides: [agent(at: URL(filePath: "/Volumes/Disk/SketchpadAgent.app"))]).sharedWith == ["org.example.agent"])#expect(try claim(besides: [update(at: URL(filePath: "/Users/x/Downloads/Sketchpad.app"))]).otherCopies.count == 1)}@@ -186,7 +197,9 @@ struct LeftoverMatcherTests {let orders = [[word, excel, outlook], [outlook, excel, word], [excel, word, outlook]]for (fileName, kind) in [("UBF8T346G9.Office", SearchLocation.Kind.groupContainers), ("com.microsoft.Word.plist", .preferences), ("com.microsoft.autoupdate2.plist", .preferences)] {- let answers = orders.map { LeftoverMatcher(app: word, installedApps: $0) { _ in nil }.match(fileName: fileName, kind: kind) }+ let answers = orders.map {+ LeftoverMatcher(app: word, installedApps: $0) { _ in nil }.match(fileName: fileName, kind: kind)+ }#expect(Set(answers).count == 1, "\(fileName) is judged differently depending on the order")}}@@ -396,7 +409,11 @@ struct LeftoverMatcherTests {let claimed = try #require(match("com.example.notes", in: .caches, for: target, with: [namesake]))#expect(claimed.sharedWith == [namesake.bundleIdentifier])- #expect(try #require(match("com.example.notes", in: .caches, for: namesake, with: [target])).sharedWith == [target.bundleIdentifier])+ #expect(+ try #require(match("com.example.notes", in: .caches, for: namesake, with: [target])).sharedWith == [+ target.bundleIdentifier+ ]+ )}/// Any developer can write one of Apple's groups into an app's entitlements. macOS would not grant it, anddiff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swiftindex f941449e..ea3ec45b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift@@ -17,7 +17,10 @@ struct LeftoverScannerTests {func found(in location: SearchLocation) -> (location: SearchLocation, leftovers: [Leftover]) {let leftover = Leftover(url: recent.url.appending(path: "com.example.app.sfl3"), kind: location.kind,- match: LeftoverMatch(reason: .bundleIdentifier, confidence: .likely, sharedWith: []), size: 10, isMeasured: true, requiresPrivileges: false+ match: LeftoverMatch(reason: .bundleIdentifier, confidence: .likely, sharedWith: []),+ size: 10,+ isMeasured: true,+ requiresPrivileges: false)return (location, [leftover])}@@ -100,13 +103,22 @@ struct LeftoverScannerTests {name: "Character Palette",teamIdentifier: "59GAB85EFG")- let listed = InstalledApp(url: elsewhere, bundleIdentifier: palette.bundleIdentifier, name: palette.name, isSystemProtected: true)+ let listed = InstalledApp(+ url: elsewhere,+ bundleIdentifier: palette.bundleIdentifier,+ name: palette.name,+ isSystemProtected: true+ )let scanner = LeftoverScanner(environment: environment(in: directory))for installedApps in [[palette], [palette, listed]] {let scan = await scanner.scan(palette, installedApps: installedApps)let preferences = try #require(scan.leftovers.first { $0.kind == .preferences })- #expect(preferences.match.otherCopies.map(PathPattern.comparablePath) == [PathPattern.comparablePath(of: elsewhere)])+ #expect(+ preferences.match.otherCopies.map(PathPattern.comparablePath) == [+ PathPattern.comparablePath(of: elsewhere)+ ]+ )#expect(!preferences.match.isRecommended)}}@@ -170,7 +182,10 @@ struct LeftoverScannerTests {try directory.file("root/Library/LaunchAgents/net.example.webhelper.plist")try directory.directory("var/C/net.example.client")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let root = directory.url.path(percentEncoded: false)let found = Dictionary(uniqueKeysWithValues: scan.leftovers.map {@@ -198,7 +213,10 @@ struct LeftoverScannerTests {try directory.directory("home/Library/Application Support/Music")let namesake = InstalledApp(url: URL(filePath: "/Applications/Music.app"), bundleIdentifier: "com.acme.music", name: "Music")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(namesake, installedApps: [namesake])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ namesake,+ installedApps: [namesake]+ )let folder = try #require(scan.leftovers.first { $0.url.lastPathComponent == "Music" })#expect(folder.match.sharedWith == ["com.apple.Music"])@@ -239,7 +257,10 @@ struct LeftoverScannerTests {let list = "home/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/net.example.client.sfl3"try directory.file(list)- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let found = scan.leftovers.filter { $0.url.lastPathComponent == "net.example.client.sfl3" }#expect(found.count == 1, "listed \(found.count) times")@@ -251,7 +272,14 @@ struct LeftoverScannerTests {/// the same folder, and `adding(_:)` compares paths rather than URLs, so it stays one row.@Test func aPathACaskSpellsWithASlashIsNotASecondRow() {let match = LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: [])- let found = Leftover(url: URL(filePath: "/Users/x/Library/Caches/net.example.client"), kind: .caches, match: match, size: 10, isMeasured: true, requiresPrivileges: false)+ let found = Leftover(+ url: URL(filePath: "/Users/x/Library/Caches/net.example.client"),+ kind: .caches,+ match: match,+ size: 10,+ isMeasured: true,+ requiresPrivileges: false+ )let named = Leftover(url: URL(filePath: "/Users/x/Library/Caches/net.example.client/", directoryHint: .isDirectory),kind: .caches,@@ -277,8 +305,15 @@ struct LeftoverScannerTests {try directory.file("home/Library/Application Support/Nobody/Tunewell/notes.db")let other = InstalledApp(url: URL(filePath: "/Applications/SomeVendor.app"), bundleIdentifier: "com.somevendor.app", name: "SomeVendor")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell, other])- let byPath = Dictionary(uniqueKeysWithValues: scan.leftovers.map { ($0.url.path(percentEncoded: false).components(separatedBy: "Application Support/").last ?? "", $0) })+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell, other]+ )+ let byPath = Dictionary(+ uniqueKeysWithValues: scan.leftovers.map {+ ($0.url.path(percentEncoded: false).components(separatedBy: "Application Support/").last ?? "", $0)+ }+ )#expect(byPath["SomeVendor/Tunewell"]?.match.heldBack == .insideAnotherAppsFolder)#expect(byPath["SomeVendor/Tunewell"]?.match.isRecommended == false)@@ -316,7 +351,10 @@ struct LeftoverScannerTests {try directory.file("home/Library/Application Support/Tunewell/Libraries/Main.musiclibrary/Library.musicdb")try directory.file("home/Library/Caches/net.example.client/cache.db")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let support = try #require(scan.leftovers.first { $0.kind == .applicationSupport })#expect(support.match.heldBack == .holdsALibrary)@@ -330,14 +368,20 @@ struct LeftoverScannerTests {try directory.file("home/Library/Containers/net.example.client/Data/Documents/playlist.txt")try directory.file("home/Library/Group Containers/ABCDE12345.net.example.client/cache.db")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let container = try #require(scan.leftovers.first { $0.kind == .containers })#expect(container.match.heldBack == .holdsDocuments)#expect(!container.match.isRecommended)try FileManager.default.removeItem(at: container.url.appending(path: "Data/Documents/playlist.txt"))- let emptied = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let emptied = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(try #require(emptied.leftovers.first { $0.kind == .containers }).match.isRecommended)}@@ -347,7 +391,10 @@ struct LeftoverScannerTests {try directory.setPermissions(0o000, of: "home/Library/Logs")defer { try? directory.setPermissions(0o755, of: "home/Library/Logs") }- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(scan.leftovers.isEmpty)#expect(scan.unreadableLocations.map(\.kind) == [.logs])@@ -391,7 +438,10 @@ struct LeftoverScannerTests {try directory.setPermissions(0o555, of: "root/Library/LaunchDaemons")defer { try? directory.setPermissions(0o755, of: "root/Library/LaunchDaemons") }- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let privileges = Dictionary(uniqueKeysWithValues: scan.leftovers.map { ($0.kind, $0.requiresPrivileges) })#expect(privileges == [.launchDaemons: true, .preferences: false])@@ -405,7 +455,10 @@ struct LeftoverScannerTests {try directory.file("home/Library/Caches/com.apple.helpd/Generated/net.example.client.help-1.0/index.html")try directory.file("home/Library/Application Support/SomeVendor/Tunewell/state.json")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let root = directory.url.path(percentEncoded: false)let found = Dictionary(uniqueKeysWithValues: scan.leftovers.map {@@ -428,14 +481,21 @@ struct LeftoverScannerTests {try directory.directory("home/Library/Application Support/Aardvark \(index)")}try directory.file("home/Library/Application Support/SomeVendor/Tunewell/state.json")- let scanner = LeftoverScanner(environment: environment(in: directory), measure: LeftoverScanner.walk, nestedFolderLimit: 5)+ let scanner = LeftoverScanner(+ environment: environment(in: directory),+ measure: LeftoverScanner.walk,+ nestedFolderLimit: 5+ )let scan = await scanner.scan(tunewell, installedApps: [tunewell])#expect(scan.leftovers.isEmpty, "the folder past the limit was looked into")#expect(scan.cutShortLocations.map(\.kind) == [.applicationSupport])- let whole = await LeftoverScanner(environment: environment(in: directory), measure: LeftoverScanner.walk).scan(tunewell, installedApps: [tunewell])+ let whole = await LeftoverScanner(environment: environment(in: directory), measure: LeftoverScanner.walk).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(whole.leftovers.map(\.url.lastPathComponent) == ["Tunewell"])#expect(whole.cutShortLocations.isEmpty)}@@ -448,7 +508,10 @@ struct LeftoverScannerTests {try directory.file("home/Library/Caches/SomeVendor/Tunewell Installer Log.txt")try directory.file("home/Library/Caches/SomeVendor/Tunewell")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(scan.leftovers.map(\.url.lastPathComponent) == ["Tunewell"])}@@ -458,7 +521,10 @@ struct LeftoverScannerTests {let directory = try TemporaryDirectory()try directory.file("home/Library/Caches/net.example.client/net.example.client.db")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(scan.leftovers.map(\.url.lastPathComponent) == ["net.example.client"])}@@ -468,7 +534,10 @@ struct LeftoverScannerTests {let directory = try TemporaryDirectory()try directory.file("home/Library/Containers/com.example.other/Data/net.example.client.plist")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(scan.leftovers.isEmpty)}@@ -479,7 +548,10 @@ struct LeftoverScannerTests {try directory.file("root/Users/Shared/Tunewell/library.db", bytes: 4_000)try directory.file("root/Users/Shared/Something Else/notes.txt")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(scan.leftovers.map(\.url.lastPathComponent) == ["Tunewell"])#expect(scan.leftovers.first?.kind == .sharedFolder)@@ -497,7 +569,10 @@ struct LeftoverScannerTests {try directory.file("home/Tunewell/my own notes.txt")try directory.file("home/Documents/Tunewell")- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let root = directory.url.path(percentEncoded: false)let found = Dictionary(@@ -605,7 +680,10 @@ struct LeftoverScannerTests {try directory.file("home/Library/Application Support/Tunewell/workspaces/a/b/project/.git/HEAD")try directory.file("home/Library/Caches/net.example.client/cache.db", bytes: 64_000)- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let root = directory.url.path(percentEncoded: false)let found = Dictionary(uniqueKeysWithValues: scan.leftovers.map {@@ -627,9 +705,17 @@ struct LeftoverScannerTests {let container = try directory.directory("home/Library/Containers/net.example.client")try directory.file("home/Library/Containers/net.example.client/Data/Library/Caches/blob", bytes: 64_000)try directory.setPermissions(0o000, of: container)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: container.path(percentEncoded: false)) }+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: container.path(percentEncoded: false)+ )+ }- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let found = try #require(scan.leftovers.first { $0.url.lastPathComponent == "net.example.client" })#expect(found.match.heldBack == .couldNotBeRead, "a folder nothing could be read from was taken for an empty one")@@ -646,7 +732,10 @@ struct LeftoverScannerTests {try directory.setPermissions(0, of: "home/Library/Application Support/net.example.client/Private")defer { try? directory.setPermissions(0o755, of: "home/Library/Application Support/net.example.client/Private") }- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let found = try #require(scan.leftovers.first { $0.url.path(percentEncoded: false).hasSuffix("Application Support/net.example.client") })#expect(found.match.heldBack == .couldNotBeRead, "a folder read only in part was taken for all it holds")@@ -772,7 +861,9 @@ struct LeftoverScannerTests {try directory.file("home/Library/Containers/com.example.notes/Data/Documents/novel.txt")let photos = try directory.directory("home/Library/Application Support/Example")try directory.file("home/Library/Application Support/Example/2024/Trip.photoslibrary/database/Photos.sqlite")- let unread: LeftoverScanner.Measure = { _ in FolderContents(size: 0, holdsRepository: false, couldNotBeRead: true) }+ let unread: LeftoverScanner.Measure = { _ in+ FolderContents(size: 0, holdsRepository: false, couldNotBeRead: true)+ }func leftover(_ url: URL, _ kind: SearchLocation.Kind) async -> Leftover {await LeftoverScanner.leftover(at: url,@@ -809,9 +900,14 @@ struct LeftoverScannerTests {let cask = HomebrewPackage(name: "tunewell", kind: .cask, appNames: ["Tunewell.app"], leftoverPatterns: ["~/Library/TUNEWELL"])let environment = environment(in: directory)let scan = await LeftoverScanner(environment: environment).scan(tunewell, installedApps: [tunewell])- let evidence = try #require(CaskEvidence.evidence(for: tunewell, casks: [cask], home: environment.homeDirectory))+ let evidence = try #require(+ CaskEvidence.evidence(for: tunewell, casks: [cask], home: environment.homeDirectory)+ )let fromTheCask = await Uninstallation.caskLeftovers(- evidence, app: tunewell, exclusions: .none, matcher: LeftoverMatcher(app: tunewell, installedApps: [tunewell]),+ evidence,+ app: tunewell,+ exclusions: .none,+ matcher: LeftoverMatcher(app: tunewell, installedApps: [tunewell]),environment: environment)@@ -835,7 +931,10 @@ struct LeftoverScannerTests {try directory.file("root/Library/Audio/Plug-Ins/VST/Native Instruments/Massive.vst/Contents/Info.plist", contents: plist("com.native-instruments.massive.vst"))try directory.file("root/Library/QuickLook/Somebody Else.qlgenerator/Contents/Info.plist", bytes: 512)- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(massive, installedApps: [massive])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ massive,+ installedApps: [massive]+ )let root = directory.url.path(percentEncoded: false)let found = Set(scan.leftovers.map { String($0.url.path(percentEncoded: false).dropFirst(root.count)) })@@ -859,7 +958,10 @@ struct LeftoverScannerTests {try directory.file("root/Library/Audio/Plug-Ins/VST3/Q10.vst3/Contents/Info.plist", contents: plist("com.waves.Q10"))try directory.file("root/Library/Audio/Plug-Ins/VST3/Pro-Q.vst3/Contents/Info.plist", contents: plist("com.fabfilter.proq"))- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(central, installedApps: [central])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ central,+ installedApps: [central]+ )#expect(scan.leftovers.map(\.url.lastPathComponent) == ["Q10.vst3"])#expect(scan.leftovers.first?.match.reason == .vendorPrefix)@@ -881,7 +983,10 @@ struct LeftoverScannerTests {try directory.file("\(plugIns)/VST3/Dynamics/Compressor.vst3/Contents/Info.plist", contents: plist("org.example.dynamics.compressor"))try directory.file("\(plugIns)/VST3/Compressor.vst3/Contents/Info.plist", contents: plist("net.example.compressor.vst3"))- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(compressor, installedApps: [compressor])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ compressor,+ installedApps: [compressor]+ )let folder = directory.url.appending(path: plugIns).path(percentEncoded: false)let found = Dictionary(uniqueKeysWithValues: scan.leftovers.map {@@ -907,7 +1012,10 @@ struct LeftoverScannerTests {try directory.file("\(plugIns)/Components/Tunewell Reverb.component/Contents/Info.plist", contents: plist("net.example.tunewell.reverb"))try directory.file("\(plugIns)/VST3/Example Audio/Space.vst3/Contents/Info.plist", contents: plist("net.example.tunewell.space"))- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(Set(scan.leftovers.map(\.url.lastPathComponent)) == ["Tunewell Reverb.component", "Space.vst3"])#expect(scan.leftovers.allSatisfy { $0.match.reason == .bundleIdentifierPrefix && $0.match.isRecommended })@@ -959,7 +1067,10 @@ struct LeftoverScannerTests {try directory.file("home/Library/LaunchAgents/com.elsewhere.agent.plist", contents: job(program: "/Applications/Other.app/Contents/MacOS/Agent"))try directory.file("home/Library/LaunchAgents/com.relative.agent.plist", contents: job(program: "sleep"))- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let found = Dictionary(uniqueKeysWithValues: scan.leftovers.map { ($0.url.lastPathComponent, $0.match) })#expect(Set(found.keys) == ["com.acmesoft.updater.plist", "net.example.nagger.plist"])@@ -974,12 +1085,19 @@ struct LeftoverScannerTests {/// which says nothing about whose it is. Where it leads does.@Test func findsALinkToAToolInsideTheApp() async throws {let directory = try TemporaryDirectory()- let app = InstalledApp(url: directory.url.appending(path: "root/Applications/Tunewell.app", directoryHint: .isDirectory), bundleIdentifier: "net.example.client", name: "Tunewell")+ let app = InstalledApp(+ url: directory.url.appending(path: "root/Applications/Tunewell.app", directoryHint: .isDirectory),+ bundleIdentifier: "net.example.client",+ name: "Tunewell"+ )try directory.file("root/Applications/Tunewell.app/Contents/MacOS/tunewell-cli", bytes: 1_000_000)let bin = try directory.directory("root/usr/local/bin")let sbin = try directory.directory("root/usr/local/sbin")func link(_ name: String, in folder: URL, to destination: String) throws {- try FileManager.default.createSymbolicLink(atPath: folder.appending(path: name).path(percentEncoded: false), withDestinationPath: destination)+ try FileManager.default.createSymbolicLink(+ atPath: folder.appending(path: name).path(percentEncoded: false),+ withDestinationPath: destination+ )}try link("tunewell-cli", in: bin, to: app.url.appending(path: "Contents/MacOS/tunewell-cli").path(percentEncoded: false))try link("spotd", in: sbin, to: "../../../Applications/Tunewell.app/Contents/MacOS/spotd")@@ -1041,7 +1159,10 @@ struct LeftoverScannerTests {try directory.file("home/Library/developer.example.app-Release/state.db", bytes: 64)try directory.file("home/Library/Preferences/unrelated.plist", bytes: 64)- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(developer, installedApps: [developer])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ developer,+ installedApps: [developer]+ )let root = directory.url.path(percentEncoded: false)let found = Dictionary(uniqueKeysWithValues: scan.leftovers.map {(String($0.url.path(percentEncoded: false).dropFirst(root.count)), $0)@@ -1188,7 +1309,10 @@ struct LeftoverScannerTests {try directory.file("home/Library/Caches/com.apple.python/Developer/wheel.whl", bytes: 64)try directory.file("home/Library/Caches/CrashReporter/Developer/report.txt", bytes: 64)- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(developer, installedApps: [developer])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ developer,+ installedApps: [developer]+ )let root = directory.url.path(percentEncoded: false)let found = Dictionary(uniqueKeysWithValues: scan.leftovers.map {(String($0.url.path(percentEncoded: false).dropFirst(root.count)), $0)@@ -1205,7 +1329,10 @@ struct LeftoverScannerTests {let directory = try TemporaryDirectory()try directory.file("root/Users/Shared/Acme/net.example.client/licence.dat", bytes: 64)- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )let found = try #require(scan.leftovers.first)#expect(found.url.lastPathComponent == "net.example.client")@@ -1230,7 +1357,10 @@ struct LeftoverScannerTests {contents: Data(metadata.replacingOccurrences(of: "%@", with: "com.example.other").utf8))- let scan = await LeftoverScanner(environment: environment(in: directory)).scan(tunewell, installedApps: [tunewell])+ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(+ tunewell,+ installedApps: [tunewell]+ )#expect(scan.leftovers.map(\.url.lastPathComponent) == ["3F2504E0-4F89-11D3-9A0C-0305E82C3301"])#expect(scan.leftovers.first?.match.reason == .bundleIdentifier)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LocalSnapshotsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LocalSnapshotsTests.swiftindex ba2a82d2..9dc5e6c1 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/LocalSnapshotsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/LocalSnapshotsTests.swift@@ -58,7 +58,10 @@ struct LocalSnapshotsTests {@Test func readsTheMomentATimeMachineSnapshotWasTaken() throws {let date = try #require(LocalSnapshots.date(in: "com.apple.TimeMachine.2026-09-17-120000.local"))- let parts = Calendar(identifier: .gregorian).dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)+ let parts = Calendar(identifier: .gregorian).dateComponents(+ [.year, .month, .day, .hour, .minute, .second],+ from: date+ )#expect(parts.year == 2026)#expect(parts.month == 9)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanConfidenceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanConfidenceTests.swiftindex dd227958..60f3cf4c 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanConfidenceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanConfidenceTests.swift@@ -80,7 +80,11 @@ struct OrphanConfidenceTests {@Test("Having watched the app go does not settle it either: a maker's other app may only ever read what they share")func aMakerStillHereOutranksHavingWatchedTheAppGo() {let removed = left("Example", team: "S8EX82NJP6", daysAgo: 40)- let judged = OrphanConfidence.judge(group(written: 40 * 24 * 60 * 60, remembered: removed), installedTeams: ["S8EX82NJP6"], now: now)+ let judged = OrphanConfidence.judge(+ group(written: 40 * 24 * 60 * 60, remembered: removed),+ installedTeams: ["S8EX82NJP6"],+ now: now+ )#expect(judged.level == .unsure)#expect(judged.reasons == [.sameMakerStillInstalled])}@@ -107,14 +111,20 @@ struct OrphanConfidenceTests {@Test("Something that wrote here weeks after the app was gone may still use the files, and the write is the reason")func aWriteWeeksAfterTheAppLeft() {- let judged = OrphanConfidence.judge(group(written: 20 * 24 * 60 * 60, remembered: left("Numi", daysAgo: 60)), now: now)+ let judged = OrphanConfidence.judge(+ group(written: 20 * 24 * 60 * 60, remembered: left("Numi", daysAgo: 60)),+ now: now+ )#expect(judged.level == .unsure)#expect(judged.reasons == [.writtenAfterItLeft(name: "Numi", written: now.addingTimeInterval(-20 * 24 * 60 * 60))])}@Test("Months of nothing touching it settle it even when something wrote after the app was gone")func aWriteAfterTheAppLeftLongAgo() throws {- let judged = OrphanConfidence.judge(group(written: 250 * 24 * 60 * 60, remembered: left("Numi", daysAgo: 400)), now: now)+ let judged = OrphanConfidence.judge(+ group(written: 250 * 24 * 60 * 60, remembered: left("Numi", daysAgo: 400)),+ now: now+ )#expect(judged.level == .certain)#expect(judged.reasons.count == 1)guard case .untouched(let months) = try #require(judged.reasons.first) else {@@ -143,7 +153,11 @@ struct OrphanConfidenceTests {func longUntouched() {let judged = OrphanConfidence.judge(group(written: 400 * 24 * 60 * 60), now: now)#expect(judged.level == .certain)- #expect(judged.reasons.contains { if case .untouched(let months) = $0 { months >= OrphanConfidence.longUntouched } else { false } })+ #expect(+ judged.reasons.contains {+ if case .untouched(let months) = $0 { months >= OrphanConfidence.longUntouched } else { false }+ }+ )}@Test("A plug-in's date does not move when it is used, so its age says nothing")@@ -168,8 +182,17 @@ struct OrphanConfidenceTests {// Nor is its own date read as the removal: what is inside may have been written since.let removed = left("Example", daysAgo: 4)- let recent = OrphanItem(url: item.url, kind: .applicationSupport, size: nil, modificationDate: now.addingTimeInterval(-4 * 24 * 60 * 60), requiresPrivileges: false)- let judged = OrphanConfidence.judge(OrphanGroup(identifier: "com.example.app", items: [recent], rememberedApp: removed), now: now)+ let recent = OrphanItem(+ url: item.url,+ kind: .applicationSupport,+ size: nil,+ modificationDate: now.addingTimeInterval(-4 * 24 * 60 * 60),+ requiresPrivileges: false+ )+ let judged = OrphanConfidence.judge(+ OrphanGroup(identifier: "com.example.app", items: [recent], rememberedApp: removed),+ now: now+ )#expect(judged.level == .unsure)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanRemovalTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanRemovalTests.swiftindex ac478a8f..1f4d9480 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanRemovalTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanRemovalTests.swift@@ -22,7 +22,13 @@ struct OrphanRemovalTests {}let back = InstalledApp(url: URL(filePath: "/Applications/Back.app"), bundleIdentifier: "com.back.again", name: "Back")- let result = await OrphanRemoval.trash(listed, installedApps: [back], scanner: scanner, using: trash, mayUseHelper: true)+ let result = await OrphanRemoval.trash(+ listed,+ installedApps: [back],+ scanner: scanner,+ using: trash,+ mayUseHelper: true+ )#expect(moved.withLock { $0 } == ["com.gone.app"])#expect(result.trashed.map(\.originalURL.lastPathComponent) == ["com.gone.app"])@@ -35,7 +41,12 @@ struct OrphanRemovalTests {try directory.file("home/Library/Caches/com.gone.app/cache.db")let served = try directory.directory("root/Library/Application Support/com.gone.app")try directory.setPermissions(0o555, of: served)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: served.path(percentEncoded: false)) }+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: served.path(percentEncoded: false)+ )+ }let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)@@ -50,7 +61,13 @@ struct OrphanRemovalTests {let privileged = listed.filter(\.requiresPrivileges).map(\.url)#expect(!privileged.isEmpty, "the fixture needs an item only an administrator can move")- let result = await OrphanRemoval.trash(listed, installedApps: [], scanner: scanner, using: trash, mayUseHelper: false)+ let result = await OrphanRemoval.trash(+ listed,+ installedApps: [],+ scanner: scanner,+ using: trash,+ mayUseHelper: false+ )#expect(helperWasAsked.withLock { $0 }.isEmpty)#expect(result.failures.map(\.url) == privileged)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swiftindex 8e6ea60d..e1237a65 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift@@ -16,7 +16,12 @@ struct OrphanScannerTests {userTemporaryDirectory: directory.url.appending(path: "var/T", directoryHint: .isDirectory))let unanswered = Unanswered()- let scanner = OrphanScanner(environment: environment, isRegisteredApp: { _ in false }, systemApps: [], walk: unanswered.walk)+ let scanner = OrphanScanner(+ environment: environment,+ isRegisteredApp: { _ in false },+ systemApps: [],+ walk: unanswered.walk+ )let stop = try await unanswered.stop {_ = await scanner.scan(installedApps: [])@@ -56,7 +61,11 @@ struct OrphanScannerTests {homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory))- return OrphanScanner(environment: environment, isRegisteredApp: { registered.contains($0) }, systemApps: systemApps)+ return OrphanScanner(+ environment: environment,+ isRegisteredApp: { registered.contains($0) },+ systemApps: systemApps+ )}/// What an app left behind can be the biggest folder in the Library. A folder that did not answer in time@@ -108,13 +117,20 @@ struct OrphanScannerTests {}defer {for folder in [served, beyond] {- try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: folder.path(percentEncoded: false))+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: folder.path(percentEncoded: false)+ )}}- let group = try #require(await scanner(in: directory).scan(installedApps: installed).groups.first { $0.identifier == "com.gone.app" })+ let group = try #require(+ await scanner(in: directory).scan(installedApps: installed).groups.first { $0.identifier == "com.gone.app" }+ )func item(_ url: URL) throws -> OrphanItem {- try #require(group.items.first { PathPattern.comparablePath(of: $0.url) == PathPattern.comparablePath(of: url) })+ try #require(+ group.items.first { PathPattern.comparablePath(of: $0.url) == PathPattern.comparablePath(of: url) }+ )}#expect(try item(served).requiresPrivileges)@@ -179,7 +195,10 @@ struct OrphanScannerTests {let folder = log.deletingLastPathComponent().deletingLastPathComponent()let lastYear = Date(timeIntervalSinceNow: -400 * 24 * 60 * 60)for old in [log.deletingLastPathComponent(), folder] {- try FileManager.default.setAttributes([.modificationDate: lastYear], ofItemAtPath: old.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.modificationDate: lastYear],+ ofItemAtPath: old.path(percentEncoded: false)+ )}let group = try #require(await scanner(in: directory).scan(installedApps: installed).groups.first)@@ -197,7 +216,9 @@ struct OrphanScannerTests {RememberedApp(bundleIdentifier: "com.installed.app", name: "Installed", teamIdentifier: nil, lastSeen: .now, lastPath: "/Applications/Installed.app"),]- let group = try #require(await scanner(in: directory).scan(installedApps: installed, remembered: remembered).groups.first)+ let group = try #require(+ await scanner(in: directory).scan(installedApps: installed, remembered: remembered).groups.first+ )#expect(group.rememberedApp == nil)#expect(group.confidence.level != .certain)@@ -594,7 +615,10 @@ struct OrphanScannerTests {try directory.file("root/Applications/Here.app/Contents/MacOS/here")try directory.file("home/Library/Application Support/com.remembered.app/state.db")func link(_ name: String, to destination: String) throws {- try FileManager.default.createSymbolicLink(atPath: bin.appending(path: name).path(percentEncoded: false), withDestinationPath: destination)+ try FileManager.default.createSymbolicLink(+ atPath: bin.appending(path: name).path(percentEncoded: false),+ withDestinationPath: destination+ )}try link("docker", to: root.appending(path: "Applications/Gone.app/Contents/MacOS/xbin/docker").path(percentEncoded: false))try link("orb", to: "../../../Applications/Gone.app/Contents/MacOS/bin/orb")@@ -602,7 +626,13 @@ struct OrphanScannerTests {try link("node", to: root.appending(path: "opt/node/bin/node").path(percentEncoded: false))try link("rem", to: root.appending(path: "Applications/Remembered.app/Contents/MacOS/rem").path(percentEncoded: false))let remembered = [- RememberedApp(bundleIdentifier: "com.remembered.app", name: "Remembered", teamIdentifier: nil, lastSeen: .now, lastPath: root.appending(path: "Applications/Remembered.app").path(percentEncoded: false)),+ RememberedApp(+ bundleIdentifier: "com.remembered.app",+ name: "Remembered",+ teamIdentifier: nil,+ lastSeen: .now,+ lastPath: root.appending(path: "Applications/Remembered.app").path(percentEncoded: false)+ )]let scan = await scanner(in: directory).scan(installedApps: installed, remembered: remembered)@@ -625,7 +655,12 @@ struct OrphanScannerTests {let link = bin.appending(path: "docker")try FileManager.default.createSymbolicLink(atPath: link.path(percentEncoded: false), withDestinationPath: "../../../Applications/Gone.app/Contents/MacOS/docker")try directory.setPermissions(0o555, of: bin)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bin.path(percentEncoded: false)) }+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: bin.path(percentEncoded: false)+ )+ }let items = await scanner(in: directory).scan(installedApps: installed).groups.flatMap(\.items)let item = try #require(items.first { $0.url.lastPathComponent == "docker" })@@ -650,7 +685,9 @@ struct OrphanScannerTests {path.copyBytes(from: temporary.appending(path: "jb.station.someone.sock").path(percentEncoded: false).utf8.prefix(path.count - 1))}let bound = withUnsafePointer(to: address) {- $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(listening, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ bind(listening, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }}try #require(bound == 0)try #require(mkfifo(temporary.appending(path: "com.gone.pipe").path(percentEncoded: false), 0o600) == 0)@@ -660,7 +697,8 @@ struct OrphanScannerTests {userTemporaryDirectory: temporary)- let scan = await OrphanScanner(environment: environment, isRegisteredApp: { _ in false }, systemApps: []).scan(installedApps: installed)+ let scan = await OrphanScanner(environment: environment, isRegisteredApp: { _ in false }, systemApps: [])+ .scan(installedApps: installed)#expect(scan.groups.flatMap(\.items).map(\.url.lastPathComponent) == ["com.gone.app"])}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PackageActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PackageActionsTests.swiftindex 4b42afeb..cecdc1ef 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PackageActionsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PackageActionsTests.swift@@ -44,7 +44,10 @@ struct PackageActionsTests {try directory.file("private/var/db/receipts/com.example.tool.plist")let asked = Mutex<[String]>([])let service = TrashService(- environment: SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url),+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url+ ),moveThroughHelper: { urls inasked.withLock { $0 += urls.map(\.lastPathComponent) }return TrashResult(trashed: urls.map { TrashedItem(originalURL: $0, trashedURL: $0, date: .now) })@@ -64,7 +67,10 @@ struct PackageActionsTests {@Test func aReceiptThatIsNotThereIsAFailure() async throws {let directory = try TemporaryDirectory()let service = TrashService(- environment: SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url),+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url+ ),moveToTrash: { _ in throw CocoaError(.fileWriteNoPermission) })diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swiftindex 1c37f5cf..dba33784 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift@@ -12,7 +12,12 @@ struct PackageReceiptsTests {"Library/LaunchDaemons", "Library/LaunchDaemons/com.adguard.helper.plist","./usr/local/bin/adguard-cli",]- let items = PackageReceipts.topLevel(files: files, installLocation: "/", namesInside: { _ in nil }, exists: { _ in true }).offered+ let items = PackageReceipts.topLevel(+ files: files,+ installLocation: "/",+ namesInside: { _ in nil },+ exists: { _ in true }+ ).offered#expect(items == ["/Adguard.app","/Library/Application Support/AdGuard Software",@@ -223,9 +228,14 @@ struct PackageReceiptsTests {default: ""}}- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )- let receipt = try #require(await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first)+ let receipt = try #require(+ await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first+ )#expect(receipt.items.map(\.url.lastPathComponent) == ["tool", "tool3"])#expect(Set(receipt.items.map(\.id)).count == 2)@@ -271,14 +281,22 @@ struct PackageReceiptsTests {default: ""}}- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )- let excluded = try #require(await PackageReceipts.list(exclusions: Exclusions(paths: [app]), pkgutil: pkgutil, environment: environment).receipts.first)+ let excluded = try #require(+ await PackageReceipts.list(exclusions: Exclusions(paths: [app]), pkgutil: pkgutil, environment: environment)+ .receipts.first+ )#expect(excluded.items.isEmpty)#expect(!excluded.nothingLeftOnDisk)try FileManager.default.removeItem(at: app)- let gone = try #require(await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first)+ let gone = try #require(+ await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first+ )#expect(gone.nothingLeftOnDisk)}@@ -298,9 +316,14 @@ struct PackageReceiptsTests {default: nil}}- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )- let receipt = try #require(await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first)+ let receipt = try #require(+ await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first+ )#expect(!receipt.isFileListKnown)#expect(!receipt.nothingLeftOnDisk)@@ -326,9 +349,14 @@ struct PackageReceiptsTests {default: ""}}- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )- let receipt = try #require(await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first)+ let receipt = try #require(+ await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first+ )#expect(receipt.items.first { $0.url == app }?.isLeftAlone == false)#expect(receipt.items.first { $0.url == rules }?.isLeftAlone == true)@@ -346,14 +374,23 @@ struct PackageReceiptsTests {let tools = PathPattern.canonical(try directory.directory("root/Applications/Example Tools"))let bin = PathPattern.canonical(try directory.directory("root/usr/local/bin"))try directory.file("root/usr/local/bin/tool")- try FileManager.default.createSymbolicLink(atPath: bin.appending(path: "linked").path(percentEncoded: false), withDestinationPath: "tool")- try FileManager.default.createSymbolicLink(atPath: bin.appending(path: "gone").path(percentEncoded: false), withDestinationPath: "/Applications/Gone.app/Contents/MacOS/gone")+ try FileManager.default.createSymbolicLink(+ atPath: bin.appending(path: "linked").path(percentEncoded: false),+ withDestinationPath: "tool"+ )+ try FileManager.default.createSymbolicLink(+ atPath: bin.appending(path: "gone").path(percentEncoded: false),+ withDestinationPath: "/Applications/Gone.app/Contents/MacOS/gone"+ )for folder in [served, vendor, tools, bin] {try directory.setPermissions(0o555, of: folder)}defer {for folder in [served, vendor, tools, bin] {- try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: folder.path(percentEncoded: false))+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: folder.path(percentEncoded: false)+ )}}let info = try #require(String(@@ -368,9 +405,14 @@ struct PackageReceiptsTests {default: ""}}- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )- let receipt = try #require(await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first)+ let receipt = try #require(+ await PackageReceipts.list(exclusions: .none, pkgutil: pkgutil, environment: environment).receipts.first+ )func item(_ url: URL) throws -> PackageReceipt.Item {try #require(receipt.items.first { $0.url == url })}@@ -381,7 +423,11 @@ struct PackageReceiptsTests {#expect(try item(tools).isLeftAlone == true)#expect(try [item(vendor), item(tools)].map(\.heldBack) == [.beyondTheHelper, .beyondTheHelper])func tool(_ name: String) throws -> PackageReceipt.Item {- try #require(receipt.items.first { $0.url.deletingLastPathComponent().lastPathComponent == "bin" && $0.url.lastPathComponent == name })+ try #require(+ receipt.items.first {+ $0.url.deletingLastPathComponent().lastPathComponent == "bin" && $0.url.lastPathComponent == name+ }+ )}#expect(try tool("tool").isLeftAlone == true, "a file in a folder only links leave was offered")#expect(try tool("linked").isLeftAlone == true, "a link that leads somewhere was offered")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swiftindex c74c70d6..2020ccd3 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swift@@ -25,7 +25,11 @@ struct PathPatternTests {let matches = PathPattern.expand(".virtualenvs/*/", home: directory.url).map { $0.path(percentEncoded: false) }#expect(Set(matches) == Set([web, link].map(PathPattern.comparablePath(of:))))- #expect(PathPattern.expand(".virtualenvs/web/", home: directory.url).map { $0.path(percentEncoded: false) } == [PathPattern.comparablePath(of: web)])+ #expect(+ PathPattern.expand(".virtualenvs/web/", home: directory.url).map { $0.path(percentEncoded: false) } == [+ PathPattern.comparablePath(of: web)+ ]+ )}@Test func expandsWildcardsIntoEveryFolderThatExists() throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PeelFolderTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PeelFolderTests.swiftindex e1c84185..8c24baa2 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PeelFolderTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PeelFolderTests.swift@@ -8,7 +8,8 @@ struct PeelFolderTests {let folder = PathPattern.comparablePath(of: PeelFolder.url)let written = [TeamRegistry.defaultURL, ExclusionStore.defaultURL, AppMemory.defaultURL,- RemovalHistory.defaultURL, RemovalHistory.refusalsURL, RemovalJournal(beside: RemovalHistory.defaultURL).url,+ RemovalHistory.defaultURL, RemovalHistory.refusalsURL,+ RemovalJournal(beside: RemovalHistory.defaultURL).url,PreferenceBackup.defaultDirectory, DigestMemory.defaultURL,]for url in written {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swiftindex 687106e3..57749015 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift@@ -13,7 +13,10 @@ struct PrivilegedPathPolicyTests {/// A policy over a fabricated root and home folder. The helper trusts only root (`trustedOwner` 0), and a/// test cannot make a file root's, so a test may pass its own user ID instead.- private func policy(in directory: borrowing TemporaryDirectory, trustedOwner: uid_t = 0) throws -> PrivilegedPathPolicy {+ private func policy(+ in directory: borrowing TemporaryDirectory,+ trustedOwner: uid_t = 0+ ) throws -> PrivilegedPathPolicy {try directory.directory("root/Library/LaunchDaemons")try directory.directory("root/Applications")try directory.directory("root/Library/Caches")@@ -31,7 +34,12 @@ struct PrivilegedPathPolicyTests {}/// Creates a file in the fabricated Trash and opens it the way the helper does.- private func trashed(_ name: String, permissions: Int = 0o644, in directory: borrowing TemporaryDirectory, by policy: PrivilegedPathPolicy) throws -> OpenItem {+ private func trashed(+ _ name: String,+ permissions: Int = 0o644,+ in directory: borrowing TemporaryDirectory,+ by policy: PrivilegedPathPolicy+ ) throws -> OpenItem {try directory.file("home/.Trash/\(name)")try directory.setPermissions(permissions, of: "home/.Trash/\(name)")let trash = try #require(policy.openTrash(ownedBy: getuid()))@@ -122,7 +130,8 @@ struct PrivilegedPathPolicyTests {]for (relative, expected) in answers {let item = path(relative, in: directory)- let opened: PrivilegedPathPolicy.Rejection? = if case .failure(let rejection) = policy.open(item) { rejection } else { nil }+ let opened: PrivilegedPathPolicy.Rejection? =+ if case .failure(let rejection) = policy.open(item) { rejection } else { nil }#expect(policy.refusal(of: item) == expected, "\(relative)")#expect(policy.refusal(of: item) == opened, "\(relative): opening answers \(String(describing: opened))")}@@ -193,11 +202,22 @@ struct PrivilegedPathPolicyTests {let destination = path("root/Library/LaunchDaemons/com.example.helper.plist", in: directory)let helper = try policy(in: directory)- #expect(helper.openDestination(destination, for: try trashed("users.plist", in: directory, by: helper)).rejection == .loadsCode)+ #expect(+ helper.openDestination(destination, for: try trashed("users.plist", in: directory, by: helper)).rejection+ == .loadsCode+ )let trusting = try policy(in: directory, trustedOwner: getuid())- #expect(trusting.openDestination(destination, for: try trashed("writable.plist", permissions: 0o664, in: directory, by: trusting)).rejection == .loadsCode)- #expect(try trusting.openDestination(destination, for: try trashed("roots.plist", in: directory, by: trusting)).get().path.hasSuffix("/LaunchDaemons/com.example.helper.plist"))+ #expect(+ trusting.openDestination(+ destination,+ for: try trashed("writable.plist", permissions: 0o664, in: directory, by: trusting)+ ).rejection == .loadsCode+ )+ #expect(+ try trusting.openDestination(destination, for: try trashed("roots.plist", in: directory, by: trusting))+ .get().path.hasSuffix("/LaunchDaemons/com.example.helper.plist")+ )}@Test func refusesRestoreDestinationsThatAreWrong() throws {@@ -273,12 +293,25 @@ struct PrivilegedPathPolicyTests {let daemons = try directory.directory("Library/LaunchDaemons").path(percentEncoded: false)@discardableResultfunc plist(_ name: String, label: String) throws -> URL {- try directory.file("Library/LaunchDaemons/\(name)", contents: PropertyListSerialization.data(fromPropertyList: ["Label": label], format: .xml, options: 0))+ try directory.file(+ "Library/LaunchDaemons/\(name)",+ contents: PropertyListSerialization.data(fromPropertyList: ["Label": label], format: .xml, options: 0)+ )}let real = try plist("vendor-daemon.plist", label: "com.vendor.daemon")try plist("com.vendor.daemon.plist", label: "com.somebody.else")- let linked = try directory.file("elsewhere.plist", contents: PropertyListSerialization.data(fromPropertyList: ["Label": "com.linked.daemon"], format: .xml, options: 0))- try FileManager.default.createSymbolicLink(atPath: daemons + "/linked.plist", withDestinationPath: linked.path(percentEncoded: false))+ let linked = try directory.file(+ "elsewhere.plist",+ contents: PropertyListSerialization.data(+ fromPropertyList: ["Label": "com.linked.daemon"],+ format: .xml,+ options: 0+ )+ )+ try FileManager.default.createSymbolicLink(+ atPath: daemons + "/linked.plist",+ withDestinationPath: linked.path(percentEncoded: false)+ )try plist("one.plist", label: "com.twice.daemon")try plist("two.plist", label: "com.twice.daemon")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swiftindex d2d22170..4b5219dc 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift@@ -13,7 +13,11 @@ struct ProjectArtifactsTests {let unanswered = Unanswered()let stop = try await unanswered.stop {- _ = await ProjectArtifacts.scan(roots: [directory.url.appending(path: "Code", directoryHint: .isDirectory)], exclusions: .none, measure: unanswered.walk)+ _ = await ProjectArtifacts.scan(+ roots: [directory.url.appending(path: "Code", directoryHint: .isDirectory)],+ exclusions: .none,+ measure: unanswered.walk+ )}#expect(stop.took < .seconds(1))@@ -78,7 +82,9 @@ struct ProjectArtifactsTests {#expect(ProjectArtifacts.markableForBackups([target], excludedFromAbove: []).isEmpty)#expect(ProjectArtifacts.markableForBackups([terraform], excludedFromAbove: []).isEmpty, "no build makes it")- #expect(ProjectArtifacts.markableForBackups([target, modules, pods], excludedFromAbove: [pods.url]) == [modules.url])+ #expect(+ ProjectArtifacts.markableForBackups([target, modules, pods], excludedFromAbove: [pods.url]) == [modules.url]+ )#expect(ProjectArtifacts.markableForBackups([modules], excludedFromAbove: [modules.url]).isEmpty)}@@ -339,7 +345,10 @@ struct ProjectArtifactsTests {let date = Date.now.addingTimeInterval(-Double(days) * 24 * 60 * 60)guard let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil) else { return }for case let item as URL in enumerator {- try FileManager.default.setAttributes([.modificationDate: date], ofItemAtPath: item.path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.modificationDate: date],+ ofItemAtPath: item.path(percentEncoded: false)+ )}try FileManager.default.setAttributes([.modificationDate: date], ofItemAtPath: url.path(percentEncoded: false))}@@ -464,7 +473,10 @@ struct ProjectArtifactsTests {try directory.file("app/node_modules/dep/index.js", bytes: 400_000)try age(directory.url, days: 60)- #expect(await ProjectArtifacts.scan(roots: [directory.url], exclusions: Exclusions(paths: [modules])).artifacts.isEmpty)+ #expect(+ await ProjectArtifacts.scan(roots: [directory.url], exclusions: Exclusions(paths: [modules]))+ .artifacts.isEmpty+ )#expect(await ProjectArtifacts.scan(roots: [directory.url]).artifacts.count == 1)}@@ -582,7 +594,9 @@ struct ProjectArtifactsTests {try directory.file("Tools/Editor.app/Contents/Resources/app/package.json")try directory.file("Tools/Editor.app/Contents/Resources/app/node_modules/left-pad/index.js", bytes: 1_000)- let found = await ProjectArtifacts.scan(roots: [directory.url.appending(path: "Tools", directoryHint: .isDirectory)]).artifacts+ let found = await ProjectArtifacts.scan(roots: [+ directory.url.appending(path: "Tools", directoryHint: .isDirectory)+ ]).artifacts#expect(found.isEmpty, "part of an installed app was offered")}@@ -649,10 +663,16 @@ struct ProjectArtifactsTests {let directory = try TemporaryDirectory()try directory.file("Project/package.json")let old = Date(timeIntervalSinceNow: -60 * 24 * 60 * 60)- try FileManager.default.setAttributes([.modificationDate: old], ofItemAtPath: try directory.file("Project/src/main.swift").path(percentEncoded: false))+ try FileManager.default.setAttributes(+ [.modificationDate: old],+ ofItemAtPath: try directory.file("Project/src/main.swift").path(percentEncoded: false)+ )try directory.file("Project/.git/index")- let activity = ProjectArtifacts.lastActivity(in: directory.url.appending(path: "Project", directoryHint: .isDirectory), ignoring: ["node_modules"])+ let activity = ProjectArtifacts.lastActivity(+ in: directory.url.appending(path: "Project", directoryHint: .isDirectory),+ ignoring: ["node_modules"]+ )#expect(activity.isCertain)#expect(try #require(activity.date).timeIntervalSinceNow > -60)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PromptStyleTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PromptStyleTests.swiftindex d6edbc44..b57e89e9 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PromptStyleTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PromptStyleTests.swift@@ -20,7 +20,13 @@ struct PromptStyleTests {let shown = try shell.output(of: "cd ~/Projects/peel; (( $+functions[vcs_info] )) && vcs_info; \(failed ? "false" : "true"); print -rnP -- \"${(e)PROMPT}\"")- let sample = style.sample(user: NSUserName(), host: PromptStyle.hostName(), path: "~/Projects/peel", branch: "main", failed: failed)+ let sample = style.sample(+ user: NSUserName(),+ host: PromptStyle.hostName(),+ path: "~/Projects/peel",+ branch: "main",+ failed: failed+ )#expect(Self.merged(Self.segments(in: shown)) == Self.merged(sample), "\(style), failed: \(failed), shown: \(shown.debugDescription)")}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swiftindex 4bba9522..50da8db3 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift@@ -120,8 +120,12 @@ struct RefusalLogTests {#expect(outcome.records?.map(\.reason) == ["last-copy"])guard case .damaged(let setAside) = outcome.problem else { Issue.record("no damage reported"); return }#expect(setAside.lastPathComponent.contains("damaged"))- #expect(try FileManager.default.contentsOfDirectory(atPath: url.deletingLastPathComponent().path(percentEncoded: false))- .contains { $0.contains("damaged") }, "the file it could not read was thrown away")+ #expect(+ try FileManager.default.contentsOfDirectory(+ atPath: url.deletingLastPathComponent().path(percentEncoded: false)+ ).contains { $0.contains("damaged") },+ "the file it could not read was thrown away"+ )}/// The file is the only copy of what was refused, so when it cannot be read it is never written over.@@ -130,7 +134,12 @@ struct RefusalLogTests {let url = try directory.directory("Peel").appending(path: "refusals.json")try Data("[]".utf8).write(to: url)try directory.setPermissions(0, of: url)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path(percentEncoded: false)) }+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o644],+ ofItemAtPath: url.path(percentEncoded: false)+ )+ }let problem = await RefusalLog(url: url).add([failure("/Users/me/a", .lastCopy)], source: "Editor", tool: "applications")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalGroupingTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalGroupingTests.swiftindex ffa9a3fc..7ffea518 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalGroupingTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalGroupingTests.swift@@ -4,7 +4,14 @@ import Testing/// What History shows: one row per removal, newest first, and inside it the largest item first.struct RemovalGroupingTests {- private func record(_ batch: UUID, _ name: String, size: Int64?, at date: Date, source: String = "Example", tool: String = "applications") -> RemovalRecord {+ private func record(+ _ batch: UUID,+ _ name: String,+ size: Int64?,+ at date: Date,+ source: String = "Example",+ tool: String = "applications"+ ) -> RemovalRecord {RemovalRecord(batch: batch,item: TrashedItem(@@ -21,7 +28,11 @@ struct RemovalGroupingTests {/// A source title Peel writes itself is also stored as a key, so History can show it in the user's current/// language. A record saved without a key still decodes, with `source` as it was written.@Test func aSourceKeyIsKeptAndAnOldRecordReadsWithoutOne() throws {- let item = TrashedItem(originalURL: URL(filePath: "/Users/x/a"), trashedURL: URL(filePath: "/Users/x/.Trash/a"), date: Date(timeIntervalSince1970: 1_800_000_000))+ let item = TrashedItem(+ originalURL: URL(filePath: "/Users/x/a"),+ trashedURL: URL(filePath: "/Users/x/.Trash/a"),+ date: Date(timeIntervalSince1970: 1_800_000_000)+ )let keyed = RemovalRecord(batch: UUID(), item: item, size: 1, source: "Duplicates", sourceKey: "tool", tool: "duplicates")let copy = try JSONDecoder().decode(RemovalRecord.self, from: JSONEncoder().encode(keyed))#expect(copy.sourceKey == "tool")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swiftindex 0eed9b14..ac46ac38 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift@@ -23,12 +23,17 @@ struct RemovalHistoryTests {}@Test func historyStaysWhereItAlwaysWas() throws {- let support = try #require(FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)+ let support = try #require(+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ )#expect(RemovalHistory.defaultURL == support.appending(path: "Peel/removals.json"))#expect(RemovalHistory.defaultURL.path(percentEncoded: false).hasSuffix("/Peel/removals.json"))#expect(RemovalHistory.refusalsURL == support.appending(path: "Peel/refusals.json"))- #expect(RemovalHistory.refusalsURL.deletingLastPathComponent() == RemovalHistory.defaultURL.deletingLastPathComponent())+ #expect(+ RemovalHistory.refusalsURL.deletingLastPathComponent()+ == RemovalHistory.defaultURL.deletingLastPathComponent()+ )}@Test func keepsRecordsAcrossLoads() async throws {@@ -57,7 +62,11 @@ struct RemovalHistoryTests {let batch = UUID()let moment = Date(timeIntervalSince1970: 1_800_000_000)for (offset, source, tool) in [(0.1, "com.gone.app", "orphans"), (0.2, "App Caches", "space"), (0.3, "SwiftTool", "projects"), (0.4, "Duplicates", "duplicates")] {- let item = TrashedItem(originalURL: URL(filePath: "/Users/x/\(source)"), trashedURL: URL(filePath: "/Users/x/.Trash/\(source)"), date: moment.addingTimeInterval(offset))+ let item = TrashedItem(+ originalURL: URL(filePath: "/Users/x/\(source)"),+ trashedURL: URL(filePath: "/Users/x/.Trash/\(source)"),+ date: moment.addingTimeInterval(offset)+ )_ = await log.add([RemovalRecord(batch: batch, item: item, size: 1, source: source, tool: tool)])}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swiftindex 3fd5d002..badc5401 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift@@ -13,15 +13,26 @@ struct RemovalHygieneTests {/// The host UUID of the Mac these tests pretend to run on, as its ByHost file names carry it.private let host = "0A1B2C3D-4E5F-6071-8293-A4B5C6D7E8F9"- private func launchdPlist(_ path: String, label: String?, in directory: borrowing TemporaryDirectory) throws -> URL {- let contents = try PropertyListSerialization.data(fromPropertyList: label.map { ["Label": $0] } ?? [:], format: .xml, options: 0)+ private func launchdPlist(+ _ path: String,+ label: String?,+ in directory: borrowing TemporaryDirectory+ ) throws -> URL {+ let contents = try PropertyListSerialization.data(+ fromPropertyList: label.map { ["Label": $0] } ?? [:],+ format: .xml,+ options: 0+ )return try directory.file(path, contents: contents)}/// launchd knows a job by the `Label` inside its file, which the file name only usually repeats.@Test func findsTheJobsBehindLaunchdPlists() throws {let directory = try TemporaryDirectory()- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )let agent = try launchdPlist("home/Library/LaunchAgents/updater.plist", label: "com.example.agent", in: directory)let shared = try launchdPlist("root/Library/LaunchAgents/com.example.shared.plist", label: "com.example.shared", in: directory)let daemon = try launchdPlist("root/Library/LaunchDaemons/com.example.helper.plist", label: "com.example.helper", in: directory)@@ -131,7 +142,9 @@ struct RemovalHygieneTests {#expect(PreferenceCleanup.domains(for: [stray, strayByHost, contained], home: home, host: host) == [PreferenceCleanup.Domain(name: "com.example.app", isByHost: false),])- #expect(PreferenceCleanup.domains(for: [stray, strayByHost, contained, containedByHost], home: home, host: host) == [+ #expect(+ PreferenceCleanup.domains(for: [stray, strayByHost, contained, containedByHost], home: home, host: host)+ == [PreferenceCleanup.Domain(name: "com.example.app", isByHost: false),PreferenceCleanup.Domain(name: "com.example.app", isByHost: true),])@@ -236,9 +249,20 @@ struct RemovalHygieneTests {return .no}- #expect(await PreferenceBackup.save([URL.homeDirectory.appending(path: "Library/Caches/com.example.app")], for: app, in: backups, through: Self.service, run: notThere) == .nothingToSave)+ #expect(+ await PreferenceBackup.save(+ [URL.homeDirectory.appending(path: "Library/Caches/com.example.app")],+ for: app,+ in: backups,+ through: Self.service,+ run: notThere+ ) == .nothingToSave+ )#expect(asked.withLock { $0 }.isEmpty, "a folder that names no domain was asked about")- #expect(await PreferenceBackup.save([plist], for: app, in: backups, through: Self.service, run: notThere) == .nothingToSave)+ #expect(+ await PreferenceBackup.save([plist], for: app, in: backups, through: Self.service, run: notThere)+ == .nothingToSave+ )#expect(asked.withLock { $0 } == [["read", "com.example.app"]])#expect(try FileManager.default.contentsOfDirectory(atPath: backups.path(percentEncoded: false)).isEmpty)}@@ -259,7 +283,14 @@ struct RemovalHygieneTests {return Self.exporting(arguments)}- let restored = await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, through: Self.service, run: run, isOpen: { false })+ let restored = await PreferenceBackup.restore(+ from: folder,+ of: "com.example.app",+ in: backups,+ through: Self.service,+ run: run,+ isOpen: { false }+ )#expect(restored == .incomplete(clearedSome: false), "a copy that could not be read was reported as put back, or as cleared")let commands = asked.withLock { $0 }@@ -268,7 +299,16 @@ struct RemovalHygieneTests {// An import that fails after the delete has cleared that domain, and the result says so.let failingImport: PreferenceBackup.Run = { arguments in arguments.first == "import" ? .no : Self.exporting(arguments) }- #expect(await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, through: Self.service, run: failingImport, isOpen: { false }) == .incomplete(clearedSome: true))+ #expect(+ await PreferenceBackup.restore(+ from: folder,+ of: "com.example.app",+ in: backups,+ through: Self.service,+ run: failingImport,+ isOpen: { false }+ ) == .incomplete(clearedSome: true)+ )}/// Put Back replaces what the app set since the reset, which may be a license entered again, so those settings@@ -285,7 +325,14 @@ struct RemovalHygieneTests {return Self.exporting(arguments)}- let restored = await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, through: Self.service, run: run, isOpen: { false })+ let restored = await PreferenceBackup.restore(+ from: folder,+ of: "com.example.app",+ in: backups,+ through: Self.service,+ run: run,+ isOpen: { false }+ )#expect(restored == .complete)let copies = PreferenceBackup.copies(in: backups)@@ -310,12 +357,25 @@ struct RemovalHygieneTests {return Self.exporting(arguments)}- let open = await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, through: Self.service, run: run, isOpen: { true })+ let open = await PreferenceBackup.restore(+ from: folder,+ of: "com.example.app",+ in: backups,+ through: Self.service,+ run: run,+ isOpen: { true }+ )#expect(open == .appIsOpen)#expect(asked.withLock { $0 }.isEmpty)let checks = Mutex(0)- let opensMeanwhile = await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, through: Self.service, run: run) {+ let opensMeanwhile = await PreferenceBackup.restore(+ from: folder,+ of: "com.example.app",+ in: backups,+ through: Self.service,+ run: run+ ) {checks.withLock { count incount += 1return count > 1@@ -340,7 +400,16 @@ struct RemovalHygieneTests {return arguments.first == "export" ? .no : .yes}- #expect(await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, through: Self.service, run: run, isOpen: { false }) == .notSaved)+ #expect(+ await PreferenceBackup.restore(+ from: folder,+ of: "com.example.app",+ in: backups,+ through: Self.service,+ run: run,+ isOpen: { false }+ ) == .notSaved+ )#expect(!asked.withLock { $0 }.contains { $0.first == "delete" || $0.first == "import" })}@@ -360,11 +429,18 @@ struct RemovalHygieneTests {let app = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "com.example.app", name: "Example")let plist = URL.homeDirectory.appending(path: "Library/Preferences/com.example.app.plist")- let refused = await PreferenceBackup.save([plist], for: app, in: backups, through: Self.service) { arguments in arguments.contains("export") ? .no : .yes }+ let refused = await PreferenceBackup.save([plist], for: app, in: backups, through: Self.service) { arguments in+ arguments.contains("export") ? .no : .yes+ }#expect(refused == .failed)#expect(try FileManager.default.contentsOfDirectory(atPath: backups.path(percentEncoded: false)).isEmpty, "an empty copy was left behind")- let nothing = await PreferenceBackup.save([URL(filePath: "/Users/x/Library/Caches/com.example.app")], for: app, in: backups, through: Self.service) { _ in .yes }+ let nothing = await PreferenceBackup.save(+ [URL(filePath: "/Users/x/Library/Caches/com.example.app")],+ for: app,+ in: backups,+ through: Self.service+ ) { _ in .yes }#expect(nothing == .nothingToSave)}@@ -423,7 +499,13 @@ struct RemovalHygieneTests {for identifier in ["company.thebrowser.Browser", "md.obsidian"] {let app = InstalledApp(url: URL(filePath: "/Applications/\(identifier).app"), bundleIdentifier: identifier, name: identifier)let plist = URL.homeDirectory.appending(path: "Library/Preferences/\(identifier).plist")- let saved = await PreferenceBackup.save([plist], for: app, in: backups, through: Self.service, run: exporting)+ let saved = await PreferenceBackup.save(+ [plist],+ for: app,+ in: backups,+ through: Self.service,+ run: exporting+ )guard case .saved = saved else {Issue.record("no copy of \(identifier)'s settings: \(saved)")continue@@ -448,7 +530,11 @@ struct RemovalHygieneTests {#expect(copies.map(\.bundleIdentifier) == ["com.example.app", "com.example.app", "com.other.tool", "com.example.app"])#expect(copies.map(\.folder.lastPathComponent).prefix(2) == ["com.example.app 2026-09-20 093000 2", "com.example.app 2026-09-20 093000"])- #expect(copies.first?.date == DateComponents(calendar: .current, year: 2026, month: 9, day: 20, hour: 9, minute: 30, second: 0).date)+ #expect(+ copies.first?.date == DateComponents(+ calendar: .current, year: 2026, month: 9, day: 20, hour: 9, minute: 30, second: 0+ ).date+ )}/// A saved copy can hold a license key or an account, and once the Trash is emptied it may be the only way@@ -461,7 +547,10 @@ struct RemovalHygieneTests {}let moved = Mutex<[String]>([])let service = TrashService(- environment: SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root")),+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ ),moveToTrash: { url inmoved.withLock { $0.append(url.lastPathComponent) }return url@@ -554,7 +643,10 @@ struct PrivacyResetTests {failures: [TrashFailure(url: notes.url, reason: .notPermitted)])- let told = PrivacyReset.worthTelling([(editor, .reset), (notes, .reset), (viewer, .notKnownToTheSystem)], after: removal)+ let told = PrivacyReset.worthTelling(+ [(editor, .reset), (notes, .reset), (viewer, .notKnownToTheSystem)],+ after: removal+ )#expect(told.map(\.app.name) == ["Notes", "Viewer"])}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swiftindex 1076411b..2c840537 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift@@ -5,7 +5,11 @@ import Testingstruct RemovalJournalTests {/// An item that moved at a time with more than milliseconds in it, as every real move has.- private func item(_ name: String, in directory: borrowing TemporaryDirectory, at date: Date = Date(timeIntervalSince1970: 1_800_000_000.002_07)) -> TrashedItem {+ private func item(+ _ name: String,+ in directory: borrowing TemporaryDirectory,+ at date: Date = Date(timeIntervalSince1970: 1_800_000_000.002_07)+ ) -> TrashedItem {TrashedItem(originalURL: directory.url.appending(path: "home/Library/Caches/\(name)"),trashedURL: directory.url.appending(path: "home/.Trash/\(name)"),@@ -22,9 +26,16 @@ struct RemovalJournalTests {return RemovalJournal.Writer(pid: process.processIdentifier, started: 1)}- private func service(in directory: borrowing TemporaryDirectory, journal: RemovalJournal, moveToTrash: @escaping @Sendable (URL) throws -> URL) -> TrashService {+ private func service(+ in directory: borrowing TemporaryDirectory,+ journal: RemovalJournal,+ moveToTrash: @escaping @Sendable (URL) throws -> URL+ ) -> TrashService {TrashService(- environment: SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root")),+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ ),journal: journal,moveToTrash: moveToTrash)@@ -202,7 +213,10 @@ struct RemovalJournalTests {let directory = try TemporaryDirectory()let journal = RemovalJournal(beside: directory.url.appending(path: "Peel/removals.json"))let moved = item("com.example.app", in: directory)- try FileManager.default.createDirectory(at: journal.url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: journal.url.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )try Data(#"{"batch":"#.utf8).write(to: journal.url)journal.note([moved], batch: UUID())diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalQuestionTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalQuestionTests.swiftindex 0145ed50..c6c39192 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalQuestionTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalQuestionTests.swift@@ -72,7 +72,12 @@ struct RemovalQuestionTests {let measured = URL(filePath: "/Users/me/Library/Caches/measured")let unknown = URL(filePath: "/Users/me/Library/Caches/unknown")- #expect(RemovalRequest(urls: [measured], sizes: [measured: 100]).total == SizeTotal(known: 100, isComplete: true))- #expect(RemovalRequest(urls: [measured, unknown], sizes: [measured: 100]).total == SizeTotal(known: 100, isComplete: false))+ #expect(+ RemovalRequest(urls: [measured], sizes: [measured: 100]).total == SizeTotal(known: 100, isComplete: true)+ )+ #expect(+ RemovalRequest(urls: [measured, unknown], sizes: [measured: 100]).total+ == SizeTotal(known: 100, isComplete: false)+ )}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swiftindex 9f1aa29c..02e3402b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift@@ -16,8 +16,16 @@ struct RemovalStandingTests {let closed = try directory.directory("closed")let notKnown = record(try directory.file("closed/hidden.txt"), size: 3)let alsoKept = record(try directory.file(".Trash/also kept.txt"), size: nil)- try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: closed.path(percentEncoded: false))- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: closed.path(percentEncoded: false)) }+ try FileManager.default.setAttributes(+ [.posixPermissions: 0o000],+ ofItemAtPath: closed.path(percentEncoded: false)+ )+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: closed.path(percentEncoded: false)+ )+ }let records = [kept, gone, away, notKnown, alsoKept]let standing = RemovalStanding(records)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalTotalsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalTotalsTests.swiftindex a8530c95..31ff4b78 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalTotalsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalTotalsTests.swift@@ -7,7 +7,11 @@ struct RemovalTotalsTests {let url = URL(filePath: path)return RemovalRecord(batch: batch,- item: TrashedItem(originalURL: url, trashedURL: URL(filePath: "/Users/x/.Trash").appending(path: url.lastPathComponent), date: .now),+ item: TrashedItem(+ originalURL: url,+ trashedURL: URL(filePath: "/Users/x/.Trash").appending(path: url.lastPathComponent),+ date: .now+ ),size: size,source: "Example",tool: "applications"@@ -85,7 +89,11 @@ struct RemovalTotalsTests {trashedURL: URL(filePath: "/Users/x/.Trash/org.example.app"),date: .now)- RemovalJournal(beside: history).note([moved], batch: UUID(), by: RemovalJournal.Writer(pid: process.processIdentifier, started: 1))+ RemovalJournal(beside: history).note(+ [moved],+ batch: UUID(),+ by: RemovalJournal.Writer(pid: process.processIdentifier, started: 1)+ )_ = await RemovalLog(url: history).load()@@ -135,7 +143,9 @@ struct RemovalTotalsTests {_ = await RemovalLog(url: history).add([record("/Users/x/Library/Caches/org.example.tool", size: 200, batch: UUID())])#expect(RemovalTotals.read(beside: history).items == 1)- let kept = try FileManager.default.contentsOfDirectory(atPath: file.deletingLastPathComponent().path(percentEncoded: false))+ let kept = try FileManager.default.contentsOfDirectory(+ atPath: file.deletingLastPathComponent().path(percentEncoded: false)+ )#expect(kept.contains { $0.hasPrefix("totals-damaged-") })}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RowCheckboxButtonTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RowCheckboxButtonTests.swiftindex 1d047b26..1d7a517a 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RowCheckboxButtonTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RowCheckboxButtonTests.swift@@ -5,7 +5,12 @@ import Testing@MainActorstruct RowCheckboxButtonTests {@Test func showMenuOpensWhatARightClickOnItOpensEvenWhileItCannotBeChanged() {- let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 100), styleMask: [.titled], backing: .buffered, defer: false)+ let window = NSWindow(+ contentRect: NSRect(x: 0, y: 0, width: 300, height: 100),+ styleMask: [.titled],+ backing: .buffered,+ defer: false+ )let row = RightClicks(frame: NSRect(x: 0, y: 0, width: 300, height: 100))window.contentView = rowlet checkbox = RowCheckboxButton(frame: NSRect(x: 20, y: 30, width: 16, height: 16))diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RunningCopiesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RunningCopiesTests.swiftindex 9aaf34f3..45958808 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RunningCopiesTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RunningCopiesTests.swift@@ -74,7 +74,10 @@ struct RunningCopiesTests {#expect(RunningCopies.belonging(to: old, among: running, installedApps: [chrome, old]).isEmpty)#expect(RunningCopies.belonging(to: chrome, among: running, installedApps: [chrome, old]).count == 1)// A reset clears settings both copies write, so for a reset the other copy counts.- #expect(RunningCopies.belonging(to: old, among: running, installedApps: [chrome, old], sharingItsSettings: true).count == 1)+ #expect(+ RunningCopies.belonging(to: old, among: running, installedApps: [chrome, old], sharingItsSettings: true)+ .count == 1+ )}/// An app that continues the identifier and runs from somewhere Peel does not list apps, such as Chrome Canarydiff --git a/Packages/PeelCore/Tests/PeelCoreTests/SSHFileTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SSHFileTests.swiftindex 812cbe38..dd84772b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SSHFileTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SSHFileTests.swift@@ -19,7 +19,12 @@ private struct SSHHome {/// The options ssh would use for `host`, by their names in lowercase, as `ssh -G` prints them.func options(for host: String) async throws -> [String: String] {- let answer = await Subprocess.run("/usr/bin/ssh", ["-G", "-F", config.path(percentEncoded: false), host], environment: [:], timeout: 10)+ let answer = await Subprocess.run(+ "/usr/bin/ssh",+ ["-G", "-F", config.path(percentEncoded: false), host],+ environment: [:],+ timeout: 10+ )guard case .success(let output) = answer else { throw POSIXError(.EIO) }#expect(output.status == 0, "\(output.errorText)")return Dictionary(output.text.split(separator: "\n").compactMap { line indiff --git a/Packages/PeelCore/Tests/PeelCoreTests/ScanCountTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ScanCountTests.swiftindex 55bcca6c..bafa64cd 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ScanCountTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ScanCountTests.swift@@ -36,7 +36,9 @@ struct ScanCountTests {}let count = ScanCount()- _ = await ScanCount.$current.withValue(count) { await CloudStorage.downloaded(home: directory.url, minimumSize: 1) }+ _ = await ScanCount.$current.withValue(count) {+ await CloudStorage.downloaded(home: directory.url, minimumSize: 1)+ }#expect(count.value == 4, "a container and the three files in it")}@@ -48,7 +50,10 @@ struct ScanCountTests {let count = ScanCount()_ = await ScanCount.$current.withValue(count) {- await ProjectArtifacts.scan(roots: [directory.url.appending(path: "Code", directoryHint: .isDirectory)], exclusions: .none) { _ in FolderContents(size: 0, holdsRepository: false) }+ await ProjectArtifacts.scan(+ roots: [directory.url.appending(path: "Code", directoryHint: .isDirectory)],+ exclusions: .none+ ) { _ in FolderContents(size: 0, holdsRepository: false) }}#expect(count.value >= 3, "the project, its build file and its node_modules at least")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ScratchVolume.swift b/Packages/PeelCore/Tests/PeelCoreTests/ScratchVolume.swiftindex af6131ea..1cc81a8b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ScratchVolume.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ScratchVolume.swift@@ -23,6 +23,8 @@ final class ScratchVolume {private static func hdiutil(_ arguments: String...) throws {let process = try Process.run(URL(filePath: "/usr/bin/hdiutil"), arguments: arguments)process.waitUntilExit()- guard process.terminationStatus == 0 else { throw CocoaError(.fileWriteUnknown, userInfo: [NSLocalizedDescriptionKey: arguments.joined(separator: " ")]) }+ guard process.terminationStatus == 0 else {+ throw CocoaError(.fileWriteUnknown, userInfo: [NSLocalizedDescriptionKey: arguments.joined(separator: " ")])+ }}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SearchingTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SearchingTests.swiftindex e8e9c62b..f7908217 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SearchingTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SearchingTests.swift@@ -10,7 +10,13 @@ struct SearchingTests {DuplicateGroup(id: paths[0],files: paths.map {- DuplicateFile(url: URL(filePath: $0), size: 10, reclaimableSize: 10, allocatedSize: 10, identity: FileIdentity(stat()))+ DuplicateFile(+ url: URL(filePath: $0),+ size: 10,+ reclaimableSize: 10,+ allocatedSize: 10,+ identity: FileIdentity(stat())+ )})}@@ -121,7 +127,9 @@ struct SearchingTests {)try Data(repeating: 7, count: 2_000).write(to: url)let moved = Mutex<[URL]>([])- let service = TrashService(environment: SearchEnvironment(homeDirectory: directory.url, rootDirectory: directory.url)) { url in+ let service = TrashService(+ environment: SearchEnvironment(homeDirectory: directory.url, rootDirectory: directory.url)+ ) { url inmoved.withLock { $0.append(url) }return url}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SelfRemovalTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SelfRemovalTests.swiftindex 70645024..efba0098 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SelfRemovalTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SelfRemovalTests.swift@@ -3,7 +3,10 @@ import Foundationimport Testingstruct SelfRemovalTests {- private func service(in directory: borrowing TemporaryDirectory, exclusions: Exclusions = .none) throws -> TrashService {+ private func service(+ in directory: borrowing TemporaryDirectory,+ exclusions: Exclusions = .none+ ) throws -> TrashService {let trash = try directory.directory("Trash")let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),@@ -27,13 +30,22 @@ struct SelfRemovalTests {let cache = try directory.directory("home/Library/Caches/com.example.peel")let folder = try directory.directory("home/Library/Application Support/Peel")- let result = await SelfRemoval.move([cache, app], app: app, folder: folder, using: try service(in: directory)) { result in+ let result = await SelfRemoval.move(+ [cache, app],+ app: app,+ folder: folder,+ using: try service(in: directory)+ ) { result intry? Data("\(result.trashed.count)".utf8).write(to: folder.appending(path: "removals.json"))}#expect(paths(result.trashed.map(\.originalURL)) == paths([cache, app, folder]))#expect(!FileManager.default.fileExists(atPath: folder.path(percentEncoded: false)))- let moved = try #require(result.trashed.first { PathPattern.comparablePath(of: $0.originalURL) == PathPattern.comparablePath(of: folder) })+ let moved = try #require(+ result.trashed.first {+ PathPattern.comparablePath(of: $0.originalURL) == PathPattern.comparablePath(of: folder)+ }+ )#expect(try String(contentsOf: moved.trashedURL.appending(path: "removals.json"), encoding: .utf8) == "2")}@@ -44,7 +56,12 @@ struct SelfRemovalTests {let cache = try directory.directory("home/Library/Caches/com.example.peel")let folder = try directory.directory("home/Library/Application Support/Peel")- let result = await SelfRemoval.move([cache, app], app: app, folder: folder, using: try service(in: directory, exclusions: Exclusions(paths: [app]))) { _ in }+ let result = await SelfRemoval.move(+ [cache, app],+ app: app,+ folder: folder,+ using: try service(in: directory, exclusions: Exclusions(paths: [app]))+ ) { _ in }#expect(paths(result.failures.map(\.url)) == paths([app]))#expect(FileManager.default.fileExists(atPath: folder.path(percentEncoded: false)))diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SheetInFrontTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SheetInFrontTests.swiftindex e7b2631c..b9fd8be3 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SheetInFrontTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SheetInFrontTests.swift@@ -5,8 +5,18 @@ import Testing@MainActorstruct SheetInFrontTests {@Test func isShowingWhileTheKeyWindowIsASheet() {- let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 200), styleMask: [.titled], backing: .buffered, defer: true)- let sheet = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 100), styleMask: [.titled], backing: .buffered, defer: true)+ let window = NSWindow(+ contentRect: NSRect(x: 0, y: 0, width: 300, height: 200),+ styleMask: [.titled],+ backing: .buffered,+ defer: true+ )+ let sheet = NSWindow(+ contentRect: NSRect(x: 0, y: 0, width: 200, height: 100),+ styleMask: [.titled],+ backing: .buffered,+ defer: true+ )let key = KeyWindow(window)let sheetInFront = SheetInFront(keyWindow: { key.window })sheetInFront.start()diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swiftindex eb9e7b8e..586ce687 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift@@ -158,7 +158,12 @@ struct ZshRequirementsTests {struct PeelLinesCommandTests {private func run(_ command: String, home: URL) async throws -> Int32 {- let answer = await Subprocess.run("/bin/zsh", ["-f", "-c", command], environment: ["HOME": home.path(percentEncoded: false), "PATH": "/usr/bin:/bin"], timeout: 10)+ let answer = await Subprocess.run(+ "/bin/zsh",+ ["-f", "-c", command],+ environment: ["HOME": home.path(percentEncoded: false), "PATH": "/usr/bin:/bin"],+ timeout: 10+ )guard case .success(let output) = answer else { throw POSIXError(.EIO) }#expect(output.errorText.isEmpty, "\(output.errorText)")return output.status@@ -191,7 +196,9 @@ struct PeelLinesCommandTests {let config = home.appending(path: ".ssh/config")let lines = SSHFile.lines(including: file, home: home)#expect(try await run(SSHFile.command(adding: lines, to: config, home: home), home: home) == 0)- let folder = try FileManager.default.attributesOfItem(atPath: config.deletingLastPathComponent().path(percentEncoded: false))+ let folder = try FileManager.default.attributesOfItem(+ atPath: config.deletingLastPathComponent().path(percentEncoded: false)+ )#expect((folder[.posixPermissions] as? Int) == 0o700)#expect(try String(contentsOf: config, encoding: .utf8) == "\n" + lines.joined(separator: "\n") + "\n")#expect(SSHFile.isIncluded(file, from: config, home: home))diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ShellSessionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ShellSessionsTests.swiftindex 494845b4..9c2d6416 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ShellSessionsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ShellSessionsTests.swift@@ -55,7 +55,13 @@ struct ShellSessionsTests {@Test func readsTerminalsShellSettingAsDefaultsDoes() async {let setting = TerminalSettings().shell()- guard case .success(let output) = await Subprocess.run("/usr/bin/defaults", ["read", TerminalSettings.identifier, "Shell"], timeout: 10), output.status == 0 else {+ guard+ case .success(let output) = await Subprocess.run(+ "/usr/bin/defaults",+ ["read", TerminalSettings.identifier, "Shell"],+ timeout: 10+ ), output.status == 0+ else {#expect(setting == nil)return}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swiftindex be3932ff..a8612fc5 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift@@ -13,7 +13,12 @@ struct SpaceInventoryTests {let unanswered = Unanswered()let stop = try await unanswered.stop {- _ = await SpaceInventory.scan(home: directory.url, root: directory.url, minimumSize: 1, measure: unanswered.measure)+ _ = await SpaceInventory.scan(+ home: directory.url,+ root: directory.url,+ minimumSize: 1,+ measure: unanswered.measure+ )}#expect(stop.took < .seconds(1))@@ -63,7 +68,12 @@ struct SpaceInventoryTests {try directory.setPermissions(0, of: "Library/Logs")defer { try? directory.setPermissions(0o755, of: "Library/Logs") }- let report = await SpaceInventory.scan(home: directory.url, root: directory.url, minimumSize: 100_000, measure: FileSize.measure)+ let report = await SpaceInventory.scan(+ home: directory.url,+ root: directory.url,+ minimumSize: 100_000,+ measure: FileSize.measure+ )#expect(report.items.map(\.id) == ["logs"])#expect(report.items.first?.size == nil)#expect(!report.needsFullDiskAccess, "ordinary permissions were read as a refusal Full Disk Access would lift")@@ -108,7 +118,12 @@ struct SpaceInventoryTests {let directory = try TemporaryDirectory()try directory.file(".colima/machine/disk.img", bytes: 4096)- let report = await SpaceInventory.scan(home: directory.url, root: directory.url, minimumSize: 1, measure: FileSize.measure)+ let report = await SpaceInventory.scan(+ home: directory.url,+ root: directory.url,+ minimumSize: 1,+ measure: FileSize.measure+ )let machines = try #require(report.items.first { $0.id == "colima" })#expect(machines.isReadOnly)#expect(machines.category == .virtualMachines)@@ -119,7 +134,12 @@ struct SpaceInventoryTests {let directory = try TemporaryDirectory()try directory.file("Library/Application Support/com.apple.wallpaper/aerials/videos/a.mov", bytes: 400_000)- let report = await SpaceInventory.scan(home: directory.url, root: directory.url, minimumSize: 100_000, measure: FileSize.measure)+ let report = await SpaceInventory.scan(+ home: directory.url,+ root: directory.url,+ minimumSize: 100_000,+ measure: FileSize.measure+ )#expect(report.items.map(\.id) == ["wallpapers"])}@@ -131,7 +151,12 @@ struct SpaceInventoryTests {try directory.file("Library/Developer/CoreSimulator/Caches/dyld/shared.bin", bytes: 400_000)try directory.file("Library/Developer/CoreSimulator/Images/runtime.dmg", bytes: 400_000)- let report = await SpaceInventory.scan(home: directory.url, root: directory.url, minimumSize: 100_000, measure: FileSize.measure)+ let report = await SpaceInventory.scan(+ home: directory.url,+ root: directory.url,+ minimumSize: 100_000,+ measure: FileSize.measure+ )let simulators = try #require(report.items.first { $0.id == "simulators" })let paths = simulators.urls.map { $0.lastPathComponent }diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SpaceRemovalTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SpaceRemovalTests.swiftindex 5cf6f54b..cefb0ddf 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SpaceRemovalTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SpaceRemovalTests.swift@@ -335,7 +335,11 @@ struct SpaceRemovalTests {let running = ["comspotifyclient": "Spotify"]let plan = await SpaceRemoval.plan(for: item(directory), environment: environment(directory), running: running)- let removable = await SpaceRemoval.removable(in: item(directory), environment: environment(directory), running: running)+ let removable = await SpaceRemoval.removable(+ in: item(directory),+ environment: environment(directory),+ running: running+ )#expect(removable.map(\.lastPathComponent) == ["com.gone.app"])#expect(removable == plan.removable)@@ -370,7 +374,11 @@ struct SpaceRemovalTests {try directory.file("home/Library/Caches/dev.zed.Zed/index.db")let running = [RunningCopies.Process(identifier: 2, bundleIdentifier: "dev.zed.Zed", bundleURL: URL(filePath: "/Applications/Zed.app"))]- let plan = await SpaceRemoval.plan(for: item(directory), environment: environment(directory), running: SpaceRemoval.namesOfRunningApps(running))+ let plan = await SpaceRemoval.plan(+ for: item(directory),+ environment: environment(directory),+ running: SpaceRemoval.namesOfRunningApps(running)+ )#expect(plan.appsToQuit == ["Zed"], "the note would read \(plan.appsToQuit.formatted(.list(type: .and)))")}@@ -474,7 +482,12 @@ struct SpaceRemovalTests {try directory.file("home/Library/Caches/com.slow.app/blob", bytes: 40_000)try directory.file("home/Library/Caches/com.gone.app/small.db", bytes: 4_000)- let plan = await SpaceRemoval.plan(for: item(directory), environment: environment(directory), exclusions: .none, running: [:]) { url in+ let plan = await SpaceRemoval.plan(+ for: item(directory),+ environment: environment(directory),+ exclusions: .none,+ running: [:]+ ) { url inurl.lastPathComponent == "com.slow.app" ? nil : await FileSize.contents(of: url)}@@ -490,7 +503,12 @@ struct SpaceRemovalTests {}let running = Mutex((now: 0, most: 0))- let plan = await SpaceRemoval.plan(for: item(directory), environment: environment(directory), exclusions: .none, running: [:]) { _ in+ let plan = await SpaceRemoval.plan(+ for: item(directory),+ environment: environment(directory),+ exclusions: .none,+ running: [:]+ ) { _ inrunning.withLock { $0.now += 1; $0.most = max($0.most, $0.now) }try? await Task.sleep(for: .milliseconds(500))running.withLock { $0.now -= 1 }@@ -519,7 +537,11 @@ struct SpaceRemovalTests {sizes: [kept: 1, deselected: 2, gone: 5, noLongerMeasured: 7])var choices = KeptSelection()- #expect(choices.update([], selectable: Set(first.removable), suggested: first.suggested) == [kept, deselected, gone, noLongerMeasured])+ #expect(+ choices.update([], selectable: Set(first.removable), suggested: first.suggested) == [+ kept, deselected, gone, noLongerMeasured,+ ]+ )let again = SpaceRemoval.Plan(removable: [kept, deselected, chosenByHand, unmeasured, new, noLongerMeasured],@@ -528,6 +550,10 @@ struct SpaceRemovalTests {sizes: [kept: 1, deselected: 2, chosenByHand: 3, unmeasured: 4, new: 6])let selected: Set = [kept, chosenByHand, gone, noLongerMeasured]- #expect(choices.update(selected, selectable: Set(again.removable), suggested: again.suggested) == [kept, chosenByHand, new])+ #expect(+ choices.update(selected, selectable: Set(again.removable), suggested: again.suggested) == [+ kept, chosenByHand, new,+ ]+ )}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/StringCatalogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/StringCatalogTests.swiftindex 8169c0c8..f669a020 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/StringCatalogTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/StringCatalogTests.swift@@ -81,7 +81,8 @@ import Testingvar problems: [String] = []for language in try Self.declaredLanguages() {for key in Self.sidebarNames {- guard let text = Self.value(of: key, in: language, catalog), Self.width(text, in: language) > room else { continue }+ guard let text = Self.value(of: key, in: language, catalog), Self.width(text, in: language) > room+ else { continue }problems.append("\(language): \(text.debugDescription) is \(Int(Self.width(text, in: language))) points, and a sidebar row has \(Int(room))")}}@@ -106,14 +107,21 @@ import Testinglet titles = keys.map { Self.value(of: $0, in: language, catalog) ?? $0 }let widest = titles.indices.map { index inlet end = index == 0 || index == titles.count - 1- return ceil((titles[index] as NSString).size(withAttributes: [.font: font]).width + (end ? 27 : 23.5))+ return ceil(+ (titles[index] as NSString).size(withAttributes: [.font: font]).width + (end ? 27 : 23.5)+ )}.max() ?? 0return CGFloat(titles.count) * widest}- let widestName = Self.sidebarNames.map { Self.width(Self.value(of: $0, in: language, catalog) ?? $0, in: language) }.max() ?? 0+ let widestName =+ Self.sidebarNames.map { Self.width(Self.value(of: $0, in: language, catalog) ?? $0, in: language) }+ .max() ?? 0// Plus a scroll bar's width, which `ToolSidebar` adds where scroll bars show beside the content.let scroller = NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy)- let sidebar = max(min(ceil(widestName + Self.sidebarSymbol) + Self.sidebarRowInsets, Self.sidebarMaximum) + scroller, 220)+ let sidebar = max(+ min(ceil(widestName + Self.sidebarSymbol) + Self.sidebarRowInsets, Self.sidebarMaximum) + scroller,+ 220+ )let checks: [(needs: CGFloat, room: CGFloat, what: String)] = [(sidebar + bar(settings) + 24, 960, "Settings' tabs beside the sidebar at the narrowest window"),(sidebar + bar(terminal) + 24, 1120, "Terminal's tabs beside the sidebar at the default window"),@@ -157,7 +165,8 @@ import Testing/// characters the font lacks. In an English process, Japanese kana would come from a Chinese font and draw wider.static func font(_ font: NSFont, in language: String) -> NSFont {let cascade = CTFontCopyDefaultCascadeListForLanguages(font, [language] as CFArray) as? [CTFontDescriptor] ?? []- return NSFont(descriptor: font.fontDescriptor.addingAttributes([.cascadeList: cascade]), size: font.pointSize) ?? font+ return NSFont(descriptor: font.fontDescriptor.addingAttributes([.cascadeList: cascade]), size: font.pointSize)+ ?? font}/// With no language declared, the checks above would have nothing to look at, so this runs them on a@@ -270,9 +279,14 @@ import Testinglet literal = try NSRegularExpression(pattern: #"Text\(verbatim: "((?:[^"\\]|\\.)*)"\)"#)var found: [String] = []for folder in ["Peel", "PeelFinder"] {- let enumerator = FileManager.default.enumerator(at: Self.repository.appending(path: folder), includingPropertiesForKeys: nil)+ let enumerator = FileManager.default.enumerator(+ at: Self.repository.appending(path: folder),+ includingPropertiesForKeys: nil+ )while let url = enumerator?.nextObject() as? URL {- guard url.pathExtension == "swift", let source = try? String(contentsOf: url, encoding: .utf8) else { continue }+ guard url.pathExtension == "swift", let source = try? String(contentsOf: url, encoding: .utf8) else {+ continue+ }for match in literal.matches(in: source, range: NSRange(source.startIndex..., in: source)) {let text = String(source[Range(match.range(at: 1), in: source)!])guard !allowed.contains(text), text.contains(where: \.isLetter), !text.contains("\\(") else { continue }@@ -360,7 +374,9 @@ struct CatalogChecker {guard let letters = oneLetterWords[language] else { return nil }let prose = text.replacing(/`[^`]*`/, with: "")let pattern = try! NSRegularExpression(pattern: "(?<![\\p{L}\\p{N}\\-’'])([\(letters)\(letters.uppercased())]) (?=\\S)")- guard let match = pattern.firstMatch(in: prose, range: NSRange(prose.startIndex..., in: prose)) else { return nil }+ guard let match = pattern.firstMatch(in: prose, range: NSRange(prose.startIndex..., in: prose)) else {+ return nil+ }return String(prose[Range(match.range(at: 1), in: prose)!])}@@ -414,7 +430,8 @@ struct CatalogChecker {let whole = String(text[Range(match.range, in: text)!])if whole == "%%" { continue }if whole.hasPrefix("${") || whole.hasPrefix("%#@") { named.append(whole); continue }- let length = match.range(at: 2).location == NSNotFound ? "" : String(text[Range(match.range(at: 2), in: text)!])+ let length =+ match.range(at: 2).location == NSNotFound ? "" : String(text[Range(match.range(at: 2), in: text)!])let conversion = String(text[Range(match.range(at: 3), in: text)!])let kind = conversion == "@" ? "@" : length + conversionif match.range(at: 1).location != NSNotFound {@@ -443,7 +460,11 @@ struct CatalogChecker {let opened = text.components(separatedBy: "^[").count - 1guard opened > 0 || text.contains("(inflect") else { return nil }do {- let parsed = try AttributedString(markdown: text, including: \.foundation, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))+ let parsed = try AttributedString(+ markdown: text,+ including: \.foundation,+ options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)+ )let runs = parsed.runs.filter { $0.inflect != nil }.countlet left = String(parsed.characters)if runs != opened { return "\(opened) ^[ but \(runs) inflected runs" }@@ -479,7 +500,14 @@ struct CatalogChecker {func leaves(_ node: [String: Any], category: String? = nil, isSubstitution: Bool = false) -> [Leaf] {var found: [Leaf] = []if let unit = node["stringUnit"] as? [String: Any] {- found.append(Leaf(category: category, state: unit["state"] as? String, text: unit["value"] as? String ?? "", isSubstitution: isSubstitution))+ found.append(+ Leaf(+ category: category,+ state: unit["state"] as? String,+ text: unit["value"] as? String ?? "",+ isSubstitution: isSubstitution+ )+ )}if let set = node["stringSet"] as? [String: Any] {found += (set["values"] as? [String] ?? [""]).map { Leaf(category: category, state: set["state"] as? String, text: $0) }@@ -547,12 +575,20 @@ struct CatalogChecker {}let categories = Set(found.filter { !$0.isSubstitution }.compactMap(\.category))let forms = found.filter { $0.category != nil && !$0.isSubstitution }- if !forms.isEmpty, !forms.contains(where: { Self.integer.firstMatch(in: $0.text, range: NSRange($0.text.startIndex..., in: $0.text)) != nil }) {+ if !forms.isEmpty,+ !forms.contains(where: {+ Self.integer.firstMatch(in: $0.text, range: NSRange($0.text.startIndex..., in: $0.text)) != nil+ }) {fail(path, key, language, "plural", "no form shows the number, which Xcode refuses to build: write a key for one and one for more")}if Self.oneIsMoreThanOne.contains(language) {let ones = found.filter { $0.category == "one" }- if ones.contains(where: { $0.isSubstitution ? !$0.text.contains("%arg") : Self.integer.firstMatch(in: $0.text, range: NSRange($0.text.startIndex..., in: $0.text)) == nil }) {+ if ones.contains(where: {+ $0.isSubstitution+ ? !$0.text.contains("%arg")+ : Self.integer.firstMatch(in: $0.text, range: NSRange($0.text.startIndex..., in: $0.text))+ == nil+ }) {fail(path, key, language, "plural", "`one` is not only 1 in this language, so its form shows the number")}}@@ -563,7 +599,15 @@ struct CatalogChecker {if !extra.isEmpty { fail(path, key, language, "plural", "\(extra.sorted()) is no category of this language") }}for leaf in found {- check(leaf, key: key, source: source, sourceSlots: sourceSlots, substitutions: substitutions, language: language, catalog: catalog)+ check(+ leaf,+ key: key,+ source: source,+ sourceSlots: sourceSlots,+ substitutions: substitutions,+ language: language,+ catalog: catalog+ )}for (name, forms) in Self.substitutionCategories(node) {guard let cldr = Self.plurals[language], !forms.isEmpty else { continue }@@ -577,7 +621,10 @@ struct CatalogChecker {}private mutating func check(- _ leaf: Leaf, key: String, source: String, sourceSlots: (slots: [Slot], numbered: Int, unnumbered: Int, named: [String]),+ _ leaf: Leaf,+ key: String,+ source: String,+ sourceSlots: (slots: [Slot], numbered: Int, unnumbered: Int, named: [String]),substitutions: [String: Slot], language: String, catalog: Catalog) {let path = catalog.path@@ -603,17 +650,20 @@ struct CatalogChecker {if Self.menuWords[key] == nil, text.filter({ $0 == ellipsis }).count != source.filter({ $0 == "…" }).count {fail(path, key, language, "ellipsis", "the English has \(source.filter { $0 == "…" }.count), written \(ellipsis) in this language")}- for mark in ["`", "*", "_"] where text.components(separatedBy: mark).count != source.components(separatedBy: mark).count {+ for mark in ["`", "*", "_"]+ where text.components(separatedBy: mark).count != source.components(separatedBy: mark).count {fail(path, key, language, "markdown", "\(mark) is formatting: as many as the English has")}if Self.linkTargets(text) != Self.linkTargets(source) { fail(path, key, language, "markdown", "a link's address has to stay as the English has it") }if let broken = Self.brokenInflection(text) { fail(path, key, language, "inflect", broken) }if text.contains("^["), !source.contains("^[") { fail(path, key, language, "inflect", "markup only where the English has it") }if text.contains("^["), !Self.keepsInflection(language) { fail(path, key, language, "inflect", "this language cannot inflect: use a plural variation") }- if Self.menuWords[key] == nil, Self.swiftUIWords[key] == nil, let word = Self.oneLetterWordBeforeASpace(in: text, language: language) {+ if Self.menuWords[key] == nil, Self.swiftUIWords[key] == nil,+ let word = Self.oneLetterWordBeforeASpace(in: text, language: language) {fail(path, key, language, "space", "a no-break space after “\(word)”, so a line never ends with it")}- if language == "pl", Self.countBeforeASpace.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) != nil {+ if language == "pl",+ Self.countBeforeASpace.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) != nil {fail(path, key, language, "space", "a no-break space between a count and its noun")}if language == "ro", let word = Self.hyphenInsideAWord(text, source: source) {@@ -641,7 +691,8 @@ struct CatalogChecker {let added = Set(slots.slots).subtracting(sourceSlots.slots)// A plural form may leave its count out ("one file"), but never a name, and only when what is// left is numbered: an unnumbered %@ would then read the count.- let safeDrop = leaf.category != nil && added.isEmpty && dropped.allSatisfy { $0.kind != "@" } && slots.unnumbered == 0+ let safeDrop =+ leaf.category != nil && added.isEmpty && dropped.allSatisfy { $0.kind != "@" } && slots.unnumbered == 0if !safeDrop {fail(path, key, language, "placeholder", "\(slots.slots.map { "\($0.position):\($0.kind)" }) against \(sourceSlots.slots.map { "\($0.position):\($0.kind)" })")}@@ -682,7 +733,11 @@ struct CatalogChecker {}for (language, node) in localizations where language != "en" {let swiftUILanguage = Self.appleLanguages[language] ?? language- guard let expected = (plist[swiftUILanguage] as? [String: String])?[apple]?.replacingOccurrences(of: "%@", with: "Peel"),+ guard+ let expected = (plist[swiftUILanguage] as? [String: String])?[apple]?.replacingOccurrences(+ of: "%@",+ with: "Peel"+ ),let value = leaves(node as? [String: Any] ?? [:]).first?.text else { continue }if value != expected { fail("Localization/Peel/Localizable.xcstrings", key, language, rule, "SwiftUI says \(expected.debugDescription)") }}@@ -698,13 +753,17 @@ struct CatalogChecker {}for word in Self.systemWords {guard let data = try? Data(contentsOf: URL(filePath: word.table)),- let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else {+ let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]+ else {fail("Localization/Peel/Localizable.xcstrings", word.key, "en", "system", "\(word.table) is not on this Mac")continue}let localizations = catalog[word.key]?["localizations"] as? [String: Any] ?? [:]for language in required {- guard let expected = (plist[Self.appleLanguages[language] ?? language] as? [String: Any])?[word.apple] as? String else {+ guard+ let expected = (plist[Self.appleLanguages[language] ?? language] as? [String: Any])?[word.apple]+ as? String+ else {fail("Localization/Peel/Localizable.xcstrings", word.key, language, "system", "macOS has no \(word.apple) in this language")continue}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TemporaryDirectory.swift b/Packages/PeelCore/Tests/PeelCoreTests/TemporaryDirectory.swiftindex e5ae85cc..f042a706 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TemporaryDirectory.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TemporaryDirectory.swift@@ -16,7 +16,10 @@ struct TemporaryDirectory: ~Copyable {@discardableResultfunc file(_ path: String, bytes: Int = 16) throws -> URL {let fileURL = url.appending(path: path)- try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: fileURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )try Data(count: bytes).write(to: fileURL)return fileURL}@@ -24,7 +27,10 @@ struct TemporaryDirectory: ~Copyable {@discardableResultfunc file(_ path: String, contents: Data) throws -> URL {let fileURL = url.appending(path: path)- try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: fileURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )try contents.write(to: fileURL)return fileURL}@@ -41,7 +47,10 @@ struct TemporaryDirectory: ~Copyable {func compressedTextFile(_ path: String) throws -> URL {let fileURL = url.appending(path: path)let source = fileURL.deletingLastPathComponent().appending(path: ".source-\(fileURL.lastPathComponent)")- try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: fileURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )try Data(String(repeating: "hello world ", count: 20_000).utf8).write(to: source)let ditto = try Process.run(URL(filePath: "/usr/bin/ditto"), arguments: ["--hfsCompression", source.path, fileURL.path])ditto.waitUntilExit()diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeAudit.swift b/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeAudit.swiftindex 1f4760e3..ae3f26a8 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeAudit.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeAudit.swift@@ -37,7 +37,11 @@ enum TerminalThemeAudit {expect(lc(theme.cursor) >= 45, "cursor Lc \(lc(theme.cursor))")expect(apcaLc(theme.background, on: theme.cursor) >= 45, "the letter under the cursor is hard to read")for slot in 1...6 {- let best = max(apcaLc(theme.text, on: ansi[slot]), apcaLc(ansi[0], on: ansi[slot]), apcaLc(theme.background, on: ansi[slot]))+ let best = max(+ apcaLc(theme.text, on: ansi[slot]),+ apcaLc(ansi[0], on: ansi[slot]),+ apcaLc(theme.background, on: ansi[slot])+ )expect(best >= 45, "no text reads on ANSI \(slot)")}return issues@@ -134,7 +138,8 @@ enum TerminalThemeAudit {let sh = 1 + 0.015 * chromaPrimeMean * tlet rt = -2 * (pow(chromaPrimeMean, 7) / (pow(chromaPrimeMean, 7) + pow(25, 7))).squareRoot()* sin(60 * exp(-pow((hueMean - 275) / 25, 2)) * radians)- return (pow(deltaL / sl, 2) + pow(deltaC / sc, 2) + pow(deltaH / sh, 2) + rt * (deltaC / sc) * (deltaH / sh)).squareRoot()+ return (pow(deltaL / sl, 2) + pow(deltaC / sc, 2) + pow(deltaH / sh, 2) + rt * (deltaC / sc) * (deltaH / sh))+ .squareRoot()}static func colorBlind(_ color: UInt32, protanopia: Bool) -> UInt32 {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeLedgerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeLedgerTests.swiftindex 53162e7a..c8cc21bd 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeLedgerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeLedgerTests.swift@@ -41,7 +41,10 @@ struct TerminalThemeLedgerTests {#expect(try ledger.use(theme, in: terminal) == .changed)let written = try #require(terminal.storedProfiles[theme.profileName])- #expect(TerminalProfile.fingerprint(of: written) == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: theme)))+ #expect(+ TerminalProfile.fingerprint(of: written)+ == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: theme))+ )#expect(terminal.storedProfiles["Basic"] != nil)#expect(terminal.names == [.newWindows: theme.profileName, .startup: theme.profileName])#expect(ledger.theme(in: terminal) == theme)@@ -182,7 +185,10 @@ struct TerminalThemeLedgerTests {#expect(try ledger.use(theme, in: terminal) == .changed)let current = try #require(terminal.storedProfiles[theme.profileName])- #expect(TerminalProfile.fingerprint(of: current) == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: theme)))+ #expect(+ TerminalProfile.fingerprint(of: current)+ == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: theme))+ )}@Test func theLedgerReadsBackWhatItStored() throws {@@ -227,7 +233,10 @@ struct TerminalOptionTests {#expect(profile["useOptionAsMetaKey"] as? Bool == true)#expect(ledger.options(in: terminal) == [.optionAsMeta])profile["useOptionAsMetaKey"] = nil- #expect(TerminalProfile.fingerprint(of: profile) == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: theme)))+ #expect(+ TerminalProfile.fingerprint(of: profile)+ == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: theme))+ )#expect(ledger.set(.noAlertSound, to: true, in: terminal) == .changed)#expect(terminal.storedProfiles[theme.profileName]?["Bell"] as? Bool == false)@@ -236,7 +245,10 @@ struct TerminalOptionTests {}@Test func anOptionTurnedOffLeavesTheKeyToTerminalAsApplesOwnProfilesDo() throws {- let apple = try #require(PropertyListSerialization.propertyList(from: Data(contentsOf: TerminalThemeTests.clearDark), format: nil) as? [String: Any])+ let apple = try #require(+ PropertyListSerialization.propertyList(from: Data(contentsOf: TerminalThemeTests.clearDark), format: nil)+ as? [String: Any]+ )for option in TerminalOption.allCases {#expect(apple[option.rawValue] == nil)}@@ -247,7 +259,10 @@ struct TerminalOptionTests {#expect(ledger.set(.optionAsMeta, to: false, in: terminal) == .changed)#expect(ledger.set(.noAlertSound, to: false, in: terminal) == .changed)let profile = try #require(terminal.storedProfiles[theme.profileName])- #expect(TerminalProfile.fingerprint(of: profile) == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: theme)))+ #expect(+ TerminalProfile.fingerprint(of: profile)+ == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: theme))+ )#expect(ledger.options(in: terminal) == [])}@@ -259,7 +274,12 @@ struct TerminalOptionTests {#expect(try ledger.use(otherTheme, in: terminal) == .changed)#expect(ledger.options(in: terminal) == [.optionAsMeta, .noAlertSound])let profile = try #require(terminal.storedProfiles[otherTheme.profileName])- #expect(TerminalProfile.fingerprint(of: profile) == TerminalProfile.fingerprint(of: try TerminalProfile.settings(for: otherTheme, options: [.optionAsMeta, .noAlertSound])))+ #expect(+ TerminalProfile.fingerprint(of: profile)+ == TerminalProfile.fingerprint(+ of: try TerminalProfile.settings(for: otherTheme, options: [.optionAsMeta, .noAlertSound])+ )+ )_ = ledger.set(.optionAsMeta, to: false, in: terminal)#expect(try ledger.use(theme, in: terminal) == .changed)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeTests.swiftindex 823bb05b..03276a47 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TerminalThemeTests.swift@@ -9,7 +9,10 @@ struct TerminalThemeTests {}@Test func everyThemeIsTerminalsClearDarkWithItsOwnColors() throws {- let apple = try #require(PropertyListSerialization.propertyList(from: Data(contentsOf: Self.clearDark), format: nil) as? [String: Any])+ let apple = try #require(+ PropertyListSerialization.propertyList(from: Data(contentsOf: Self.clearDark), format: nil)+ as? [String: Any]+ )for theme in TerminalThemeCatalog.all {let profile = try TerminalProfile.settings(for: theme)#expect(Set(profile.keys) == Set(apple.keys).union(["CursorColor"]), "\(theme.name)")@@ -36,7 +39,9 @@ struct TerminalThemeTests {let page = try String(contentsOf: StringCatalogTests.repository.appending(path: "TERMINAL.md"), encoding: .utf8)for theme in themes {let data = try Data(contentsOf: folder.appending(path: "Themes/\(theme.profileName).terminal"))- let published = try #require(PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any])+ let published = try #require(+ PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]+ )let profile = try TerminalProfile.settings(for: theme)#expect(Set(published.keys) == Set(profile.keys), "\(theme.name)")for (key, value) in profile where !key.hasSuffix("Color") {@@ -54,11 +59,15 @@ struct TerminalThemeTests {let pictures = try FileManager.default.contentsOfDirectory(atPath: folder.path).filter { $0.hasSuffix(".png") }#expect(Set(pictures) == Set(PromptStyle.allCases.map { "\($0).png" }))let homebrew = URL(filePath: "/opt/homebrew", directoryHint: .isDirectory)- var lines = ShellSetting.allCases.flatMap(\.lines) + [ShellFile.completionSystem] + PromptStyle.allCases.flatMap(\.lines)+ var lines =+ ShellSetting.allCases.flatMap(\.lines) + [ShellFile.completionSystem]+ + PromptStyle.allCases.flatMap(\.lines)lines += GitSetting.allCases.filter { $0 != .signCommits }.flatMap { $0.values(signingKey: nil) }.map { "git config --global \($0.key) \($0.value)" }lines += ["git config --global gpg.format ssh", "git config --global commit.gpgSign true"]lines += SSHSetting.allCases.flatMap(\.lines)- lines += TerminalTool.allCases.flatMap { $0.setup(prefix: homebrew) }.flatMap(\.lines).map { $0.replacing("/opt/homebrew", with: "$HOMEBREW_PREFIX") }+ lines += TerminalTool.allCases.flatMap { $0.setup(prefix: homebrew) }.flatMap(\.lines).map {+ $0.replacing("/opt/homebrew", with: "$HOMEBREW_PREFIX")+ }let pageLines = Set(page.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) })for line in lines {#expect(pageLines.contains(line), "\(line)")@@ -78,8 +87,12 @@ struct TerminalThemeTests {] + zip(ansiKeys, theme.ansi)for (key, expected) in colors {let data = try #require(profile[key] as? Data, "\(theme.name): \(key)")- let color = try #require(try NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: data)?.usingColorSpace(.sRGB))- let channels = [color.redComponent, color.greenComponent, color.blueComponent].map { Int(($0 * 255).rounded()) }+ let color = try #require(+ try NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: data)?.usingColorSpace(.sRGB)+ )+ let channels = [color.redComponent, color.greenComponent, color.blueComponent].map {+ Int(($0 * 255).rounded())+ }#expect(channels == [Int(expected >> 16 & 0xFF), Int(expected >> 8 & 0xFF), Int(expected & 0xFF)], "\(theme.name): \(key)")#expect(color.alphaComponent == (key == "BackgroundColor" ? 0.95 : 1), "\(theme.name): \(key)")}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TerminalToolTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TerminalToolTests.swiftindex 2f55bfb0..752d8016 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TerminalToolTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TerminalToolTests.swift@@ -18,7 +18,12 @@ struct TerminalToolTests {@Test func everyLineForZshrcIsZshThatParses() async throws {for tool in TerminalTool.allCases {for setup in tool.setup(prefix: Self.prefix) where setup.place != .terminal {- let answer = await Subprocess.run("/bin/zsh", ["-f", "-n", "-c", setup.lines.joined(separator: "\n")], environment: [:], timeout: 10)+ let answer = await Subprocess.run(+ "/bin/zsh",+ ["-f", "-n", "-c", setup.lines.joined(separator: "\n")],+ environment: [:],+ timeout: 10+ )guard case .success(let output) = answer else { throw POSIXError(.EIO) }#expect(output.status == 0 && output.errorText.isEmpty, "\(tool): \(output.errorText)")}@@ -32,7 +37,9 @@ struct TerminalToolTests {#expect(try place(.fzfTab) < place(.zshAutosuggestions))#expect(try place(.zoxide) > place(.zshCompletions))#expect(shell.last == .zshSyntaxHighlighting)- let last = TerminalTool.allCases.filter { $0.setup(prefix: Self.prefix).contains { $0.place == .lastLineOfZshrc } }+ let last = TerminalTool.allCases.filter {+ $0.setup(prefix: Self.prefix).contains { $0.place == .lastLineOfZshrc }+ }#expect(last == [.zshSyntaxHighlighting])}@@ -61,11 +68,29 @@ struct TerminalToolTests {@Test func homebrewSaysWhetherAToolIsStillOffered() {let names: Set<String> = ["fzf", "fzf-tab", "tlrc"]- let retired = HomebrewRetirement(stage: .disabled, reason: .unmaintained, disableDate: nil, replacement: .formula("tlrc"))- #expect(TerminalTool.tlrc.availability(known: names, packages: [HomebrewPackage(name: "tlrc", kind: .formula)]) == .available)+ let retired = HomebrewRetirement(+ stage: .disabled,+ reason: .unmaintained,+ disableDate: nil,+ replacement: .formula("tlrc")+ )+ #expect(+ TerminalTool.tlrc.availability(known: names, packages: [HomebrewPackage(name: "tlrc", kind: .formula)])+ == .available+ )#expect(TerminalTool.fzfTab.availability(known: ["fzf-tab"], packages: []) == .unknownToHomebrew)- #expect(TerminalTool.tlrc.availability(known: names, packages: [HomebrewPackage(name: "tlrc", kind: .formula, retirement: retired)]) == .retired(retired))- #expect(TerminalTool.fzfTab.availability(known: names, packages: [HomebrewPackage(name: "fzf", kind: .formula, retirement: retired)]) == .retired(retired))+ #expect(+ TerminalTool.tlrc.availability(+ known: names,+ packages: [HomebrewPackage(name: "tlrc", kind: .formula, retirement: retired)]+ ) == .retired(retired)+ )+ #expect(+ TerminalTool.fzfTab.availability(+ known: names,+ packages: [HomebrewPackage(name: "fzf", kind: .formula, retirement: retired)]+ ) == .retired(retired)+ )}@Test func aToolIsInstalledOnlyWhenHomebrewLinkedEveryFormulaItNeeds() throws {@@ -76,7 +101,10 @@ struct TerminalToolTests {try FileManager.default.createSymbolicLink(at: prefix.appending(path: "opt/fzf-tab"), withDestinationURL: cellar)#expect(!TerminalTool.fzfTab.isInstalled(prefix: prefix))try FileManager.default.createDirectory(at: prefix.appending(path: "Cellar/fzf/0.74.4"), withIntermediateDirectories: true)- try FileManager.default.createSymbolicLink(at: prefix.appending(path: "opt/fzf"), withDestinationURL: prefix.appending(path: "Cellar/fzf/0.74.4"))+ try FileManager.default.createSymbolicLink(+ at: prefix.appending(path: "opt/fzf"),+ withDestinationURL: prefix.appending(path: "Cellar/fzf/0.74.4")+ )#expect(TerminalTool.fzfTab.isInstalled(prefix: prefix))}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TerminalWindowsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TerminalWindowsTests.swiftindex a326eebd..1513f963 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TerminalWindowsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TerminalWindowsTests.swift@@ -19,7 +19,9 @@ struct TerminalWindowsTests {@Test func aSwitchForOneAppNeverReadsTheGlobalDomain() throws {let domain = "org.example.peel.windows"- let globalKeys = CFPreferencesCopyKeyList(kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) as? [String] ?? []+ let globalKeys =+ CFPreferencesCopyKeyList(kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)+ as? [String] ?? []let held = try #require(globalKeys.lazy.compactMap { key -> (key: String, value: Tweak.Value)? inswitch CFPreferencesCopyAppValue(key as CFString, domain as CFString) {case let text as String: (key, .text(text))@@ -28,7 +30,16 @@ struct TerminalWindowsTests {}}.first)func tweak(_ kind: Tweak.Kind) -> Tweak {- Tweak(id: "test", domain: domain, key: held.key, kind: kind, restart: .none, group: .terminal, hasASystemControl: false, documentation: .undocumented)+ Tweak(+ id: "test",+ domain: domain,+ key: held.key,+ kind: kind,+ restart: .none,+ group: .terminal,+ hasASystemControl: false,+ documentation: .undocumented+ )}let store = TweakStore()#expect(store.state(of: tweak(.aSwitch(held.value))).isOn)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TextEditingTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TextEditingTests.swiftindex d82c76a6..850de234 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TextEditingTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TextEditingTests.swift@@ -7,7 +7,12 @@ struct TextEditingTests {/// A text field being typed in makes its window's field editor the first responder, and while it is, a command/// whose key is also a text editing key leaves that key to the text.@Test func followsTheFieldEditorOfTheWindowItWatches() {- let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 100), styleMask: [.titled], backing: .buffered, defer: true)+ let window = NSWindow(+ contentRect: NSRect(x: 0, y: 0, width: 300, height: 100),+ styleMask: [.titled],+ backing: .buffered,+ defer: true+ )let field = NSTextField(frame: NSRect(x: 10, y: 10, width: 200, height: 24))let label = NSTextField(labelWithString: "Name")window.contentView?.addSubview(field)@@ -30,11 +35,21 @@ struct TextEditingTests {/// A window that is not key can still say it became key, as the list macOS shows to complete a word does/// while a field is typed in. The field's window is still the key one, so the text is still being edited.@Test func asksWhichWindowIsKeyWheneverOneSaysItBecameKey() {- let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 100), styleMask: [.titled], backing: .buffered, defer: true)+ let window = NSWindow(+ contentRect: NSRect(x: 0, y: 0, width: 300, height: 100),+ styleMask: [.titled],+ backing: .buffered,+ defer: true+ )let field = NSTextField(frame: NSRect(x: 10, y: 10, width: 200, height: 24))window.contentView?.addSubview(field)window.makeFirstResponder(field)- let completions = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 100, height: 100), styleMask: [], backing: .buffered, defer: true)+ let completions = NSPanel(+ contentRect: NSRect(x: 0, y: 0, width: 100, height: 100),+ styleMask: [],+ backing: .buffered,+ defer: true+ )let key = KeyWindow(window)let editing = TextEditing(keyWindow: { key.window })editing.start()@@ -55,7 +70,12 @@ struct TextEditingTests {/// Undo and Redo act on the typing in the field being edited, and say what they would take back in the/// words of the field's undo manager.@Test func undoesAndRedoesTheTypingInTheFieldBeingEdited() throws {- let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 100), styleMask: [.titled], backing: .buffered, defer: true)+ let window = NSWindow(+ contentRect: NSRect(x: 0, y: 0, width: 300, height: 100),+ styleMask: [.titled],+ backing: .buffered,+ defer: true+ )let field = NSTextField(frame: NSRect(x: 10, y: 10, width: 200, height: 24))window.contentView?.addSubview(field)let editing = TextEditing()diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TranslatedNameTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TranslatedNameTests.swiftindex f91d661e..18d50c21 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TranslatedNameTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TranslatedNameTests.swift@@ -19,7 +19,10 @@ import Testing}@Test func theInstallerIsStillKnownAsTheApps() {- #expect(Installers.installedApp(for: URL(filePath: "/Users/me/Downloads/Latest-2.1.dmg"), in: [latest])?.bundleIdentifier == latest.bundleIdentifier)+ #expect(+ Installers.installedApp(for: URL(filePath: "/Users/me/Downloads/Latest-2.1.dmg"), in: [latest])?+ .bundleIdentifier == latest.bundleIdentifier+ )}@Test func theUninstallerBesideItIsStillItsOwn() {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashMoverTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashMoverTests.swiftindex 73259e5b..3be39364 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashMoverTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashMoverTests.swift@@ -9,7 +9,9 @@ import Testing/// tests run on an exFAT disk made for them.struct TrashMoverTests {private func contents(of url: URL) throws -> [String] {- try FileManager.default.contentsOfDirectory(atPath: url.path(percentEncoded: false)).filter { !$0.hasPrefix(".") }.sorted()+ try FileManager.default.contentsOfDirectory(atPath: url.path(percentEncoded: false)).filter {+ !$0.hasPrefix(".")+ }.sorted()}private func write(_ text: String, at url: URL) throws {@@ -24,12 +26,18 @@ struct TrashMoverTests {@Test func aFileMovesWhereTheDiskCannotRefuseToReplace() throws {let directory = try TemporaryDirectory()- let disk = try ScratchVolume(fileSystem: "ExFAT", mountedAt: directory.url.appending(path: "Stick", directoryHint: .isDirectory))+ let disk = try ScratchVolume(+ fileSystem: "ExFAT",+ mountedAt: directory.url.appending(path: "Stick", directoryHint: .isDirectory)+ )let file = disk.url.appending(path: "folder/notes.txt")try write("mine", at: file)let trash = disk.url.appending(path: "Trash", directoryHint: .isDirectory)- let landed = try TrashMover.move(try OpenItem.at(file.path(percentEncoded: false)).get(), into: try folder(trash)).get()+ let landed = try TrashMover.move(+ try OpenItem.at(file.path(percentEncoded: false)).get(),+ into: try folder(trash)+ ).get()#expect(URL(filePath: landed).lastPathComponent == "notes.txt")#expect(try String(contentsOfFile: landed, encoding: .utf8) == "mine")@@ -39,7 +47,10 @@ struct TrashMoverTests {@Test func whatIsAlreadyThereIsNeverReplaced() throws {let directory = try TemporaryDirectory()- let disk = try ScratchVolume(fileSystem: "ExFAT", mountedAt: directory.url.appending(path: "Stick", directoryHint: .isDirectory))+ let disk = try ScratchVolume(+ fileSystem: "ExFAT",+ mountedAt: directory.url.appending(path: "Stick", directoryHint: .isDirectory)+ )let file = disk.url.appending(path: "folder/notes.txt")let earlier = disk.url.appending(path: "Trash/notes.txt")try write("mine", at: file)@@ -55,7 +66,10 @@ struct TrashMoverTests {@Test func aFolderMovesWithEverythingInIt() throws {let directory = try TemporaryDirectory()- let disk = try ScratchVolume(fileSystem: "ExFAT", mountedAt: directory.url.appending(path: "Stick", directoryHint: .isDirectory))+ let disk = try ScratchVolume(+ fileSystem: "ExFAT",+ mountedAt: directory.url.appending(path: "Stick", directoryHint: .isDirectory)+ )try write("1", at: disk.url.appending(path: "folder/Project/one.txt"))try write("2", at: disk.url.appending(path: "folder/Project/deeper/two.txt"))let trash = disk.url.appending(path: "Trash", directoryHint: .isDirectory)@@ -70,7 +84,10 @@ struct TrashMoverTests {@Test func putBackNeverReplacesWhatCameBackInTheMeantime() throws {let directory = try TemporaryDirectory()- let disk = try ScratchVolume(fileSystem: "ExFAT", mountedAt: directory.url.appending(path: "Stick", directoryHint: .isDirectory))+ let disk = try ScratchVolume(+ fileSystem: "ExFAT",+ mountedAt: directory.url.appending(path: "Stick", directoryHint: .isDirectory)+ )let trashed = disk.url.appending(path: "Trash/notes.txt")let another = disk.url.appending(path: "Trash/other.txt")try write("from the Trash", at: trashed)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swiftindex dd3edf7c..47f445ff 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift@@ -48,12 +48,19 @@ struct TrashServiceTests {private func launchdPlist(_ path: String, in directory: borrowing TemporaryDirectory) throws -> URL {let label = URL(filePath: path).deletingPathExtension().lastPathComponent- return try directory.file(path, contents: PropertyListSerialization.data(fromPropertyList: ["Label": label], format: .xml, options: 0))+ return try directory.file(+ path,+ contents: PropertyListSerialization.data(fromPropertyList: ["Label": label], format: .xml, options: 0)+ )}/// A service that moves everything except `stuck` into the test's own Trash, both as the user and through/// the helper. The jobs it would stop are recorded in `stopped`.- private func service(in directory: borrowing TemporaryDirectory, stopped: Stopped, stuck: URL) throws -> TrashService {+ private func service(+ in directory: borrowing TemporaryDirectory,+ stopped: Stopped,+ stuck: URL+ ) throws -> TrashService {let trash = try directory.directory("home/.Trash")let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),@@ -177,7 +184,10 @@ struct TrashServiceTests {let going = try launchdPlist("home/Library/LaunchAgents/com.example.going.plist", in: directory)let stopped = Stopped()let service = TrashService(- environment: SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root")),+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ ),exclusions: Exclusions(paths: [kept]),stopJobs: { jobs, _ in await stopped.record(jobs) },moveToTrash: { url in@@ -218,9 +228,18 @@ struct TrashServiceTests {return destination}let service = TrashService(- environment: SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root")),+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ ),forgetDomains: { await forgotten.record($0, owner: $1) },- moveThroughHelper: { urls in TrashResult(trashed: urls.compactMap { url in (try? move(url)).map { TrashedItem(originalURL: url, trashedURL: $0, date: .now) } }) },+ moveThroughHelper: { urls in+ TrashResult(+ trashed: urls.compactMap { url in+ (try? move(url)).map { TrashedItem(originalURL: url, trashedURL: $0, date: .now) }+ }+ )+ },moveToTrash: move)@@ -347,7 +366,10 @@ struct TrashServiceTests {@Test func putBackLeavesAnotherItemInThePlaceItHolds() throws {let directory = try TemporaryDirectory()let original = directory.url.appending(path: "home/Projects/One/node_modules")- try FileManager.default.createDirectory(at: original.deletingLastPathComponent(), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: original.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )let first = try directory.directory("home/.Trash/node_modules")let identity = try #require(TrashedItem.Identity(ofItemAt: first))try FileManager.default.moveItem(at: first, to: directory.url.appending(path: "emptied"))@@ -367,7 +389,10 @@ struct TrashServiceTests {let service = try service(in: directory)let secret = try directory.file("home/Library/Messages/chat.db")try directory.directory("drop")- try FileManager.default.createSymbolicLink(at: directory.url.appending(path: "drop/.Trash"), withDestinationURL: secret.deletingLastPathComponent())+ try FileManager.default.createSymbolicLink(+ at: directory.url.appending(path: "drop/.Trash"),+ withDestinationURL: secret.deletingLastPathComponent()+ )let thesis = try directory.file("home/Documents/.Trash/thesis.pages")let nested = try directory.file("home/.Trash/folder/inside.txt")@@ -495,7 +520,10 @@ struct TrashServiceTests {let caches = directory.url.appending(path: "home/Library/Caches", directoryHint: .isDirectory)let service = try realService(in: directory, afterTheGuard: {try? FileManager.default.moveItem(at: caches.appending(path: "com.evil"), to: caches.appending(path: "com.evil.real"))- try? FileManager.default.createSymbolicLink(atPath: caches.appending(path: "com.evil").path(percentEncoded: false), withDestinationPath: "../Messages")+ try? FileManager.default.createSymbolicLink(+ atPath: caches.appending(path: "com.evil").path(percentEncoded: false),+ withDestinationPath: "../Messages"+ )})let result = await service.trash([decoy])@@ -516,12 +544,17 @@ struct TrashServiceTests {try directory.directory("home/Library/Caches/Vendor")let trashed = try directory.file("home/.Trash/x.pdf")let record = TrashedItem(originalURL: home.appending(path: "Library/Caches/Vendor/x.pdf"), trashedURL: trashed, date: .now)- let removalGuard = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let removalGuard = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )try TrashService.putBack(record) { held inlet answer = removalGuard.refusal(of: held)try? FileManager.default.moveItem(at: caches.appending(path: "Vendor"), to: caches.appending(path: "Vendor.real"))- try? FileManager.default.createSymbolicLink(atPath: caches.appending(path: "Vendor").path(percentEncoded: false), withDestinationPath: cloud.path(percentEncoded: false))+ try? FileManager.default.createSymbolicLink(+ atPath: caches.appending(path: "Vendor").path(percentEncoded: false),+ withDestinationPath: cloud.path(percentEncoded: false)+ )return answer}@@ -593,7 +626,9 @@ struct TrashServiceTests {private static var scratchVolume: URL? {guard let path = ProcessInfo.processInfo.environment["PEEL_TEST_VOLUME"], !path.isEmpty else { return nil }var isDirectory: ObjCBool = false- guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else { return nil }+ guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else {+ return nil+ }return URL(filePath: path, directoryHint: .isDirectory)}@@ -629,7 +664,10 @@ struct TrashServiceTests {let userItem = try directory.file("home/Library/Caches/com.example.app/cache.db").deletingLastPathComponent()let privilegedItem = try directory.file("root/Library/LaunchDaemons/com.example.helper.plist")- let result = try await service(in: directory).trash([userItem, privilegedItem], usingHelperFor: [privilegedItem])+ let result = try await service(in: directory).trash(+ [userItem, privilegedItem],+ usingHelperFor: [privilegedItem]+ )#expect(result.trashed.map(\.originalURL) == [userItem])#expect(result.failures == [TrashFailure(url: privilegedItem, reason: .needsHelper)])@@ -711,7 +749,10 @@ struct TrashServiceTests {/// be bypassed by writing the other.@Test func refusesTheSystemsRootsHoweverTheyAreSpelled() throws {let directory = try TemporaryDirectory()- let environment = SearchEnvironment(homeDirectory: directory.url, rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url,+ rootDirectory: directory.url.appending(path: "root")+ )let guardian = RemovalGuard(environment: environment)for path in ["/var", "/private/var", "/tmp", "/private/tmp", "/etc", "/private/etc", "/Users/Shared", "/cores",@@ -728,7 +769,9 @@ struct TrashServiceTests {let keychains = home.appending(path: "Library/Keychains", directoryHint: .isDirectory)let folders = try [keychains] + (0..<3).map { try directory.directory("home/Library/Keychains/\($0)") }try directory.directory("home/Library/Keychains/0/inner")- let guardian = RemovalGuard(environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root")))+ let guardian = RemovalGuard(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))+ )let longAgo = timespec(tv_sec: 946_684_800, tv_nsec: 0)let accessed = { (folder: URL) invar info = stat()@@ -812,7 +855,10 @@ struct TrashServiceTests {let folder = try directory.directory("home/Library/Application Support/Vendor")let inside = try directory.file("home/Library/Application Support/Vendor/App/state.db")let service = TrashService(- environment: SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root")),+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ ),moveToTrash: { url inguard url.isThere else { throw CocoaError(.fileNoSuchFile) }let moved = directory.url.appending(path: "trash-\(url.lastPathComponent)")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/Unanswered.swift b/Packages/PeelCore/Tests/PeelCoreTests/Unanswered.swiftindex f1a183a3..6143a66b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/Unanswered.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/Unanswered.swift@@ -41,7 +41,9 @@ final class Unanswered: Sendable {/// Runs `scan` and cancels it 50 ms after its first request, once everything it asks at the same time is/// waiting. Returns how long the scan took to return after the cancel, and how many folders it asked about/// before and after it.- func stop(_ scan: @escaping @Sendable () async -> Void) async throws -> (took: Duration, askedBefore: Int, askedAfter: Int) {+ func stop(+ _ scan: @escaping @Sendable () async -> Void+ ) async throws -> (took: Duration, askedBefore: Int, askedAfter: Int) {let running = Task { [self] inawait scan()finished.withLock { $0 = true }diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallSelectionTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallSelectionTests.swiftindex c3ddaa3b..c9f036fb 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallSelectionTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallSelectionTests.swift@@ -5,7 +5,11 @@ import Testingstruct UninstallSelectionTests {private let app = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "com.example.app", name: "Example")- private func leftover(_ name: String, confidence: MatchConfidence = .certain, requiresPrivileges: Bool = false) -> Leftover {+ private func leftover(+ _ name: String,+ confidence: MatchConfidence = .certain,+ requiresPrivileges: Bool = false+ ) -> Leftover {Leftover(url: URL(filePath: "/Users/me/Library/Caches/\(name)"),kind: .caches,@@ -18,7 +22,11 @@ struct UninstallSelectionTests {private let other = InstalledApp(url: URL(filePath: "/Applications/Other.app"), bundleIdentifier: "com.example.other", name: "Other")- private func uninstallation(of app: InstalledApp? = nil, appRequiresPrivileges: Bool = false, _ leftovers: [Leftover]) -> Uninstallation {+ private func uninstallation(+ of app: InstalledApp? = nil,+ appRequiresPrivileges: Bool = false,+ _ leftovers: [Leftover]+ ) -> Uninstallation {Uninstallation(app: app ?? self.app,appSize: 10_000,@@ -150,7 +158,9 @@ struct UninstallSelectionTests {let own = leftover("com.example.app")let others = leftover("com.example.other")let shared = leftover("com.example.shared")- let bulk = BulkUninstallation(uninstallations: [uninstallation([own, shared]), uninstallation(of: other, [others, shared])])+ let bulk = BulkUninstallation(uninstallations: [+ uninstallation([own, shared]), uninstallation(of: other, [others, shared]),+ ])var choices = UninstallSelection()let suggested = choices.update([], in: bulk, canUseHelper: true)#expect(suggested == [app.url, own.url, shared.url, other.url, others.url])@@ -172,7 +182,11 @@ struct UninstallSelectionTests {selected = choices.personChanged(from: selected, to: selected.subtracting([other.url]), in: bulk)#expect(selected == [app.url])- #expect(choices.personChanged(from: selected, to: selected.union([other.url]), in: bulk) == [app.url, other.url, others.url])+ #expect(+ choices.personChanged(from: selected, to: selected.union([other.url]), in: bulk) == [+ app.url, other.url, others.url,+ ]+ )}/// An app the person keeps stays kept through the page's scans: a file of it found later is not selected.@@ -184,7 +198,9 @@ struct UninstallSelectionTests {var selected = choices.update([], in: before, canUseHelper: true)selected = choices.personChanged(from: selected, to: selected.subtracting([other.url]), in: before)- let after = BulkUninstallation(uninstallations: [uninstallation([]), uninstallation(of: other, [others, later])])+ let after = BulkUninstallation(uninstallations: [+ uninstallation([]), uninstallation(of: other, [others, later]),+ ])#expect(choices.update(selected, in: after, canUseHelper: true) == [app.url])}@@ -215,6 +231,10 @@ struct UninstallSelectionTests {selected = choices.personChanged(from: selected, to: selected.subtracting([app.url]), in: bulk)selected = choices.personChanged(from: selected, to: selected.union([app.url]), in: bulk)#expect(selected == [app.url])- #expect(choices.personChanged(from: selected, to: selected.union([copy.url]), in: bulk) == [app.url, copy.url, own.url])+ #expect(+ choices.personChanged(from: selected, to: selected.union([copy.url]), in: bulk) == [+ app.url, copy.url, own.url,+ ]+ )}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swiftindex 72cc9a06..d5554372 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift@@ -5,7 +5,12 @@ import Testingstruct UninstallationTests {private let app = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "com.example.app", name: "Example")- private func leftover(_ name: String, confidence: MatchConfidence = .certain, sharedWith: [String] = [], requiresPrivileges: Bool = false) -> Leftover {+ private func leftover(+ _ name: String,+ confidence: MatchConfidence = .certain,+ sharedWith: [String] = [],+ requiresPrivileges: Bool = false+ ) -> Leftover {Leftover(url: URL(filePath: "/Users/me/Library/Caches/\(name)"),kind: .caches,@@ -16,7 +21,11 @@ struct UninstallationTests {)}- private func uninstallation(app: InstalledApp? = nil, appRequiresPrivileges: Bool = false, leftovers: [Leftover]) -> Uninstallation {+ private func uninstallation(+ app: InstalledApp? = nil,+ appRequiresPrivileges: Bool = false,+ leftovers: [Leftover]+ ) -> Uninstallation {Uninstallation(app: app ?? self.app,appSize: 10_000,@@ -58,9 +67,19 @@ struct UninstallationTests {#expect(uninstallation(app: protectedApp, leftovers: []).suggestedSelection(canUseHelper: true).isEmpty)// An app macOS keeps stays, so what it holds is data in use, not a leftover. For Notes, that is every note.- #expect(uninstallation(app: protectedApp, leftovers: [leftover("com.apple.Chess")]).suggestedSelection(canUseHelper: true).isEmpty)- #expect(uninstallation(appRequiresPrivileges: true, leftovers: []).suggestedSelection(canUseHelper: false).isEmpty)- #expect(uninstallation(appRequiresPrivileges: true, leftovers: []).suggestedSelection(canUseHelper: true) == [app.url])+ #expect(+ uninstallation(app: protectedApp, leftovers: [leftover("com.apple.Chess")]).suggestedSelection(+ canUseHelper: true+ ).isEmpty+ )+ #expect(+ uninstallation(appRequiresPrivileges: true, leftovers: []).suggestedSelection(canUseHelper: false).isEmpty+ )+ #expect(+ uninstallation(appRequiresPrivileges: true, leftovers: []).suggestedSelection(canUseHelper: true) == [+ app.url+ ]+ )#expect(uninstallation(appRequiresPrivileges: true, leftovers: []).privilegedURLs == [app.url])}@@ -77,9 +96,14 @@ struct UninstallationTests {let plan = uninstallation(leftovers: [plain, possible, keys, excluded, unmeasured, privileged])#expect(plan.selectable(canUseHelper: false) == [app.url, plain.url, possible.url, unmeasured.url])- #expect(plan.selectable(canUseHelper: true) == [app.url, plain.url, possible.url, unmeasured.url, privileged.url])+ #expect(+ plan.selectable(canUseHelper: true) == [app.url, plain.url, possible.url, unmeasured.url, privileged.url]+ )for canUseHelper in [false, true] {- #expect(plan.suggestedSelection(canUseHelper: canUseHelper).isSubset(of: plan.selectable(canUseHelper: canUseHelper)))+ #expect(+ plan.suggestedSelection(canUseHelper: canUseHelper)+ .isSubset(of: plan.selectable(canUseHelper: canUseHelper))+ )}let needsHelper = uninstallation(appRequiresPrivileges: true, leftovers: [plain])@@ -117,9 +141,14 @@ struct UninstallationTests {let shared = leftover("shared", sharedWith: [other.bundleIdentifier])let otherPlan = Uninstallation(app: other, appSize: 10_000, appRequiresPrivileges: false,- scan: LeftoverScan(leftovers: [leftover("com.example.other"), leftover("shared", sharedWith: [app.bundleIdentifier])], unreadableLocations: [])+ scan: LeftoverScan(+ leftovers: [leftover("com.example.other"), leftover("shared", sharedWith: [app.bundleIdentifier])],+ unreadableLocations: []+ ))- let bulk = BulkUninstallation(uninstallations: [uninstallation(appRequiresPrivileges: true, leftovers: [own, shared]), otherPlan])+ let bulk = BulkUninstallation(uninstallations: [+ uninstallation(appRequiresPrivileges: true, leftovers: [own, shared]), otherPlan,+ ])#expect(bulk.suggestedSelection(canUseHelper: false) == [other.url, URL(filePath: "/Users/me/Library/Caches/com.example.other")])#expect(bulk.suggestedSelection(canUseHelper: true).isSuperset(of: [app.url, own.url, shared.url, other.url]))@@ -161,10 +190,16 @@ struct UninstallationTests {}defer {for bundle in [inReach, beyond] {- try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bundle.path(percentEncoded: false))+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: bundle.path(percentEncoded: false)+ )}}- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )for (bundle, isBeyond) in [(inReach, false), (beyond, true)] {for isKept in [false, true] {@@ -195,7 +230,8 @@ struct UninstallationTests {let slow = Leftover(url: URL(filePath: "/Users/me/Library/Caches/slow"),kind: .caches,- match: LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: []).forReview(.notMeasured),+ match: LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: [])+ .forReview(.notMeasured),size: 0,isMeasured: false,requiresPrivileges: false@@ -253,7 +289,11 @@ struct UninstallationTests {#expect(plan.movable(among: plan.scan.leftovers, withApp: true).count == 1)#expect(!plan.privilegedURLs.contains(bundle))- let several = await BulkUninstallation.prepare([installed], installedApps: [installed], environment: environment)+ let several = await BulkUninstallation.prepare(+ [installed],+ installedApps: [installed],+ environment: environment+ )#expect(several.suggestedSelection(canUseHelper: true).map(\.lastPathComponent) == ["org.example.app.plist"])#expect(!several.selectable(canUseHelper: true).contains(bundle))#expect(several.staying(selected: []).isEmpty, "an app already in the Trash held its leftovers back")@@ -281,7 +321,11 @@ struct UninstallationTests {#expect(!plan.selectable(canUseHelper: true).contains(bundle))#expect(plan.movable(among: plan.scan.leftovers, withApp: true).count == plan.scan.leftovers.count)- let several = await BulkUninstallation.prepare([installed], installedApps: [installed], environment: environment)+ let several = await BulkUninstallation.prepare(+ [installed],+ installedApps: [installed],+ environment: environment+ )#expect(several.suggestedSelection(canUseHelper: true).isEmpty)#expect(!several.selectable(canUseHelper: true).contains(bundle))#expect(several.total == SizeTotal(plan.scan.leftovers.map { $0.isMeasured ? $0.size : nil }))@@ -300,7 +344,12 @@ struct UninstallationTests {#expect(free.suggestedSelection(canUseHelper: true).count == 2)for exclusions in [Exclusions(bundleIdentifiers: ["com.example.app"]), Exclusions(paths: [bundle])] {- let plan = await Uninstallation.prepare(installed, installedApps: [installed], exclusions: exclusions, environment: environment)+ let plan = await Uninstallation.prepare(+ installed,+ installedApps: [installed],+ exclusions: exclusions,+ environment: environment+ )#expect(plan.isExcluded)#expect(plan.scan.leftovers.isEmpty)#expect(plan.suggestedSelection(canUseHelper: true).isEmpty)@@ -319,8 +368,16 @@ struct UninstallationTests {let link = bin.appending(path: "scribble")try FileManager.default.createSymbolicLink(at: link, withDestinationURL: app.url.appending(path: "Contents/MacOS/scribble"))try directory.setPermissions(0o555, of: bin)- defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bin.path(percentEncoded: false)) }- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ defer {+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: bin.path(percentEncoded: false)+ )+ }+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )let plan = await Uninstallation.prepare(app, installedApps: [app], environment: environment)let leftover = try #require(plan.scan.leftovers.first { $0.url.lastPathComponent == "scribble" })@@ -343,14 +400,24 @@ struct UninstallationTests {}defer {for folder in [served, named, identified] {- try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: folder.path(percentEncoded: false))+ try? FileManager.default.setAttributes(+ [.posixPermissions: 0o755],+ ofItemAtPath: folder.path(percentEncoded: false)+ )}}- let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ )let plan = await Uninstallation.prepare(app, installedApps: [app], environment: environment)func leftover(_ url: URL) throws -> Leftover {- try #require(plan.scan.leftovers.first { PathPattern.comparablePath(of: $0.url) == PathPattern.comparablePath(of: url) })+ try #require(+ plan.scan.leftovers.first {+ PathPattern.comparablePath(of: $0.url) == PathPattern.comparablePath(of: url)+ }+ )}let suggested = plan.suggestedSelection(canUseHelper: true)let bulk = BulkUninstallation(uninstallations: [plan])@@ -383,10 +450,20 @@ struct UninstallationTests {let cache = try directory.directory("home/Library/Caches/com.example.app")let installed = InstalledApp(url: bundle, bundleIdentifier: "com.example.app", name: "Example")let path = PathPattern.comparablePath(of: bundle)- let cask = HomebrewPackage(name: "example", kind: .cask, appNames: ["Example.app"], leftoverPatterns: [path, path + "/", PathPattern.comparablePath(of: cache) + "/"])+ let cask = HomebrewPackage(+ name: "example",+ kind: .cask,+ appNames: ["Example.app"],+ leftoverPatterns: [path, path + "/", PathPattern.comparablePath(of: cache) + "/"]+ )let environment = SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))- let plan = await Uninstallation.prepare(installed, installedApps: [installed], casks: [cask], environment: environment)+ let plan = await Uninstallation.prepare(+ installed,+ installedApps: [installed],+ casks: [cask],+ environment: environment+ )#expect(!plan.scan.leftovers.contains { PathPattern.comparablePath(of: $0.url) == path }, "the app is listed as its own leftover")#expect(plan.scan.leftovers.count { $0.url.lastPathComponent == "com.example.app" } == 1, "one folder, two rows")@@ -397,7 +474,10 @@ struct UninstallationTests {/// both of the first two checks right.@Test func readsAPathByTheLocationThatWouldHaveFoundIt() {let home = URL(filePath: "/Users/me", directoryHint: .isDirectory)- let environment = SearchEnvironment(homeDirectory: home, rootDirectory: URL(filePath: "/", directoryHint: .isDirectory))+ let environment = SearchEnvironment(+ homeDirectory: home,+ rootDirectory: URL(filePath: "/", directoryHint: .isDirectory)+ )func place(_ path: String) -> SearchLocation.Kind {Uninstallation.place(of: URL(filePath: path), in: environment).kind@@ -519,7 +599,8 @@ struct SuggestedSelectionOnThisMacTests {let app = uninstallation.applet suggested = uninstallation.suggestedSelection(canUseHelper: true)for leftover in uninstallation.scan.leftovers where suggested.contains(leftover.url) {- let users = leftover.match.sharedWith + leftover.match.otherCopies.map { $0.path(percentEncoded: false) }+ let users =+ leftover.match.sharedWith + leftover.match.otherCopies.map { $0.path(percentEncoded: false) }#expect(!leftover.match.isShared, "\(app.name): \(leftover.url.lastPathComponent) is shared with \(users)")#expect(leftover.match.confidence >= .likely, "\(app.name): \(leftover.url.lastPathComponent) is only a guess")}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swiftindex c9856059..a18c87ea 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift@@ -55,7 +55,14 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {let configuration = URLSessionConfiguration.ephemeralconfiguration.protocolClasses = [CannedProtocol.self]let antarctic = UpdateChecker(session: URLSession(configuration: configuration), locale: Locale(identifier: "en_AQ"))- let sold = InstalledApp(url: URL(filePath: "/Applications/Notes Pro.app"), bundleIdentifier: "com.example.notes", name: "Notes Pro", version: "1.0", isFromAppStore: true, updateFeed: .appStore)+ let sold = InstalledApp(+ url: URL(filePath: "/Applications/Notes Pro.app"),+ bundleIdentifier: "com.example.notes",+ name: "Notes Pro",+ version: "1.0",+ isFromAppStore: true,+ updateFeed: .appStore+ )reply("itunes.apple.com", status: 400, #"{"errorMessage":"Invalid value(s) for key(s): [country]"}"#)#expect(await antarctic.status(for: sold) == .failed)#expect(CannedProtocol.asked.withLock { $0 } == ["itunes.apple.com", "itunes.apple.com"])@@ -83,7 +90,10 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {/// Sparkle compares build numbers, so a feed's `sparkle:version` is compared with the app's `CFBundleVersion`.@Test func comparesTheFeedsBuildWithTheAppsBuild() async {reply("feed.example.com", appcast("<item><enclosure url=\"https://feed.example.com/a.zip\" sparkle:version=\"101\" sparkle:shortVersionString=\"1.0\" /></item>"))- #expect(await checker.status(for: sparkleApp()) == .updateAvailable(version: "1.0", source: .developer, releaseNotes: nil))+ #expect(+ await checker.status(for: sparkleApp())+ == .updateAvailable(version: "1.0", source: .developer, releaseNotes: nil)+ )reply("feed.example.com", appcast("<item><enclosure url=\"https://feed.example.com/a.zip\" sparkle:version=\"100\" sparkle:shortVersionString=\"1.0\" /></item>"))#expect(await checker.status(for: sparkleApp()) == .upToDate)@@ -109,7 +119,9 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {/// it has an Intel processor.@Test func aReleaseForAppleSiliconIsAnUpdateOnlyOnAppleSilicon() async {reply("feed.example.com", appcast("<item><sparkle:version>200</sparkle:version><sparkle:shortVersionString>2.0</sparkle:shortVersionString><sparkle:hardwareRequirements>arm64</sparkle:hardwareRequirements></item>"))- let expected: UpdateStatus = HostArchitecture.isAppleSilicon ? .updateAvailable(version: "2.0", source: .developer, releaseNotes: nil) : .upToDate+ let expected: UpdateStatus = HostArchitecture.isAppleSilicon+ ? .updateAvailable(version: "2.0", source: .developer, releaseNotes: nil)+ : .upToDate#expect(await checker.status(for: sparkleApp()) == expected)}@@ -117,7 +129,14 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {/// answer is used for them rather than "Can't check for updates".@Test func automaticFallsBackToWhatHomebrewKnows() async {let app = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "com.example.app", name: "Example", version: "1.0")- let current = HomebrewPackage(name: "example", kind: .cask, installedVersion: "1.0", latestVersion: "1.0", isOutdated: false, appNames: ["Example.app"])+ let current = HomebrewPackage(+ name: "example",+ kind: .cask,+ installedVersion: "1.0",+ latestVersion: "1.0",+ isOutdated: false,+ appNames: ["Example.app"]+ )reply("nowhere.example.com", "")#expect(await checker.status(for: app, preference: .automatic, casks: [current]) == .upToDate)@@ -127,7 +146,13 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {// Its own feed fails: Homebrew's answer still stands.reply("feed.example.com", status: 500, "")var fed = sparkleApp()- fed = InstalledApp(url: app.url, bundleIdentifier: app.bundleIdentifier, name: app.name, version: "1.0", updateFeed: fed.updateFeed)+ fed = InstalledApp(+ url: app.url,+ bundleIdentifier: app.bundleIdentifier,+ name: app.name,+ version: "1.0",+ updateFeed: fed.updateFeed+ )#expect(await checker.status(for: fed, preference: .automatic, casks: [current]) == .upToDate)}@@ -135,11 +160,20 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {/// newer one is out with the release's page, where it is downloaded. A page anywhere but GitHub is not believed,/// and an answer in another form, or none, is a failed check.@Test func peelLearnsOfItsOwnNewReleaseFromGitHub() async {- let peel = InstalledApp(url: URL(filePath: "/Applications/Peel.app"), bundleIdentifier: "com.tuguidragos.Peel", name: "Peel", version: "1.0.1", updateFeed: .gitHubRelease(GitHubRelease.peel))+ let peel = InstalledApp(+ url: URL(filePath: "/Applications/Peel.app"),+ bundleIdentifier: "com.tuguidragos.Peel",+ name: "Peel",+ version: "1.0.1",+ updateFeed: .gitHubRelease(GitHubRelease.peel)+ )let page = "https://github.com/TuguiDragos/Peel/releases/tag/v1.0.2"reply("api.github.com", #"{"tag_name":"v1.0.2","html_url":"\#(page)","draft":false,"prerelease":false}"#)- #expect(await checker.status(for: peel) == .updateAvailable(version: "1.0.2", source: .developer, releaseNotes: URL(string: page)))+ #expect(+ await checker.status(for: peel)+ == .updateAvailable(version: "1.0.2", source: .developer, releaseNotes: URL(string: page))+ )#expect(CannedProtocol.asked.withLock { $0 } == ["api.github.com"])reply("api.github.com", #"{"tag_name":"v1.0.2","html_url":"https://example.com/peel.dmg"}"#)@@ -160,13 +194,27 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {/// all. Neither is a failed check: there is no Mac version to read, so the app is `.unsupported` and is asked/// about again in a week, rather than read as a feed that is down and asked again every few hours.@Test func aUniversalPurchaseIsNotAFailedCheck() async {- let sold = InstalledApp(url: URL(filePath: "/Applications/Notes Pro.app"), bundleIdentifier: "com.example.notes", name: "Notes Pro", version: "1.0", isFromAppStore: true, updateFeed: .appStore)+ let sold = InstalledApp(+ url: URL(filePath: "/Applications/Notes Pro.app"),+ bundleIdentifier: "com.example.notes",+ name: "Notes Pro",+ version: "1.0",+ isFromAppStore: true,+ updateFeed: .appStore+ )reply("itunes.apple.com", #"{"resultCount":1,"results":[{"kind":"software","version":"3.6.7","trackViewUrl":"https://apps.apple.com/app/id1"}]}"#)#expect(await checker.status(for: sold) == .unsupported)reply("itunes.apple.com", #"{"resultCount":1,"results":[{"kind":"mac-software","version":"2.0","trackViewUrl":"https://apps.apple.com/app/id1"}]}"#)- #expect(await checker.status(for: sold) == .updateAvailable(version: "2.0", source: .appStore, releaseNotes: URL(string: "https://apps.apple.com/app/id1")))+ #expect(+ await checker.status(for: sold)+ == .updateAvailable(+ version: "2.0",+ source: .appStore,+ releaseNotes: URL(string: "https://apps.apple.com/app/id1")+ )+ )reply("itunes.apple.com", #"{"resultCount":0,"results":[]}"#)#expect(await checker.status(for: sold) == .unsupported)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateMemoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateMemoryTests.swiftindex fd8ba559..a37e2c7b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateMemoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateMemoryTests.swift@@ -4,7 +4,13 @@ import Testingstruct UpdateMemoryTests {private func app(_ version: String, build: String = "1") -> InstalledApp {- InstalledApp(url: URL(filePath: "/Applications/Foo.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.foo", name: "Foo", version: version, buildVersion: build)+ InstalledApp(+ url: URL(filePath: "/Applications/Foo.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.foo",+ name: "Foo",+ version: version,+ buildVersion: build+ )}private let schedule = UpdateSchedule.next(after: .upToDate, following: nil)@@ -12,7 +18,12 @@ struct UpdateMemoryTests {/// An answer is about the build it was given for. If the app updates itself while Peel is closed, the/// answer about 1.0 is dropped; kept, it would read "2.0 → 2.0" under Updates Available.@Test func forgetsAnAnswerAboutAnotherBuild() {- let learned = UpdateMemory(status: .updateAvailable(version: "2.0"), schedule: schedule, checked: .now, describing: app("1.0"))+ let learned = UpdateMemory(+ status: .updateAvailable(version: "2.0"),+ schedule: schedule,+ checked: .now,+ describing: app("1.0")+ )let memory = ["com.example.foo": learned]#expect(UpdateMemory.recalled(from: memory, for: [app("1.0")]) == memory)@@ -43,18 +54,29 @@ struct UpdateMemoryTests {let memory = ["com.example.foo": learned]#expect(UpdateMemory.recalled(from: memory, for: [], now: schedule.due).count == 1)- #expect(UpdateMemory.recalled(from: memory, for: [], now: schedule.due.addingTimeInterval(UpdateMemory.longestAbsence + 1)).isEmpty)+ #expect(+ UpdateMemory.recalled(+ from: memory,+ for: [],+ now: schedule.due.addingTimeInterval(UpdateMemory.longestAbsence + 1)+ ).isEmpty+ )}/// An entry stored by an earlier version of Peel names no build, so it describes no app, and the app is/// checked again.@Test func readsAnEntryStoredBeforeBuildsWereKept() throws {- let stored = try JSONEncoder().encode(["com.example.foo": UpdateMemory(status: .upToDate, schedule: schedule, checked: nil, describing: app("1.0"))])+ let stored = try JSONEncoder().encode([+ "com.example.foo": UpdateMemory(status: .upToDate, schedule: schedule, checked: nil, describing: app("1.0"))+ ])var object = try #require(JSONSerialization.jsonObject(with: stored) as? [String: [String: Any]])object["com.example.foo"]?.removeValue(forKey: "version")object["com.example.foo"]?.removeValue(forKey: "buildVersion")- let old = try JSONDecoder().decode([String: UpdateMemory].self, from: JSONSerialization.data(withJSONObject: object))+ let old = try JSONDecoder().decode(+ [String: UpdateMemory].self,+ from: JSONSerialization.data(withJSONObject: object)+ )#expect(old["com.example.foo"]?.describes(app("1.0")) == false)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdatePrivacyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdatePrivacyTests.swiftindex 0e850610..36f6aa27 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdatePrivacyTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdatePrivacyTests.swift@@ -47,7 +47,9 @@ private final class OneRequestServer: Sendable {address.sin_addr.s_addr = inet_addr("127.0.0.1")var length = socklen_t(MemoryLayout<sockaddr_in>.size)let bound = withUnsafeMutablePointer(to: &address) {- $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(listening, $0, length) == 0 && getsockname(listening, $0, &length) == 0 }+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ bind(listening, $0, length) == 0 && getsockname(listening, $0, &length) == 0+ }}guard bound, listen(listening, 1) == 0 else {close(listening)@@ -84,7 +86,9 @@ private final class OneRequestServer: Sendable {let lines = String(decoding: request, as: UTF8.self).components(separatedBy: "\r\n").dropFirst()headers.withLock { found infound = Dictionary(lines.compactMap { line in- line.firstIndex(of: ":").map { (String(line[..<$0]), line[line.index(after: $0)...].trimmingCharacters(in: .whitespaces)) }+ line.firstIndex(of: ":").map {+ (String(line[..<$0]), line[line.index(after: $0)...].trimmingCharacters(in: .whitespaces))+ }}, uniquingKeysWith: { first, _ in first })}_ = Array(reply.utf8).withUnsafeBytes { write(connection, $0.baseAddress, $0.count) }diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateScheduleTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateScheduleTests.swiftindex cc8a881e..abb3cd5f 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateScheduleTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateScheduleTests.swift@@ -49,7 +49,9 @@ struct UpdateScheduleTests {waits.append(schedule.wait)}let hour: TimeInterval = 3600- let expected: [TimeInterval] = [UpdateSchedule.afterFailure, 12 * hour, 24 * hour, UpdateSchedule.longestAfterFailure]+ let expected: [TimeInterval] = [+ UpdateSchedule.afterFailure, 12 * hour, 24 * hour, UpdateSchedule.longestAfterFailure,+ ]#expect(Array(waits.prefix(4)) == expected)#expect(schedule.wait == UpdateSchedule.longestAfterFailure)#expect(waits.allSatisfy { $0 <= UpdateSchedule.longestAfterFailure })diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateTests.swiftindex 8f499eb8..9d968c61 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateTests.swift@@ -24,7 +24,11 @@ struct VersionComparisonTests {struct AppcastTests {private func latestItem(in feed: String, systemVersion: String = "26.7.0") -> AppcastItem? {- if case .latest(let item) = Appcast.read(Data(feed.utf8), systemVersion: systemVersion, isAppleSilicon: true) { item } else { nil }+ if case .latest(let item) = Appcast.read(Data(feed.utf8), systemVersion: systemVersion, isAppleSilicon: true) {+ item+ } else {+ nil+ }}/// A feed shared with WinSparkle lists a Windows build beside the Mac one, and the last release for an@@ -51,7 +55,9 @@ struct AppcastTests {<item><sparkle:version>500</sparkle:version><sparkle:hardwareRequirements>metal</sparkle:hardwareRequirements></item></channel></rss>"""- let read = { (isAppleSilicon: Bool) in Appcast.read(Data(feed.utf8), systemVersion: "26.7.0", isAppleSilicon: isAppleSilicon) }+ let read = { (isAppleSilicon: Bool) in+ Appcast.read(Data(feed.utf8), systemVersion: "26.7.0", isAppleSilicon: isAppleSilicon)+ }guard case .latest(let onIntel) = read(false), case .latest(let onAppleSilicon) = read(true) else {Issue.record("the feed was not read")return@@ -65,7 +71,10 @@ struct AppcastTests {<item><sparkle:version>600</sparkle:version><sparkle:hardwareRequirements>arm64 metal</sparkle:hardwareRequirements></item></channel></rss>"""- #expect(Appcast.read(Data(onlyForAppleSilicon.utf8), systemVersion: "26.7.0", isAppleSilicon: false) == .nothingForThisMac)+ #expect(+ Appcast.read(Data(onlyForAppleSilicon.utf8), systemVersion: "26.7.0", isAppleSilicon: false)+ == .nothingForThisMac+ )}/// The parser under `XMLParser` refuses a feed whose internal entities would grow it ten billion times.@@ -231,7 +240,11 @@ struct AppStoreLookupTests {}struct UpdateFeedDetectionTests {- private func bundle(info: [String: String], files: [String: String] = [:], in directory: borrowing TemporaryDirectory) throws -> URL {+ private func bundle(+ info: [String: String],+ files: [String: String] = [:],+ in directory: borrowing TemporaryDirectory+ ) throws -> URL {var plist = infoplist["CFBundleIdentifier"] = "com.example.app"let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)@@ -281,8 +294,13 @@ struct UpdateFeedDetectionTests {let contents = try directory.directory("Example.app/Contents")let info = ["SUFeedURL": "https://example.com/appcast.xml"]- #expect(UpdateFeed.detect(info: info, contents: contents, isFromAppStore: false, isSystemProtected: true) == nil)- #expect(UpdateFeed.detect(info: info, contents: contents, isFromAppStore: false, isSystemProtected: false) == .sparkle(try #require(URL(string: "https://example.com/appcast.xml"))))+ #expect(+ UpdateFeed.detect(info: info, contents: contents, isFromAppStore: false, isSystemProtected: true) == nil+ )+ #expect(+ UpdateFeed.detect(info: info, contents: contents, isFromAppStore: false, isSystemProtected: false)+ == .sparkle(try #require(URL(string: "https://example.com/appcast.xml")))+ )}/// Peel's own copy is checked against its releases on GitHub. No other app says where it is released, so no@@ -292,7 +310,14 @@ struct UpdateFeedDetectionTests {let contents = try directory.directory("Peel.app/Contents")let peel = UpdateFeed.detect(info: ["CFBundleIdentifier": "com.tuguidragos.Peel"], contents: contents, isFromAppStore: false, isSystemProtected: false)#expect(peel == .gitHubRelease(GitHubRelease.peel))- #expect(UpdateFeed.detect(info: ["CFBundleIdentifier": "com.example.editor"], contents: contents, isFromAppStore: false, isSystemProtected: false) == nil)+ #expect(+ UpdateFeed.detect(+ info: ["CFBundleIdentifier": "com.example.editor"],+ contents: contents,+ isFromAppStore: false,+ isSystemProtected: false+ ) == nil+ )}}@@ -355,7 +380,10 @@ struct TeamRegistryTests {_ = await registry.check([app("com.example.app", team: "AAAA111111")], now: start)#expect(await registry.check([app("com.example.app", team: nil)], now: start.addingTimeInterval(60)).changes.isEmpty, "said at once, which an update in progress would trigger")- let later = await registry.check([app("com.example.app", team: nil)], now: start.addingTimeInterval(60 + TeamRegistry.settlingTime + 1)).changes+ let later = await registry.check(+ [app("com.example.app", team: nil)],+ now: start.addingTimeInterval(60 + TeamRegistry.settlingTime + 1)+ ).changes#expect(later.map(\.previous) == ["AAAA111111"])#expect(later.map(\.current) == [""])@@ -380,12 +408,17 @@ struct TeamRegistryTests {let directory = try TemporaryDirectory()let url = directory.url.appending(path: "teams.json")_ = await TeamRegistry(url: url).check([app("com.example.app", team: "AAAA111111")])- let written = try FileManager.default.attributesOfItem(atPath: url.path(percentEncoded: false))[.modificationDate] as? Date+ let written =+ try FileManager.default.attributesOfItem(atPath: url.path(percentEncoded: false))[.modificationDate]+ as? Datetry await Task.sleep(for: .milliseconds(50))_ = await TeamRegistry(url: url).check([app("com.example.app", team: "AAAA111111")])- #expect(try FileManager.default.attributesOfItem(atPath: url.path(percentEncoded: false))[.modificationDate] as? Date == written)+ #expect(+ try FileManager.default.attributesOfItem(atPath: url.path(percentEncoded: false))[.modificationDate]+ as? Date == written+ )}/// A registry that cannot be read is never written over. Rebuilt from today's apps, it would hide for good a@@ -487,11 +520,21 @@ struct UpdateSourceTests {@Test func asksTheCaskThatIsInstalledNotItsBetterKnownSibling() {let firefox = InstalledApp(url: URL(filePath: "/Applications/Firefox.app"), bundleIdentifier: "org.mozilla.firefox", name: "Firefox")let known = HomebrewPackage(name: "firefox", kind: .cask, latestVersion: "140.0", appNames: ["Firefox.app"])- let installed = HomebrewPackage(name: "firefox@esr", kind: .cask, installedVersion: "128.1", latestVersion: "128.2", isOutdated: true, appNames: ["Firefox.app"])+ let installed = HomebrewPackage(+ name: "firefox@esr",+ kind: .cask,+ installedVersion: "128.1",+ latestVersion: "128.2",+ isOutdated: true,+ appNames: ["Firefox.app"]+ )let casks = CaskEvidence.combined(installed: [installed], known: [known], receipts: [])#expect(casks.map(\.name) == ["firefox", "firefox@esr"], "the base cask sorts first, which is what hid the other")- #expect(UpdateChecker().homebrewStatus(for: firefox, casks: casks) == .updateAvailable(version: "128.2", source: .homebrew, releaseNotes: nil))+ #expect(+ UpdateChecker().homebrewStatus(for: firefox, casks: casks)+ == .updateAvailable(version: "128.2", source: .homebrew, releaseNotes: nil)+ )#expect(CaskEvidence.cask(for: firefox, in: casks)?.name == "firefox@esr")}@@ -534,8 +577,18 @@ struct UpdatePreferencesTests {/// An app's page shows the last answer about it, but not an update the user muted: a skipped version, or an/// app Peel was told never to check, is not announced there again.@Test func aMutedUpdateIsNotShownAsAvailable() {- let editor = InstalledApp(url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.editor", name: "Editor", version: "1.0")- let notes = InstalledApp(url: URL(filePath: "/Applications/Notes.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.notes", name: "Notes", version: "2.0")+ let editor = InstalledApp(+ url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.editor",+ name: "Editor",+ version: "1.0"+ )+ let notes = InstalledApp(+ url: URL(filePath: "/Applications/Notes.app", directoryHint: .isDirectory),+ bundleIdentifier: "com.example.notes",+ name: "Notes",+ version: "2.0"+ )let waiting = UpdateStatus.updateAvailable(version: "3.0")let newer = UpdateStatus.updateAvailable(version: "4.0")let preferences = UpdatePreferences(source: .automatic, ignoredIdentifiers: ["com.example.notes"], skippedVersions: ["com.example.editor": "3.0"])diff --git a/Packages/PeelCore/Tests/PeelCoreTests/VendorRemovalTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/VendorRemovalTests.swiftindex 2901804d..a407265b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/VendorRemovalTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/VendorRemovalTests.swift@@ -3,8 +3,17 @@ import Foundationimport Testingstruct VendorRemovalTests {- private func app(in directory: borrowing TemporaryDirectory, path: String, name: String, identifier: String = "com.example.app") -> InstalledApp {- InstalledApp(url: directory.url.appending(path: path, directoryHint: .isDirectory), bundleIdentifier: identifier, name: name)+ private func app(+ in directory: borrowing TemporaryDirectory,+ path: String,+ name: String,+ identifier: String = "com.example.app"+ ) -> InstalledApp {+ InstalledApp(+ url: directory.url.appending(path: path, directoryHint: .isDirectory),+ bundleIdentifier: identifier,+ name: name+ )}@Test func findsAnUninstallerShippedWithTheApp() throws {@@ -147,7 +156,11 @@ struct VendorRemovalTests {let tool = try directory.file("usr/local/bin/example")let plain = { (url: URL) in URL(filePath: url.path(percentEncoded: false).removingSuffix("/")) }- let example = InstalledApp(url: URL(filePath: bundle.path(percentEncoded: false), directoryHint: .isDirectory), bundleIdentifier: "com.example.app", name: "Example")+ let example = InstalledApp(+ url: URL(filePath: bundle.path(percentEncoded: false), directoryHint: .isDirectory),+ bundleIdentifier: "com.example.app",+ name: "Example"+ )let receipt = PackageReceipt(identifier: "com.example.app.pkg",version: "1.0",diff --git a/Packages/PeelCore/Tests/PeelCoreTests/WalletIDs.swift b/Packages/PeelCore/Tests/PeelCoreTests/WalletIDs.swiftindex b480e668..cc171a86 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/WalletIDs.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/WalletIDs.swift@@ -32,9 +32,14 @@ enum WalletIDs {for line in text[start.upperBound..<end.lowerBound].split(separator: "\n") {let line = line.trimmingCharacters(in: .whitespaces)if line.hasPrefix("// "), let colon = line.range(of: ": ", options: .backwards) {- named = (String(line[line.index(line.startIndex, offsetBy: 3)..<colon.lowerBound]), String(line[colon.upperBound...]))+ named = (+ String(line[line.index(line.startIndex, offsetBy: 3)..<colon.lowerBound]),+ String(line[colon.upperBound...])+ )} else if line.hasPrefix("\""), let wallet = named {- entries.append(Entry(name: wallet.name, id: wallet.id, fingerprint: String(line.dropFirst().prefix(64))))+ entries.append(+ Entry(name: wallet.name, id: wallet.id, fingerprint: String(line.dropFirst().prefix(64)))+ )named = nil}}