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
List a package installed for one account alone
Țugui Dragoșa68f224c2f51
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex d5687a22..95ddf70f 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -72,9 +72,10 @@ the Homebrew page's uninstall and cleanups are Homebrew's own.(`SearchLocation`): Application Support, Caches, Containers, Preferences, launch agents, plug-in folders, thetop of the home folder, and more. It adds the paths the app's Homebrew cask names in its `uninstall` and `zap`stanzas, whether or not Homebrew installed the app (`CaskEvidence`); the installer receipt that proves the app,- its two files in `/private/var/db/receipts`, while what the package installed stays with the Package Receipts- page, which lists it only while the receipt is there, so a receipt whose package left more outside the app is- held back; the cask's own folder in Homebrew's Caskroom when Homebrew installed it (`HomebrewPackage.caskroomFolder`);+ its two files in `/private/var/db/receipts`, or in the home's `Library/Receipts` for a package installed for one+ account, while what the package installed stays with the Package Receipts page, which lists it only while the+ receipt is there, so a receipt whose package left more outside the app is held back; the cask's own folder in+ Homebrew's Caskroom when Homebrew installed it (`HomebrewPackage.caskroomFolder`);and what an area the app manages keeps in the home folder, such as Xcode's simulators. A page's scan runsthrough its `ScanRun`, so a newer scan or the Stop button ends an older one, and it counts what it reads so thepage can show progress.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6a86a1b4..6569dc91 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -538,6 +538,8 @@ its changes the way [Keep a Changelog](https://keepachangelog.com/) suggests.#### Package Receipts+- Lists a package installed for your account alone, and Forget Receipt and an uninstall find its receipt in your+ Library.- A folder is offered whole only when nothing inside it is missing from the receipt, and every item follows its app'srules, an app that uninstalls itself with its warning.- A package placed by its own scripts is never called a receipt only, a package installed into an app offers the appdiff --git a/GUIDE.md b/GUIDE.mdindex 4f751666..f57f06f6 100644--- a/GUIDE.md+++ b/GUIDE.md@@ -275,14 +275,13 @@ and how many items the others hold.warns that apps using it may stop working, says that macOS loads a camera plug-in only once legacy video devicesupport has been restored in macOS Recovery, or says that nothing loads it anymore, as for a Quick Look generator, anold Internet plug-in such as Flash, or a contextual menu item.-- **Package Receipts:** what installer packages other than Apple's put on your startup disk, item by item, to move to- the Trash.- Nothing is selected for you, and Select Recommended passes by a folder a package made that now holds what something- else put there. Forget Receipt moves the receipt itself to the Trash, through Peel's helper, so macOS no longer counts- the package as installed, and Forget All does so at once for every package listed under Receipt Only, which left- nothing on your Mac. An app a package installed follows the rules of its own page, and so does the rest of its- package: what is left to Finder or to the maker's uninstaller stays where it is, and what may exist only on this Mac- is shown and not selected.+- **Package Receipts:** what installer packages other than Apple's put on your startup disk, for every account or for+ yours alone, item by item, to move to the Trash. Nothing is selected for you, and Select Recommended passes by a+ folder a package made that now holds what something else put there. Forget Receipt moves the receipt itself to the+ Trash, through Peel's helper where it takes one, so macOS no longer counts the package as installed, and Forget All+ does so at once for every package listed under Receipt Only, which left nothing on your Mac. An app a package+ installed follows the rules of its own page, and so does the rest of its package: what is left to Finder or to the+ maker's uninstaller stays where it is, and what may exist only on this Mac is shown and not selected.- **Intel Software:** what still needs Rosetta, which macOS 27 is the last release to offer for most Intel software:apps, apps built for both that ask macOS to open them as Intel, the Intel-only parts inside other apps, plug-ins,drivers, background items, the commands in `/usr/local`, and the Java runtimes in either Library'sdiff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swiftindex 0782f9de..8f4d8f75 100644--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift@@ -191,8 +191,11 @@ public struct SearchEnvironment: Sendable {/// The first folder of every path the home's Library and the Mac's search as a location of their own, such as/// `Preferences`. The top of a Library never offers one of its own whole: it is looked inside, never moved. One- /// only the other Library searches, such as `PrivilegedHelperTools` in the home's, is a folder like any other.- static let homeLibraryEntriesScannedElsewhere = firstFolders(of: userEntries.map(\.1) + Plugins.folders.map(\.0))+ /// only the other Library searches, such as `PrivilegedHelperTools` in the home's, is a folder like any other. The+ /// home's `Receipts` holds what packages installed for this account left, each weighed as a receipt.+ static let homeLibraryEntriesScannedElsewhere = firstFolders(+ of: userEntries.map(\.1) + Plugins.folders.map(\.0) + ["Receipts"]+ )static let localLibraryEntriesScannedElsewhere = firstFolders(of: localEntries.map(\.1) + Plugins.folders.map(\.0) + systemCodeFolders)diff --git a/Packages/PeelCore/Sources/PeelCore/Packages/PackageActions.swift b/Packages/PeelCore/Sources/PeelCore/Packages/PackageActions.swiftindex 81510380..6d3c8e09 100644--- a/Packages/PeelCore/Sources/PeelCore/Packages/PackageActions.swift+++ b/Packages/PeelCore/Sources/PeelCore/Packages/PackageActions.swift@@ -1,26 +1,34 @@public import Foundation+internal import PeelPrivilegedpublic enum PackageActions {static let misplacedReceipt = "The receipt isn’t where macOS keeps receipts."static let forgottenReceipt = "It was already forgotten."- /// Returns the receipt's files that exist: `<identifier>.bom` and `<identifier>.plist` in- /// `private/var/db/receipts` on `volume`. macOS counts the package as installed only while they are there.- /// The identifier becomes part of a file name, so one that could name anything but a plain file in that- /// folder (empty, starting with `.`, or holding a `/`) gets no files.- static func receiptFiles(of identifier: String, onVolume volume: URL) -> [URL] {+ /// Returns the receipt's files that exist: `<identifier>.bom` and `<identifier>.plist` in the folder macOS keeps+ /// the receipts of `volume` in. macOS counts the package as installed only while they are there. The identifier+ /// becomes part of a file name, so one that could name anything but a plain file in that folder (empty, starting+ /// with `.`, or holding a `/`) gets no files.+ static func receiptFiles(of identifier: String, onVolume volume: URL, home: URL = .homeDirectory) -> [URL] {guard !identifier.isEmpty, !identifier.hasPrefix("."), !identifier.contains("/") else { return [] }- return ["bom", "plist"].map { receiptsFolder(onVolume: volume).appending(path: identifier + "." + $0) }+ let folder = receiptsFolder(onVolume: volume, home: home)+ return ["bom", "plist"].map { folder.appending(path: identifier + "." + $0) }.filter(\.isThere).map(PathPattern.spelledOnDisk)}+ /// When a receipt last changed, on the startup disk or in the home folder.+ public static func receiptsChanged(+ root: URL = URL(filePath: "/", directoryHint: .isDirectory), home: URL = .homeDirectory+ ) -> Date? {+ [receiptsChanged(onVolume: root, home: home), receiptsChanged(onVolume: home, home: home)]+ .compactMap(\.self).max()+ }+/// When a receipt on `volume` last changed: the newest date of the folder macOS keeps them in and of what is in it./// Writing, forgetting, or putting back a receipt changes the folder's; an upgrade rewrites a receipt in place,/// which changes only the file's. Nil when the folder can't be read.- public static func receiptsChanged(- onVolume volume: URL = URL(filePath: "/", directoryHint: .isDirectory)- ) -> Date? {- let folder = receiptsFolder(onVolume: volume)+ static func receiptsChanged(onVolume volume: URL, home: URL = .homeDirectory) -> Date? {+ let folder = receiptsFolder(onVolume: volume, home: home)let path = folder.path(percentEncoded: false)guard let names = try? FileManager.default.contentsOfDirectory(atPath: path) else { return nil }return ([folder] + names.map { folder.appending(path: $0) }).compactMap(modified).max()@@ -33,8 +41,12 @@ public enum PackageActions {return Date(timeIntervalSince1970: TimeInterval(time.tv_sec) + TimeInterval(time.tv_nsec) / 1_000_000_000)}- private static func receiptsFolder(onVolume volume: URL) -> URL {- volume.appending(path: "private/var/db/receipts", directoryHint: .isDirectory)+ /// The folder macOS keeps the receipts of `volume` in. For a package installed for one account, `pkgutil` names+ /// that account's home folder as the volume, and the receipt is in the Library there.+ private static func receiptsFolder(onVolume volume: URL, home: URL) -> URL {+ let isTheHome = PathPattern.comparablePath(of: volume) == PathPattern.comparablePath(of: home)+ let folder = isTheHome ? "Library/Receipts" : "private/var/db/receipts"+ return volume.appending(path: folder, directoryHint: .isDirectory)}/// Moves the receipt to the Trash, so macOS stops counting the package as installed and History can put@@ -52,17 +64,18 @@ public enum PackageActions {}static func forget(_ receipts: [PackageReceipt], through service: TrashService) async -> TrashResult {+ let home = service.environment.homeDirectoryvar files: [URL] = []var refused: [TrashFailure] = []for receipt in receipts {- let own = receiptFiles(of: receipt.identifier, onVolume: receipt.volume)+ let own = receiptFiles(of: receipt.identifier, onVolume: receipt.volume, home: home)// Asked now, with the exclusions this removal goes by: one can come after the scan the receipt is from.if receipt.apps.contains(where: service.excludes) {refused += own.map { TrashFailure(url: $0, reason: .guarded(.excluded)) }} else if own.isEmpty {// Named by the file macOS would keep, so the failure says which receipt rather than which disk. With// the folder there, the receipt was forgotten some other way since Peel read it.- let folder = receiptsFolder(onVolume: receipt.volume)+ let folder = receiptsFolder(onVolume: receipt.volume, home: home)let missing = folder.appending(path: receipt.identifier + ".plist")let why = folder.isRealFolder ? Self.forgottenReceipt : Self.misplacedReceiptrefused.append(TrashFailure(url: missing, reason: .failed(why)))@@ -71,7 +84,12 @@ public enum PackageActions {}}guard !files.isEmpty else { return TrashResult(failures: refused) }- var result = await service.trash(files, usingHelperFor: Set(files))+ // The helper serves no folder of a home, and the account can move what is there itself.+ let homeFolder = PathPattern.comparablePath(of: home)+ let forTheHelper = files.filter {+ !PathComponents.isPath(PathPattern.comparablePath(of: $0), inside: homeFolder)+ }+ var result = await service.trash(files, usingHelperFor: Set(forTheHelper))result.failures += refusedreturn result}diff --git a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipt.swift b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipt.swiftindex ccb187e7..40230977 100644--- a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipt.swift+++ b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipt.swift@@ -41,7 +41,8 @@ public struct PackageReceipt: Sendable, Hashable, Identifiable {public let identifier: Stringpublic let version: String?public let installDate: Date?- /// The volume the package was installed to, which is where its receipt is kept.+ /// The volume the package was installed to, which is where its receipt is kept, or the home folder of the account+ /// it was installed for.public let volume: URLpublic var items: [Item]/// True when the file list is known and nothing on it is still on disk. This is judged from the disk, not@@ -62,7 +63,11 @@ public struct PackageReceipt: Sendable, Hashable, Identifiable {/// `version` is the package's own number.public var productVersion: String?- public var id: String { identifier }+ /// A package can be installed on the startup disk and for an account too, each with a receipt of its own.+ public var id: String {+ let place = volume.path(percentEncoded: false)+ return place == "/" ? identifier : place + "/" + identifier+ }/// The version to show: the product's when the history gives one.public var shownVersion: String? { productVersion ?? version }diff --git a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swiftindex 4e10d2b3..fb93d668 100644--- a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift+++ b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift@@ -20,6 +20,13 @@ public enum PackageReceipts {"/usr/local/share/doc", "/usr/local/share/man", "/usr/local/share/man/man1", "/var",]+ /// The same in a home folder, where a package installed for one account writes, each named from that folder.+ static let sharedInTheHome: Set<String> = {+ let searched = LibraryFolder.inTheUsersLibrary.map { "/Library/" + $0.rawValue }+ let own = ProtectedData.accountFolders.map { "/" + $0 }+ return Set(searched + searched.flatMap(ProtectedObjects.ancestors(of:)) + own + ["/", "/Applications"])+ }()+/// Returns whether `receipt` is the installer receipt of the app whose bundle identifier is `identifier`:/// the identifier itself, or the identifier followed by `.`, `-`, or `_`. A shared prefix is not enough,/// so `com.adguard.mac.vpn-pkg` (AdGuard VPN) never proves `com.adguard.mac.adguard` (AdGuard), and@@ -57,6 +64,13 @@ public enum PackageReceipts {/// Nil when the tool could not be run, failed, or timed out: no answer is not "nothing installed".typealias Pkgutil = @Sendable ([String]) async -> String?+ /// `pkgutil` asked about what was installed for one account alone, which it knows by that account's home folder as+ /// the volume, and of which plain `pkgutil` says nothing.+ static func forAccount(home: URL, _ pkgutil: @escaping Pkgutil) -> Pkgutil {+ let volume = home.path(percentEncoded: false)+ return { await pkgutil(["--volume", volume] + $0) }+ }+public static func list(exclusions: Exclusions = .none) async -> PackageScan {await list(exclusions: exclusions, pkgutil: pkgutil)}@@ -77,18 +91,22 @@ public enum PackageReceipts {guard let packages = packageList(in: await pkgutil(["--pkgs-plist"])) else {return PackageScan(receipts: [], couldNotAsk: true)}- let identifiers = packages.filter { !$0.hasPrefix("com.apple.") }+ let account = forAccount(home: environment.homeDirectory, pkgutil)+ let forTheAccount = packageList(in: await account(["--pkgs-plist"])) ?? []+ let asked: [(identifier: String, volume: URL?, pkgutil: Pkgutil)] =+ packages.map { ($0, nil, pkgutil) } + forTheAccount.map { ($0, environment.homeDirectory, account) }let receipts = await withTaskGroup(of: PackageReceipt.self) { group in- var pending = identifiers.makeIterator()+ var pending = asked.filter { !$0.identifier.hasPrefix("com.apple.") }.makeIterator()var results: [PackageReceipt] = []- for _ in 0..<concurrentReceipts {- guard let identifier = pending.next() else { break }+ for _ in 0..<concurrentReceipts where !Task.isCancelled {+ guard let package = pending.next() else { break }group.addTask {await Self.receipt(- identifier,+ package.identifier,+ volume: package.volume,exclusions: exclusions,- pkgutil: pkgutil,+ pkgutil: package.pkgutil,removalGuard: removalGuard,reach: reach,shared: shared,@@ -100,12 +118,13 @@ public enum PackageReceipts {while let result = await group.next() {results.append(result)// A stopped scan starts no other package: each would ask `pkgutil` for nothing.- if !Task.isCancelled, let identifier = pending.next() {+ if !Task.isCancelled, let package = pending.next() {group.addTask {await Self.receipt(- identifier,+ package.identifier,+ volume: package.volume,exclusions: exclusions,- pkgutil: pkgutil,+ pkgutil: package.pkgutil,removalGuard: removalGuard,reach: reach,shared: shared,@@ -163,29 +182,38 @@ public enum PackageReceipts {installing url: URL,exclusions: Exclusions,pkgutil: @escaping Pkgutil,+ environment: SearchEnvironment = .current,systemExtensions: @escaping AppExtensions.SystemExtensionsAnswer = AppExtensions.askingMacOS) async -> [PackageReceipt] {let wanted = PathPattern.comparablePath(of: PathPattern.canonical(url))- let identifiers = await packages(listing: wanted, pkgutil: pkgutil)+ let home = environment.homeDirectory+ // A package installed for one account alone writes only in that account's home folder.+ let isInTheHome = PathComponents.isPath(wanted, inside: PathPattern.comparablePath(of: home))+ let asked: [(volume: URL?, pkgutil: Pkgutil)] =+ [(nil, pkgutil)] + (isInTheHome ? [(home, forAccount(home: home, pkgutil))] : [])var receipts: [PackageReceipt] = []- let removalGuard = RemovalGuard(environment: .current, exclusions: exclusions)- let reach = HelperReach(environment: .current)- let shared = sharedFolders(in: .current)+ let removalGuard = RemovalGuard(environment: environment, exclusions: exclusions)+ let reach = HelperReach(environment: environment)+ let shared = sharedFolders(in: environment)let installed = InstalledSystemExtensions(asking: systemExtensions)- for identifier in identifiers.sorted() where !Task.isCancelled {- let found = await receipt(- identifier,- exclusions: exclusions,- pkgutil: pkgutil,- removalGuard: removalGuard,- reach: reach,- shared: shared,- installed: installed,- environment: .current- )- guard found.installs(wanted) else { continue }- receipts.append(found.receipt)+ for domain in asked {+ let identifiers = await packages(listing: wanted, pkgutil: domain.pkgutil)+ for identifier in identifiers.sorted() where !Task.isCancelled {+ let found = await receipt(+ identifier,+ volume: domain.volume,+ exclusions: exclusions,+ pkgutil: domain.pkgutil,+ removalGuard: removalGuard,+ reach: reach,+ shared: shared,+ installed: installed,+ environment: environment+ )+ guard found.installs(wanted) else { continue }+ receipts.append(found.receipt)+ }}return receipts}@@ -217,12 +245,17 @@ public enum PackageReceipts {/// Whether the package left anything outside `app` that is still on the disk, of which the receipt is the only/// record. A package `pkgutil` doesn't describe counts as having left something, so its receipt stays.- static func leftSomethingOutside(_ identifier: String, app: URL, pkgutil: Pkgutil) async -> Bool {+ static func leftSomethingOutside(+ _ identifier: String, app: URL, accountHome: URL? = nil, pkgutil: Pkgutil+ ) async -> Bool {guard let (_, _, installLocation) = await description(of: identifier, pkgutil: pkgutil),let listing = await pkgutil(["--files", identifier])else { return true }let bundle = PathPattern.comparablePath(of: PathPattern.canonical(app))- return topLevel(files: lines(of: listing), installLocation: installLocation.path(percentEncoded: false)).onDisk+ return topLevel(+ files: lines(of: listing), installLocation: installLocation.path(percentEncoded: false),+ accountHome: accountHome?.path(percentEncoded: false)+ ).onDisk.contains { !PathComponents.isPath(PathPattern.comparablePath(of: URL(filePath: $0)), atOrInside: bundle) }}@@ -300,6 +333,7 @@ public enum PackageReceipts {private static func receipt(_ identifier: String,+ volume askedVolume: URL? = nil,exclusions: Exclusions = .none,pkgutil: Pkgutil,removalGuard: RemovalGuard,@@ -315,7 +349,7 @@ public enum PackageReceipts {identifier: identifier,version: nil,installDate: nil,- volume: URL(filePath: "/", directoryHint: .isDirectory),+ volume: askedVolume ?? URL(filePath: "/", directoryHint: .isDirectory),items: [], nothingLeftOnDisk: false, isFileListKnown: false)return Found(receipt: unknown, paths: [])@@ -326,7 +360,10 @@ public enum PackageReceipts {let throughScripts = listing != nil&& (files.isEmpty || isTemporary(installLocation: info["install-location"] as? String ?? ""))- let found = topLevel(files: files, installLocation: installLocation.path(percentEncoded: false))+ let found = topLevel(+ files: files, installLocation: installLocation.path(percentEncoded: false),+ accountHome: askedVolume?.path(percentEncoded: false)+ )// An app's own rules reach the rest of its package, as they reach its files on its page, and a folder an app// sits in moves that app too. What else a folder holds isn't this package's, even when the folder is.let inspected = { (paths: [String]) in@@ -463,10 +500,12 @@ public enum PackageReceipts {/// Returns the outermost existing paths that are this package's own, never a shared directory such as/// `/Library`. `onDisk` holds all of them, and a path this account can't reach is not gone. `offered` leaves out/// protected data (`ProtectedData.refuses`), which Peel never lists at all. `othersFilled` holds the folders- /// offered whole that hold what something besides this package put there.+ /// offered whole that hold what something besides this package put there. `accountHome` is the home folder of the+ /// account a package was installed for alone, where the folders every package shares are those of a home.static func topLevel(files: [String],installLocation: String,+ accountHome: String? = nil,home: String = URL.homeDirectory.path(percentEncoded: false),namesInside: (String) -> [String]? = PackageReceipts.namesInside,exists: (String) -> Bool = { !URL(filePath: $0).isMissing }@@ -479,7 +518,15 @@ public enum PackageReceipts {let listed = Set(paths)// A Mac disk is case-insensitive unless formatted otherwise, so `library/...` in a receipt is `/Library`.let shared = Set(sharedDirectories.map { $0.lowercased() })- let isShared = { (path: String) in shared.contains(path.lowercased()) }+ let sharedAtHome = Set(sharedInTheHome.map { $0.lowercased() })+ let accountFolder = accountHome.map { ($0 as NSString).standardizingPath.lowercased() }+ let isShared = { (path: String) in+ let path = path.lowercased()+ guard let accountFolder, path == accountFolder || path.hasPrefix(accountFolder + "/") else {+ return shared.contains(path)+ }+ return sharedAtHome.contains(path == accountFolder ? "/" : String(path.dropFirst(accountFolder.count)))+ }// A package can be built with a bundle as its install location, an app's own folder, and lists only what is// inside it. The bundle is still one item.if !isShared(root), isBundle(root, exists: exists) {diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swiftindex c48b69fa..76794215 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift@@ -150,7 +150,33 @@ public struct Uninstallation: Sendable {installedApps: [InstalledApp],exclusions: Exclusions,environment: SearchEnvironment,- pkgutil: PackageReceipts.Pkgutil = PackageReceipts.pkgutil+ pkgutil: @escaping PackageReceipts.Pkgutil = PackageReceipts.pkgutil+ ) async -> [Leftover] {+ var leftovers = await receiptLeftovers(+ for: app, receipts: receipts, installedApps: installedApps, exclusions: exclusions,+ environment: environment, accountHome: nil, pkgutil: pkgutil+ )+ // A package installed for one account alone writes only in that account's home folder.+ let home = environment.homeDirectory+ let homeFolder = PathPattern.comparablePath(of: home)+ if PathComponents.isPath(PathPattern.comparablePath(of: app.url), inside: homeFolder) {+ let account = PackageReceipts.forAccount(home: home, pkgutil)+ leftovers += await receiptLeftovers(+ for: app, receipts: await PackageReceipts.identifiers(pkgutil: account), installedApps: installedApps,+ exclusions: exclusions, environment: environment, accountHome: home, pkgutil: account+ )+ }+ return leftovers+ }++ private static func receiptLeftovers(+ for app: InstalledApp,+ receipts: Set<String>,+ installedApps: [InstalledApp],+ exclusions: Exclusions,+ environment: SearchEnvironment,+ accountHome: URL?,+ pkgutil: PackageReceipts.Pkgutil) async -> [Leftover] {let identifier = app.bundleIdentifier?.lowercased()let identifiers = Set((installedApps.map(\.bundleIdentifier) + [identifier]).compactMap { $0?.lowercased() })@@ -162,8 +188,11 @@ public struct Uninstallation: Sendable {var leftovers: [Leftover] = []for receipt in (Array(named) + wroteOnlyTheApp).sorted() {let leftMore = named.contains(receipt)- ? await PackageReceipts.leftSomethingOutside(receipt, app: app.url, pkgutil: pkgutil) : false- for url in PackageActions.receiptFiles(of: receipt, onVolume: environment.rootDirectory)+ ? await PackageReceipts.leftSomethingOutside(+ receipt, app: app.url, accountHome: accountHome, pkgutil: pkgutil+ ) : false+ let volume = accountHome ?? environment.rootDirectory+ for url in PackageActions.receiptFiles(of: receipt, onVolume: volume, home: environment.homeDirectory)where !exclusions.excludes(url) {let leftover = await LeftoverScanner.leftover(at: url,diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swiftindex 70ee6b93..a87c3fa9 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift@@ -661,6 +661,18 @@ struct LeftoverScannerTests {#expect(scan.leftovers.map(\.url.lastPathComponent) == ["net.example.client.helper"])}+ @Test func aReceiptInTheHomesLibraryIsLeftToTheRuleForReceipts() async throws {+ let directory = try TemporaryDirectory()+ try directory.file("home/Library/Receipts/net.example.client.plist", bytes: 16)+ try directory.file("home/Library/PrivilegedHelperTools/net.example.client.helper", bytes: 16)++ let scanner = LeftoverScanner(environment: environment(in: directory))++ let scan = await scanner.scan(tunewell, installedApps: [tunewell])++ #expect(scan.leftovers.map(\.url.lastPathComponent) == ["net.example.client.helper"])+ }+@Test func eachLibrarySkipsOnlyWhatItSearchesItself() throws {let directory = try TemporaryDirectory()let environment = environment(in: directory)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PackageActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PackageActionsTests.swiftindex 41c681d9..a659ef6d 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PackageActionsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PackageActionsTests.swift@@ -92,6 +92,48 @@ struct PackageActionsTests {#expect(result.failures.isEmpty)}+ @Test func aPackageInstalledForOneAccountKeepsItsReceiptInThatAccountsLibrary() async throws {+ let directory = try TemporaryDirectory()+ try directory.file("home/Library/Receipts/org.example.solo.bom")+ try directory.file("home/Library/Receipts/org.example.solo.plist")+ let home = PathPattern.canonical(directory.url.appending(path: "home", directoryHint: .isDirectory))+ let asked = Mutex<[String]>([])+ let moved = Mutex<[String]>([])+ let service = TrashService(+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: directory.url),+ moveThroughHelper: { urls in+ asked.withLock { $0 += urls.map(\.lastPathComponent) }+ return TrashResult()+ },+ moveToTrash: { url in+ moved.withLock { $0.append(url.lastPathComponent) }+ return url+ }+ )++ let result = await PackageActions.forget([receipt("org.example.solo", on: home)], through: service)++ #expect(asked.withLock { $0 }.isEmpty, "The helper serves no folder of a home")+ #expect(moved.withLock { $0 }.sorted() == ["org.example.solo.bom", "org.example.solo.plist"])+ #expect(result.failures.isEmpty)+ }++ @Test func aReceiptInTheHomeFolderCountsAsAChange() throws {+ let directory = try TemporaryDirectory()+ let root = directory.url.appending(path: "root", directoryHint: .isDirectory)+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)+ try directory.file("root/private/var/db/receipts/org.example.one.plist")+ let before = try #require(PackageActions.receiptsChanged(root: root, home: home))++ let later = Date(timeIntervalSinceNow: 60)+ let file = try directory.file("home/Library/Receipts/org.example.solo.plist")+ try FileManager.default.setAttributes(+ [.modificationDate: later], ofItemAtPath: file.path(percentEncoded: false)+ )++ #expect(try #require(PackageActions.receiptsChanged(root: root, home: home)) > before)+ }+@Test func forgetsSeveralReceiptsInOneRemoval() async throws {let directory = try TemporaryDirectory()for name in ["com.example.one", "com.example.two"] {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swiftindex cba94eaa..36ef5059 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift@@ -21,6 +21,86 @@ struct PackageReceiptsTests {#expect(found.offered == ["/\(plugIns)/SonoBus.aaxplugin"])}+ private func forOneAccount(+ home: URL, location: String = "", files: String+ ) -> PackageReceipts.Pkgutil {+ let volume = home.path(percentEncoded: false)+ return { arguments in+ guard arguments.prefix(2) == ["--volume", volume] else {+ return arguments.first == "--pkgs-plist" ? PkgutilAnswer.packages() : nil+ }+ switch arguments[2] {+ case "--pkgs-plist":+ return PkgutilAnswer.packages("org.example.solo")+ case "--pkg-info-plist":+ return PkgutilAnswer.packageInfo("org.example.solo", volume: volume, location: location)+ case "--files":+ return files+ case "--file-info-plist":+ return PkgutilAnswer.fileInfo(arguments[3], packages: "org.example.solo")+ default:+ return nil+ }+ }+ }++ @Test func listsAPackageInstalledForOneAccountWithoutItsSharedFolders() async throws {+ let directory = try TemporaryDirectory()+ let volume = PathPattern.canonical(directory.url)+ let home = volume.appending(path: "home", directoryHint: .isDirectory)+ try directory.file("home/Applications/Solo.app/Contents/Info.plist", bytes: 16)+ try directory.file("home/Library/Application Support/org.example.solo/data", bytes: 16)+ let files = """+ Applications+ Applications/Solo.app+ Applications/Solo.app/Contents+ Applications/Solo.app/Contents/Info.plist+ Library+ Library/Application Support+ Library/Application Support/org.example.solo+ Library/Application Support/org.example.solo/data++ """+ let environment = SearchEnvironment(homeDirectory: home, rootDirectory: volume)++ let scan = await PackageReceipts.list(+ exclusions: .none, pkgutil: forOneAccount(home: home, files: files), environment: environment+ )++ let solo = try #require(scan.receipts.first)+ #expect(solo.identifier == "org.example.solo")+ #expect(solo.items.map(\.url.lastPathComponent).sorted() == ["Solo.app", "org.example.solo"])+ #expect(!solo.items.contains { $0.requiresPrivileges })+ }++ @Test func aPackageOnTheStartupDiskAndInAnAccountAreTwoReceipts() {+ let receipt = { (volume: String) in+ PackageReceipt(+ identifier: "org.example.solo", version: nil, installDate: nil,+ volume: URL(filePath: volume, directoryHint: .isDirectory), items: []+ )+ }++ #expect(receipt("/").id == "org.example.solo")+ #expect(receipt("/Users/example").id != receipt("/").id)+ }++ @Test func findsThePackageThatInstalledAnAppInTheHomeFolder() async throws {+ let directory = try TemporaryDirectory()+ let volume = PathPattern.canonical(directory.url)+ let home = volume.appending(path: "home", directoryHint: .isDirectory)+ try directory.file("home/Applications/Solo.app/Contents/Info.plist", bytes: 16)+ let app = home.appending(path: "Applications/Solo.app", directoryHint: .isDirectory)+ let files = "Applications\nApplications/Solo.app\nApplications/Solo.app/Contents\n"++ let found = await PackageReceipts.receipts(+ installing: app, exclusions: .none, pkgutil: forOneAccount(home: home, files: files),+ environment: SearchEnvironment(homeDirectory: home, rootDirectory: volume)+ )++ #expect(found.map(\.identifier) == ["org.example.solo"])+ }+@Test func aPackageInstalledIntoAnAppOffersTheApp() {let files = ["Contents", "Contents/Info.plist", "Contents/MacOS", "Contents/MacOS/Example"]@@ -256,6 +336,7 @@ struct PackageReceiptsTests {)let pkgutil: PackageReceipts.Pkgutil = { arguments inif arguments.first == "--pkgs-plist" { return packages }+ if arguments.last == "--pkgs-plist" { return PkgutilAnswer.packages() }return await unanswered.pkgutil(arguments)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swiftindex 4dd6f38f..1932ab78 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift@@ -1199,6 +1199,36 @@ struct UninstallationTests {#expect(found.map(\.kind) == [.receipts, .receipts])}+ @Test func anAppInstalledForOneAccountTakesItsReceiptFromThatAccountsLibrary() async throws {+ let directory = try TemporaryDirectory()+ let root = PathPattern.canonical(directory.url)+ let home = root.appending(path: "home", directoryHint: .isDirectory)+ try directory.directory("home/Applications/Example.app")+ try directory.file("home/Library/Receipts/com.example.app.pkg.bom")+ try directory.file("home/Library/Receipts/com.example.app.pkg.plist")+ let environment = SearchEnvironment(homeDirectory: home, rootDirectory: root)+ let bundle = home.appending(path: "Applications/Example.app", directoryHint: .isDirectory)+ let app = InstalledApp(url: bundle, bundleIdentifier: "com.example.app", name: "Example")+ let volume = home.path(percentEncoded: false)+ let pkgutil: PackageReceipts.Pkgutil = { arguments in+ guard arguments.prefix(2) == ["--volume", volume] else { return nil }+ switch arguments[2] {+ case "--pkgs-plist": return PkgutilAnswer.packages("com.example.app.pkg")+ case "--pkg-info-plist": return PkgutilAnswer.packageInfo(arguments[3], volume: volume, location: "")+ case "--files": return "Applications\nApplications/Example.app\nApplications/Example.app/Contents\n"+ default: return nil+ }+ }++ let found = await Uninstallation.receiptLeftovers(+ for: app, receipts: [], installedApps: [app], exclusions: .none, environment: environment, pkgutil: pkgutil+ )++ #expect(found.map(\.url.lastPathComponent) == ["com.example.app.pkg.bom", "com.example.app.pkg.plist"])+ #expect(found.allSatisfy { $0.url.deletingLastPathComponent().lastPathComponent == "Receipts" })+ #expect(found.map(\.match.isRecommended) == [true, true])+ }+@Test func keepsAReceiptWhosePackageLeftMoreOutsideTheApp() async throws {let directory = try TemporaryDirectory()let environment = SearchEnvironment(