Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Never list what one of Apple's packages installed as an app's leftover

Țugui Dragoș1876c168791c
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
index 342ef3b7..312d6d62 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
@@ -5,11 +5,13 @@ public struct LeftoverScanner: Sendable {
typealias Measure = @Sendable (URL) async -> FolderContents?
/// Whether the guard refuses a path outright, whatever the rest of the scan makes of it.
typealias Refuses = @Sendable (_ path: String, _ home: String) -> Bool
+ typealias InstalledByApple = @Sendable (URL) async -> Bool
public let environment: SearchEnvironment
public let exclusions: Exclusions
private let measure: Measure
private let refuses: Refuses
+ private let installedByApple: InstalledByApple
/// The most folders listed per location while searching inside folders the app does not claim.
private let nestedFolderLimit: Int
@@ -25,12 +27,14 @@ public struct LeftoverScanner: Sendable {
exclusions: Exclusions = .none,
measure: @escaping Measure,
refuses: @escaping Refuses = { ProtectedData.refuses($0, home: $1) },
+ installedByApple: @escaping InstalledByApple = { await PackageReceipts.isInstalledByApple($0) },
nestedFolderLimit: Int = NestedSearch.folderLimit
) {
self.environment = environment
self.exclusions = exclusions
self.measure = measure
self.refuses = refuses
+ self.installedByApple = installedByApple
self.nestedFolderLimit = nestedFolderLimit
}
@@ -99,7 +103,8 @@ public struct LeftoverScanner: Sendable {
for location in environment.locations where location.kind != .safariWebApps || app.isASafariWebApp {
let home = environment.homeDirectory.path(percentEncoded: false)
let bundle = PathPattern.comparablePath(of: app.url)
- _ = group.addTaskUnlessCancelled { [exclusions, measure, refuses, nestedFolderLimit] in
+ _ = group.addTaskUnlessCancelled {
+ [exclusions, measure, refuses, installedByApple, nestedFolderLimit] in
(location, await Self.scan(
location,
matcher: matcher,
@@ -107,7 +112,9 @@ public struct LeftoverScanner: Sendable {
bundle: bundle,
exclusions: exclusions,
measure: measure,
- refuses: refuses, nestedFolderLimit: nestedFolderLimit
+ refuses: refuses,
+ installedByApple: installedByApple,
+ nestedFolderLimit: nestedFolderLimit
))
}
}
@@ -196,6 +203,7 @@ public struct LeftoverScanner: Sendable {
exclusions: Exclusions,
measure: @escaping Measure,
refuses: Refuses,
+ installedByApple: @escaping InstalledByApple,
nestedFolderLimit: Int
) async -> LocationResult {
let entries: [String]
@@ -234,10 +242,11 @@ public struct LeftoverScanner: Sendable {
}
}
- let leftovers = await measured(toMeasure, kind: location.kind, home: home, measure: measure)
+ let taken = await withoutWhatAppleInstalled(toMeasure, home: home, installedByApple: installedByApple)
+ let leftovers = await measured(taken, kind: location.kind, home: home, measure: measure)
let inside = await nested(
in: nobodysFolders, of: location, matcher: matcher, home: home, bundle: bundle, exclusions: exclusions,
- measure: measure, refuses: refuses, limit: nestedFolderLimit
+ measure: measure, refuses: refuses, installedByApple: installedByApple, limit: nestedFolderLimit
)
return .found(
leftovers + inside.found, cutShort: inside.wasCutShort ? location : nil,
@@ -256,6 +265,7 @@ public struct LeftoverScanner: Sendable {
exclusions: Exclusions,
measure: @escaping Measure,
refuses: Refuses,
+ installedByApple: @escaping InstalledByApple,
limit: Int
) async -> (found: [Leftover], wasCutShort: Bool, unreadable: [URL]) {
let kind = location.kind
@@ -280,10 +290,27 @@ public struct LeftoverScanner: Sendable {
guard canLookInside, url.isRealFolder, !refuses(path, home), !exclusions.excludes(url) else { return .pass }
return .lookInside
}
- let found = await measured(search.found, kind: kind, home: home, measure: measure)
+ let taken = await withoutWhatAppleInstalled(search.found, home: home, installedByApple: installedByApple)
+ let found = await measured(taken, kind: kind, home: home, measure: measure)
return (found, search.wasCutShort, search.unreadable)
}
+ /// What a search took, less what one of Apple's packages installed, which is Apple's whatever its name says. Only
+ /// what sits outside the home is asked, since Apple's receipts list nothing inside one.
+ private static func withoutWhatAppleInstalled(
+ _ found: [Found], home: String, installedByApple: @escaping InstalledByApple
+ ) async -> [Found] {
+ let homePath = PathPattern.comparablePath(of: URL(filePath: home, directoryHint: .isDirectory))
+ let outside = found.filter {
+ !PathComponents.isPath(PathPattern.comparablePath(of: $0.url), atOrInside: homePath)
+ }
+ guard !outside.isEmpty else { return found }
+ let apples = Set(await outside.concurrentMap(width: concurrentMeasurements) { item in
+ await installedByApple(item.url) ? item.url : nil
+ }.compactMap(\.self))
+ return found.filter { !apples.contains($0.url) }
+ }
+
/// Something a search took as the app's, waiting to be measured.
private struct Found: Sendable {
let url: URL
diff --git a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift
index edb6e480..116297c3 100644
--- a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift
@@ -200,10 +200,33 @@ public enum PackageReceipts {
/// Reads what `pkgutil --file-info-plist` prints: a `path-info` array with the `pkgid` of each package that
/// lists the path. Apple's own packages are left out.
static func packageIdentifiers(in answer: String?) -> [String] {
+ installers(in: answer).filter { !$0.hasPrefix("com.apple.") }
+ }
+
+ private static func installers(in answer: String?) -> [String] {
guard let answer,
let plist = try? PropertyListSerialization.propertyList(from: Data(answer.utf8), format: nil),
let packages = (plist as? [String: Any])?["path-info"] as? [[String: Any]] else { return [] }
- return packages.compactMap { $0["pkgid"] as? String }.filter { !$0.hasPrefix("com.apple.") }
+ return packages.compactMap { $0["pkgid"] as? String }
+ }
+
+ /// Whether one of Apple's packages installed `url`: a receipt of macOS or of one of Apple's tools lists it, and
+ /// that package installs at the root, the only place where the path a receipt lists is the path asked about.
+ @concurrent
+ public static func isInstalledByApple(_ url: URL) async -> Bool {
+ await isInstalledByApple(url, pkgutil: pkgutil)
+ }
+
+ static func isInstalledByApple(_ url: URL, pkgutil: Pkgutil) async -> Bool {
+ let path = PathPattern.comparablePath(of: PathPattern.canonical(url))
+ let apples = installers(in: await pkgutil(["--file-info-plist", path])).filter { $0.hasPrefix("com.apple.") }
+ for identifier in apples.sorted() where !Task.isCancelled {
+ guard let installLocation = await description(of: identifier, pkgutil: pkgutil)?.installLocation else {
+ continue
+ }
+ if PathPattern.comparablePath(of: installLocation) == "/" { return true }
+ }
+ return false
}
/// A receipt and the full paths of everything it lists, so `installs(_:)` can tell whether it installed a path.
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
index 70af7c54..6ac3d626 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
@@ -239,14 +239,18 @@ public struct Uninstallation: Sendable {
app: InstalledApp,
exclusions: Exclusions,
matcher: LeftoverMatcher,
- environment: SearchEnvironment
+ environment: SearchEnvironment,
+ installedByApple: @escaping @Sendable (URL) async -> Bool = { await PackageReceipts.isInstalledByApple($0) }
) async -> [Leftover] {
var leftovers: [Leftover] = []
// Compared by path: the app's URL ends in a slash and a cask's path does not, and many casks list the app
// among what they delete. What sits inside the bundle is skipped too: it goes with the app, and moved on
// its own it would be cut out of an app that stays.
let bundle = PathPattern.comparablePath(of: app.url)
+ let home = PathPattern.comparablePath(of: environment.homeDirectory)
for item in evidence.items where !exclusions.excludes(item.url) && !isAtOrInside(bundle, item.url) {
+ // What one of Apple's packages installed is Apple's, whatever a cask says.
+ if !isAtOrInside(home, item.url), await installedByApple(item.url) { continue }
let place = place(of: item.url, in: environment)
let own = matcher.match(fileName: item.url.lastPathComponent, kind: place.kind, at: item.url)
// Every folder on the way counts: a path inside a folder another app claims is not this app's alone.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift
index ca67fb5a..2e331ad9 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift
@@ -1,5 +1,6 @@
import Foundation
@testable import PeelCore
+import Synchronization
import Testing
struct CaskEvidenceTests {
@@ -242,6 +243,39 @@ struct CaskEvidenceTests {
#expect(leftovers.filter(\.match.isRecommended).count == 1)
}
+ @Test func leavesOutACaskPathApplesPackagesInstalled() async throws {
+ let directory = try TemporaryDirectory()
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+ let kit = try directory.directory("root/Library/Example Kit/Example")
+ let audio = try directory.directory("root/Library/Example Audio/Example")
+ try directory.directory("home/Library/Caches/com.example.app")
+ let cask = HomebrewPackage(name: "example", kind: .cask, appNames: ["Example.app"], leftoverPatterns: [
+ kit.path(percentEncoded: false), audio.path(percentEncoded: false), "~/Library/Caches/com.example.app",
+ ])
+ let app = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "com.example.app", name: "Example")
+ let evidence = try #require(CaskEvidence.evidence(for: app, casks: [cask], home: home))
+ let asked = Mutex(0)
+
+ let leftovers = await Uninstallation.caskLeftovers(
+ evidence,
+ app: app,
+ exclusions: .none,
+ matcher: LeftoverMatcher(app: app, installedApps: [app]),
+ environment: SearchEnvironment(
+ homeDirectory: home,
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ ),
+ installedByApple: { url in
+ asked.withLock { $0 += 1 }
+ return url.deletingLastPathComponent().lastPathComponent == "Example Kit"
+ }
+ )
+
+ let found = Set(leftovers.map { "\($0.url.deletingLastPathComponent().lastPathComponent)/\($0.url.lastPathComponent)" })
+ #expect(found == ["Example Audio/Example", "Caches/com.example.app"])
+ #expect(asked.withLock { $0 } == 2)
+ }
+
private func environment(_ home: URL) -> SearchEnvironment {
SearchEnvironment(homeDirectory: home, rootDirectory: home.appending(path: "root", directoryHint: .isDirectory))
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
index c7856e3e..1f9c91e6 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
@@ -1597,6 +1597,39 @@ struct LeftoverScannerTests {
#expect(found["home/Library/Example Audio/org.example.hexachord"]?.match.isRecommended == true)
}
+ @Test func neverTakesWhatApplesPackagesInstalled() async throws {
+ let directory = try TemporaryDirectory()
+ let app = InstalledApp(
+ url: URL(filePath: "/Applications/Hexachord.app"),
+ bundleIdentifier: "org.example.hexachord",
+ name: "Hexachord"
+ )
+ for path in [
+ "root/Library/Hexachord/state.db", "root/Library/Example Kit/Hexachord/frame.png",
+ "root/Library/Example Audio/Hexachord/samples.db", "home/Library/Example Kit/Hexachord/presets.db",
+ ] {
+ try directory.file(path, bytes: 64)
+ }
+ let root = directory.url.path(percentEncoded: false)
+ let apples: Set<String> = ["root/Library/Hexachord", "root/Library/Example Kit/Hexachord"]
+ let asked = Mutex<Set<String>>([])
+ let scanner = LeftoverScanner(
+ environment: environment(in: directory),
+ measure: LeftoverScanner.walk,
+ installedByApple: { url in
+ let path = String(url.path(percentEncoded: false).dropFirst(root.count))
+ asked.withLock { _ = $0.insert(path) }
+ return apples.contains(path)
+ }
+ )
+
+ let scan = await scanner.scan(app, installedApps: [app])
+
+ let found = Set(scan.leftovers.map { String($0.url.path(percentEncoded: false).dropFirst(root.count)) })
+ #expect(found == ["root/Library/Example Audio/Hexachord", "home/Library/Example Kit/Hexachord"])
+ #expect(asked.withLock { $0 } == apples.union(["root/Library/Example Audio/Hexachord"]))
+ }
+
@Test func findsTheFoldersOfEachReleaseInsideItsMakersFolder() async throws {
let directory = try TemporaryDirectory()
let app = InstalledApp(
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift
index 3b6c41c1..af264680 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift
@@ -515,4 +515,33 @@ struct PackageReceiptsTests {
#expect(try tool("linked").isLeftAlone == true, "a link that leads somewhere was offered")
#expect(try tool("gone").isLeftAlone == false)
}
+
+ @Test func knowsWhatApplesPackagesInstalledOnThisMac() async throws {
+ let directory = try TemporaryDirectory()
+ let applicationSupport = URL(filePath: "/Library/Application Support", directoryHint: .isDirectory)
+
+ #expect(await PackageReceipts.isInstalledByApple(applicationSupport))
+ #expect(await PackageReceipts.isInstalledByApple(directory.url) == false)
+ }
+
+ @Test func countsOnlyApplesPackagesThatInstallAtTheRoot() async {
+ func answering(location: String, package: String = "com.apple.pkg.Example") -> PackageReceipts.Pkgutil {
+ { arguments in
+ switch arguments.first {
+ case "--file-info-plist": PkgutilAnswer.fileInfo(arguments[1], packages: package)
+ case "--pkg-info-plist": PkgutilAnswer.packageInfo(package, location: location)
+ default: nil
+ }
+ }
+ }
+ let url = URL(filePath: "/Library/Example Kit/Example", directoryHint: .isDirectory)
+
+ #expect(await PackageReceipts.isInstalledByApple(url, pkgutil: answering(location: "/")))
+ #expect(await PackageReceipts.isInstalledByApple(url, pkgutil: answering(location: "")))
+ #expect(await PackageReceipts.isInstalledByApple(url, pkgutil: answering(location: "Library/Apple/")) == false)
+ #expect(
+ await PackageReceipts.isInstalledByApple(url, pkgutil: answering(location: "/", package: "org.example.pkg"))
+ == false
+ )
+ }
}