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
Know the apps a cask installs from an installer package
Țugui Dragoșb858862c6575
diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swiftindex 82349024..ce78df62 100644--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift@@ -37,9 +37,10 @@ public struct CaskEvidence: Sendable, Hashable {public static func installedCask(for app: InstalledApp, in casks: [HomebrewPackage]) -> HomebrewPackage? {let path = PathPattern.comparablePath(of: app.url)return casks.first { cask in- guard cask.installedVersion != nil, proves(cask, isThe: app) else { return false }- return cask.appTargets.isEmpty- || cask.appTargets.contains { $0.caseInsensitiveCompare(path) == .orderedSame }+ guard cask.installedVersion != nil else { return false }+ let isAmong = { (apps: [String]) in apps.contains { $0.caseInsensitiveCompare(path) == .orderedSame } }+ if isAmong(cask.packagedApps) { return true }+ return proves(cask, isThe: app) && (cask.appTargets.isEmpty || isAmong(cask.appTargets))}}diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swiftindex 635282eb..318dc441 100644--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift@@ -47,6 +47,10 @@ public struct HomebrewPackage: Sendable, Hashable, Identifiable {/// The entries of `packageIdentifiers` whose receipts are installed, lowercased. `noting(receipts:)` sets/// them, so the cask carries this proof to every place that checks it.public private(set) var receiptsOnThisMac: [String] = []+ /// Where the packages named by `packageIdentifiers` wrote apps, as their receipts list them, for an installed cask+ /// that installs from a `.pkg` and so may name no app. An installer's script can move an app once its package+ /// wrote it, so an app found at one of these is the cask's, and one found elsewhere may still be.+ public private(set) var packagedApps: [String] = []/// An installed cask's folder in Homebrew's Caskroom (`brew --caskroom <token>`), set by `kept(inCaskroom:)`.public private(set) var caskroomFolder: URL?/// True for an installed cask whose every app is gone from where Homebrew put it, set by `checkingItsApps()`.@@ -86,6 +90,12 @@ public struct HomebrewPackage: Sendable, Hashable, Identifiable {return noted}+ func noting(packagedApps: [String]) -> HomebrewPackage {+ var noted = self+ noted.packagedApps = packagedApps+ return noted+ }+public func kept(inCaskroom caskroom: URL) -> HomebrewPackage {var kept = selfkept.caskroomFolder = caskroom.appending(path: name, directoryHint: .isDirectory)@@ -507,7 +517,10 @@ public enum Homebrew {guard let packages = parseInstalled(Data(output.utf8), caskroom: caskroom) else {throw CommandFailure(output: output)}- return packages.map { $0.checkingItsApps() }+ return await packages.concurrentMap(width: PackageReceipts.concurrentReceipts) { package in+ let apps = await PackageReceipts.apps(installedByPackagesMatching: package.packageIdentifiers)+ return package.noting(packagedApps: apps).checkingItsApps()+ }}/// Returns the name of every cask Homebrew knows of, read from its local copy of the definitions. It needsdiff --git a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swiftindex 63799f5b..e12d83f5 100644--- a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift+++ b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift@@ -2,7 +2,7 @@ public import Foundationinternal import PeelPrivilegedpublic enum PackageReceipts {- private static let concurrentReceipts = 4+ static let concurrentReceipts = 4/// Directories many packages install into; they never belong to a single package.static let sharedDirectories: Set<String> = [@@ -187,10 +187,7 @@ public enum PackageReceipts {reach: HelperReach,shared: [String]) async -> Found {- guard- let data = await pkgutil(["--pkg-info-plist", identifier])?.data(using: .utf8),- let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]- else {+ guard let (info, volume, installLocation) = await description(of: identifier, pkgutil: pkgutil) else {// `pkgutil` named the package but did not describe it. It stays listed, with what it installed unknown,// rather than vanishing from the page.let unknown = PackageReceipt(@@ -203,11 +200,8 @@ public enum PackageReceipts {return Found(receipt: unknown, paths: [])}- let volume = URL(filePath: info["volume"] as? String ?? "/", directoryHint: .isDirectory)- let location = info["install-location"] as? String ?? ""- let installLocation = volume.appending(path: location, directoryHint: .isDirectory)let listing = await pkgutil(["--files", identifier])- let files = (listing ?? "").split(whereSeparator: \.isNewline).map(String.init)+ let files = lines(of: listing)let found = topLevel(files: files, installLocation: installLocation.path(percentEncoded: false))var items: [PackageReceipt.Item] = []@@ -242,13 +236,54 @@ public enum PackageReceipts {nothingLeftOnDisk: listing != nil && found.onDisk.isEmpty,isFileListKnown: listing != nil),- paths: files.map { file in- let relative = file.hasPrefix("./") ? String(file.dropFirst(2)) : file- return installLocation.appending(path: relative).path(percentEncoded: false)- }+ paths: files.map { path(of: $0, in: installLocation).path(percentEncoded: false) })}+ /// What `pkgutil --pkg-info-plist` says of a package, with the volume and the folder its file list is relative to.+ private static func description(+ of identifier: String,+ pkgutil: Pkgutil+ ) async -> (info: [String: Any], volume: URL, installLocation: URL)? {+ guard+ let data = await pkgutil(["--pkg-info-plist", identifier])?.data(using: .utf8),+ let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]+ else { return nil }+ let volume = URL(filePath: info["volume"] as? String ?? "/", directoryHint: .isDirectory)+ let location = info["install-location"] as? String ?? ""+ return (info, volume, volume.appending(path: location, directoryHint: .isDirectory))+ }++ private static func path(of file: String, in installLocation: URL) -> URL {+ installLocation.appending(path: file.hasPrefix("./") ? String(file.dropFirst(2)) : file)+ }++ /// Where the packages `patterns` name wrote apps, finding the packages as Homebrew does for a cask's `pkgutil`+ /// entries: `pkgutil --pkgs=` matches each pattern against whole identifiers.+ static func apps(installedByPackagesMatching patterns: [String]) async -> [String] {+ await apps(installedByPackagesMatching: patterns, pkgutil: pkgutil)+ }++ static func apps(installedByPackagesMatching patterns: [String], pkgutil: Pkgutil) async -> [String] {+ var identifiers: Set<String> = []+ for pattern in patterns {+ identifiers.formUnion(lines(of: await pkgutil(["--pkgs=\(pattern)"])))+ }+ var apps: Set<String> = []+ for identifier in identifiers where !Task.isCancelled {+ guard let (_, _, installLocation) = await description(of: identifier, pkgutil: pkgutil) else { continue }+ for folder in lines(of: await pkgutil(["--files", identifier, "--only-dirs"])) {+ let app = path(of: folder, in: installLocation)+ if app.pathExtension.lowercased() == "app" { apps.insert(PathPattern.comparablePath(of: app)) }+ }+ }+ return apps.sorted()+ }++ private static func lines(of answer: String?) -> [String] {+ (answer ?? "").split(whereSeparator: \.isNewline).map(String.init)+ }+/// The folders every account on the Mac uses, `/Users/Shared`, spelled to be compared.private static func sharedFolders(in environment: SearchEnvironment) -> [String] {environment.locations.filter { $0.kind == .sharedFolder }.map { PathPattern.comparablePath(of: $0.url) }diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swiftindex b4d6c830..c1e6c61b 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift@@ -140,15 +140,20 @@ public struct Uninstallation: Sendable {!exclusions.excludes(folder)else { return [] }let bundle = PathPattern.comparablePath(of: app.url)+ let isTheApp = { (path: String) in path.caseInsensitiveCompare(bundle) == .orderedSame }let others = cask.appTargets.filter { target in- target.caseInsensitiveCompare(bundle) != .orderedSame && FileManager.default.fileExists(atPath: target)+ !isTheApp(target) && FileManager.default.fileExists(atPath: target)}- let sharedWith = others.map { target in+ let otherApps = installedApps.filter { other in+ !isTheApp(PathPattern.comparablePath(of: other.url))+ && CaskEvidence.installedCask(for: other, in: casks)?.id == cask.id+ }+ let sharedWith = Set(otherApps.map(\.bundleIdentifier) + others.map { target inlet installed = installedApps.first {PathPattern.comparablePath(of: $0.url).caseInsensitiveCompare(target) == .orderedSame}return installed?.bundleIdentifier ?? Bundle(url: URL(filePath: target))?.bundleIdentifier ?? target- }+ })let home = environment.homeDirectory.path(percentEncoded: false)let leftover = await LeftoverScanner.leftover(at: folder,diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewReceiptTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewReceiptTests.swiftindex 8b4ccd0b..39567883 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewReceiptTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewReceiptTests.swift@@ -211,6 +211,61 @@ struct HomebrewReceiptTests {#expect(!plan.suggestedSelection(canUseHelper: false).contains(row.url))}+ @Test func anAppACasksPackagesWroteTakesItsHomebrewRecordAlong() async throws {+ let installed = try Installed()+ let app = try installed.app("Example", identifier: "org.example.app")+ let other = try installed.app("Example Effects", identifier: "org.example.effects")+ let location = String(PathPattern.comparablePath(of: app.url.deletingLastPathComponent()).dropFirst())+ let pkgutil: PackageReceipts.Pkgutil = { arguments in+ switch arguments {+ case ["--pkgs=org.example.suite.*"]:+ "org.example.suite.pkg\n"+ case ["--pkg-info-plist", "org.example.suite.pkg"]:+ PkgutilAnswer.packageInfo("org.example.suite.pkg", location: location)+ case ["--files", "org.example.suite.pkg", "--only-dirs"]:+ "Example.app\nExample.app/Contents\nExample Effects.app\n"+ default:+ nil+ }+ }+ let patterns = ["org.example.suite.*"]+ let cask = HomebrewPackage(name: "example", kind: .cask, installedVersion: "1.0", packageIdentifiers: patterns)+ .kept(inCaskroom: installed.caskroom)+ .noting(packagedApps: await PackageReceipts.apps(installedByPackagesMatching: patterns, pkgutil: pkgutil))++ #expect(cask.packagedApps == [app.url, other.url].map(PathPattern.comparablePath(of:)).sorted())+ let alone = await Uninstallation.prepare(+ app, installedApps: [app], casks: [cask], environment: installed.environment+ )+ let shared = await Uninstallation.prepare(+ app, installedApps: [app, other], casks: [cask], environment: installed.environment+ )++ #expect(alone.scan.leftovers.first { $0.kind == .homebrewReceipt }?.match.isRecommended == true)+ #expect(shared.scan.leftovers.first { $0.kind == .homebrewReceipt }?.match.sharedWith == ["org.example.effects"])+ }++ /// An installer's script can move the apps its package wrote, so the cask's other apps are found by its proof.+ @Test func anotherAppACaskProvesByItsReceiptKeepsItsHomebrewRecord() async throws {+ let installed = try Installed()+ let app = try installed.app("Synth", identifier: "org.example.synth")+ let other = try installed.app("Synth Effects", identifier: "org.example.effects")+ let cask = HomebrewPackage(+ name: "example",+ kind: .cask,+ installedVersion: "1.0",+ packageIdentifiers: ["org.example.synth.app.pkg", "org.example.effects.app.pkg"]+ ).kept(inCaskroom: installed.caskroom).noting(receipts: ["org.example.synth.app.pkg", "org.example.effects.app.pkg"])++ let plan = await Uninstallation.prepare(+ app, installedApps: [app, other], casks: [cask], environment: installed.environment+ )++ let row = try #require(plan.scan.leftovers.first { $0.kind == .homebrewReceipt })+ #expect(row.match.sharedWith == ["org.example.effects"])+ #expect(!plan.suggestedSelection(canUseHelper: false).contains(row.url))+ }+@Test func theReceiptGoesToTheTrashAfterTheApp() async throws {let installed = try Installed()let app = try installed.app("Example", identifier: "org.example.app")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/KnownCasksTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/KnownCasksTests.swiftindex 742a615f..10008875 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/KnownCasksTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/KnownCasksTests.swift@@ -148,6 +148,20 @@ struct KnownCasksTests {#expect(CaskEvidence.cask(for: copy, in: [cask]) != nil, "what the cask knows about the product still holds for the copy")}+ @Test func onlyTheCopyACasksPackagesWroteIsHomebrews() {+ let cask = HomebrewPackage(name: "example", kind: .cask, installedVersion: "1.0")+ .noting(packagedApps: ["/Applications/Example.app"])+ let brewed = app("Example", "org.example.app")+ let copy = InstalledApp(+ url: URL(filePath: "/Users/me/Applications/Example.app", directoryHint: .isDirectory),+ bundleIdentifier: "org.example.app",+ name: "Example"+ )++ #expect(CaskEvidence.installedCask(for: brewed, in: [cask]) != nil)+ #expect(CaskEvidence.installedCask(for: copy, in: [cask]) == nil, "a second copy was called Homebrew's")+ }+@Test func asksForNothingWhenThereIsNothingToAskAbout() async {#expect(await CaskEvidence.knownCasks(for: []).isEmpty)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PkgutilAnswer.swift b/Packages/PeelCore/Tests/PeelCoreTests/PkgutilAnswer.swiftindex 3930a206..d70d192b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PkgutilAnswer.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PkgutilAnswer.swift@@ -12,6 +12,11 @@ enum PkgutilAnswer {xml(["path": path, "path-info": packages.map { ["pkgid": $0] }] as [String: Any])}+ /// `pkgutil --pkg-info-plist <identifier>`: where the package installed what it lists.+ static func packageInfo(_ identifier: String, volume: String = "/", location: String) -> String {+ xml(["pkgid": identifier, "volume": volume, "install-location": location])+ }+private static func xml(_ plist: Any) -> String {let data = try! PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)return String(decoding: data, as: UTF8.self)