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.

Another copy of an app keeps the files it uses

Țugui Dragoș4a665336e639
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index eb41720f..bd4a198f 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -64,7 +64,8 @@ Take the most common case, uninstalling an app. Every other page follows the sam
2. **Match.** For each file, `LeftoverMatcher` weighs the evidence that it belongs to the app: its bundle
identifier, the identifiers of what the app embeds, its application groups, its signing team, its name. The
answer is a `LeftoverMatch`: a confidence (`certain`, `likely`, or `possible`), the reason, the other
- installed apps that claim the file too, and, when Peel holds it back, why (`HoldBack`).
+ installed apps that claim the file too, the other copies of the app that use it (any macOS knows, wherever
+ they are, named by their place), and, when Peel holds it back, why (`HoldBack`).
3. **Measure.** `FileSize` walks each folder on a thread of its own, with a time budget. A folder that doesn't
answer in time, or that macOS won't open, has an unknown size, never zero, and every list shows it that way.
4. **Plan.** The page shows every match with its reason. Only `certain` and `likely` matches that nothing else
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 02d58a71..4412cc37 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -48,10 +48,13 @@ manifest doesn't set it, so ask for it on the command line to hold the package t
swift build --package-path Packages/PeelCore -Xswiftc -warnings-as-errors
```
-Some tests read this Mac rather than a fixture, on purpose: an answer about Homebrew, launchd, or the disk is
-worth little against a mock. They are slower, and they depend on what you have installed. The slowest scans every
-app installed here, in full, to check that nothing Peel would select is refused or shared. It takes minutes, so it
-runs only when asked for, and it is worth running before a release:
+Tests run through the code Peel runs, on the Mac running them: a scan asks this Mac's Launch Services and reads its
+system apps and a real disk, since an answer about Homebrew, launchd, Launch Services, or the disk is worth little
+against a mock. A stand-in is only for what a Mac can't do on demand, such as a folder that never answers, and the
+files a test scans sit in a temporary home, never in yours. Some tests read this Mac on purpose, so they are slower
+and depend on what you have installed. The slowest scans every app installed here, in full, to check that nothing
+Peel would select is refused or shared. It takes minutes, so it runs only when asked for, and it is worth running
+before a release:
```bash
PEEL_TEST_THIS_MAC=1 swift test --package-path Packages/PeelCore --filter SuggestedSelectionOnThisMacTests
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
index 991dc0e7..08e5d530 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
@@ -151,8 +151,9 @@ struct LeftoversCommand: AsyncParsableCommand {
if let heldBack = leftover.match.heldBack {
summary += ", review: \(heldBack.summary)"
} else if !leftover.match.isRecommended {
+ let users = leftover.match.sharedWith + leftover.match.otherCopies.map(Output.path)
summary += leftover.match.isShared
- ? ", review: shared with \(leftover.match.sharedWith.joined(separator: ", "))"
+ ? ", review: shared with \(users.joined(separator: ", "))"
: ", review: \(leftover.match.confidence.summary) match"
}
if leftover.requiresPrivileges {
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Records.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Records.swift
index 14df4814..2eb41223 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Records.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Records.swift
@@ -45,6 +45,8 @@ struct LeftoverRecord: Encodable {
/// Why Peel left the item unselected on purpose, or `null` when it didn't.
let heldBack: String?
let sharedWith: [String]
+ /// Other copies of the app that use the item too, by their place, since they share its identifier.
+ let otherCopies: [String]
let isRecommended: Bool
let needsAdministrator: Bool
@@ -55,6 +57,7 @@ struct LeftoverRecord: Encodable {
confidence = leftover.match.confidence.summary
heldBack = leftover.match.heldBack?.rawValue
sharedWith = leftover.match.sharedWith
+ otherCopies = leftover.match.otherCopies.map(Output.path)
isRecommended = leftover.match.isRecommended
needsAdministrator = leftover.requiresPrivileges
}
@@ -66,6 +69,7 @@ struct LeftoverRecord: Encodable {
case confidence
case heldBack
case sharedWith
+ case otherCopies
case isRecommended
case needsAdministrator
}
@@ -79,6 +83,7 @@ struct LeftoverRecord: Encodable {
try container.encode(confidence, forKey: .confidence)
try container.encode(heldBack, forKey: .heldBack)
try container.encode(sharedWith, forKey: .sharedWith)
+ try container.encode(otherCopies, forKey: .otherCopies)
try container.encode(isRecommended, forKey: .isRecommended)
try container.encode(needsAdministrator, forKey: .needsAdministrator)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift
index 17263fb1..54ba5e0c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift
@@ -8,7 +8,13 @@ public enum AppInspector {
/// Where macOS thinks an app is, including folders Peel doesn't scan, such as a build folder.
/// A copy in the Trash doesn't count as installed.
public static func applicationURL(forBundleIdentifier identifier: String) -> URL? {
- NSWorkspace.shared.urlsForApplications(withBundleIdentifier: identifier).first { url in
+ applicationURLs(forBundleIdentifier: identifier).first
+ }
+
+ /// Every copy of the app with `identifier` that macOS knows, wherever it is, best first. A copy in the Trash
+ /// doesn't count as installed.
+ static func applicationURLs(forBundleIdentifier identifier: String) -> [URL] {
+ NSWorkspace.shared.urlsForApplications(withBundleIdentifier: identifier).filter { url in
let path = url.path(percentEncoded: false)
return !path.contains("/.Trash/") && !path.contains("/.Trashes/") && FileManager.default.fileExists(atPath: path)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
index ecf37bc1..c03a9827 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
@@ -72,21 +72,32 @@ public struct LeftoverMatch: Sendable, Hashable {
public let confidence: MatchConfidence
/// Bundle identifiers of other installed apps that match the item equally well.
public let sharedWith: [String]
+ /// Other copies of the app, wherever they are, that use the item too. They share its identifier, so each is
+ /// known by its place.
+ public let otherCopies: [URL]
/// The reason the item was left unselected on purpose, if it was.
public var heldBack: HoldBack?
/// True when `reason` is an identifier that is a single word, such as `notes`. A bundle writes its own
/// identifier, so such a claim says no more than a name.
public let isAWord: Bool
- public init(reason: MatchReason, confidence: MatchConfidence, sharedWith: [String], heldBack: HoldBack? = nil, isAWord: Bool = false) {
+ public init(
+ reason: MatchReason,
+ confidence: MatchConfidence,
+ sharedWith: [String],
+ otherCopies: [URL] = [],
+ heldBack: HoldBack? = nil,
+ isAWord: Bool = false
+ ) {
self.reason = reason
self.confidence = confidence
self.sharedWith = sharedWith
+ self.otherCopies = Set(otherCopies).sorted { $0.path(percentEncoded: false) < $1.path(percentEncoded: false) }
self.heldBack = heldBack
self.isAWord = isAWord
}
- public var isShared: Bool { !sharedWith.isEmpty }
+ public var isShared: Bool { !sharedWith.isEmpty || !otherCopies.isEmpty }
/// True when the claim is the app's name, or an identifier that is only a word.
public var restsOnAName: Bool { reason == .name || isAWord }
@@ -99,7 +110,7 @@ public struct LeftoverMatch: Sendable, Hashable {
/// Returns the same match, held back for `heldBack`: shown, but never selected.
public func forReview(_ heldBack: HoldBack) -> LeftoverMatch {
- LeftoverMatch(reason: reason, confidence: confidence, sharedWith: sharedWith, heldBack: heldBack, isAWord: isAWord)
+ LeftoverMatch(reason: reason, confidence: confidence, sharedWith: sharedWith, otherCopies: otherCopies, heldBack: heldBack, isAWord: isAWord)
}
/// Combines two apps' claims on one item, cautiously and the same in either order: the weaker claim counts,
@@ -116,6 +127,7 @@ public struct LeftoverMatch: Sendable, Hashable {
reason: weaker.reason,
confidence: weaker.confidence,
sharedWith: Set(sharedWith).union(other.sharedWith).sorted(),
+ otherCopies: otherCopies + other.otherCopies,
heldBack: heldBack,
isAWord: isAWord || other.isAWord
)
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift
index 6a03ec28..49783c9d 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift
@@ -39,22 +39,30 @@ struct LeftoverMatcher: Sendable {
guard let evidence = target.evidence(for: candidate) else { return nil }
var sharedWith: Set<String> = []
+ var otherCopies: [URL] = []
+ func share(with other: Profile) {
+ if other.identifier == target.identifier {
+ otherCopies.append(other.url)
+ } else {
+ sharedWith.insert(other.bundleIdentifier)
+ }
+ }
for other in others {
guard let rival = other.evidence(for: candidate) else {
// Siblings from the same maker, like Firefox Nightly beside Firefox, use the same files.
if target.isSibling(of: other), other.sharesName(with: candidate) {
- sharedWith.insert(other.bundleIdentifier)
+ share(with: other)
}
continue
}
// A likely claim by name against one by identifier: neither wins, whatever their ranks, and the item
// is shared. Otherwise the stronger claim wins, as with Chrome and Chrome Canary, and equal ones share.
if rival.family != evidence.family, rival.confidence >= .likely, evidence.confidence >= .likely {
- sharedWith.insert(other.bundleIdentifier)
+ share(with: other)
} else if rival.rank > evidence.rank {
return nil
} else if rival.rank == evidence.rank {
- sharedWith.insert(other.bundleIdentifier)
+ share(with: other)
}
}
if evidence.reason == .bundleIdentifierPrefix {
@@ -64,6 +72,7 @@ struct LeftoverMatcher: Sendable {
reason: evidence.reason,
confidence: evidence.confidence,
sharedWith: sharedWith.sorted(),
+ otherCopies: otherCopies,
isAWord: evidence.isAWord
)
}
@@ -84,11 +93,16 @@ struct LeftoverMatcher: Sendable {
}
}
- /// Bundle identifiers of the other installed apps with any claim on `fileName`. A path a Homebrew cask names
- /// is checked this way too, so one shared with another app is never selected for this app.
- func othersClaiming(fileName: String, kind: SearchLocation.Kind) -> [String] {
+ /// The other installed apps with any claim on `fileName`, by bundle identifier, and the other copies of this app
+ /// with one. A path a Homebrew cask names is checked this way too, so one shared with another app or another
+ /// copy is never selected for this app.
+ func othersClaiming(fileName: String, kind: SearchLocation.Kind) -> (apps: [String], copies: [URL]) {
let candidate = Candidate(Self.key(from: fileName, kind: kind))
- return others.filter { $0.evidence(for: candidate) != nil }.map(\.bundleIdentifier).sorted()
+ let claiming = others.filter { $0.evidence(for: candidate) != nil }
+ return (
+ claiming.filter { $0.identifier != target.identifier }.map(\.bundleIdentifier).sorted(),
+ claiming.filter { $0.identifier == target.identifier }.map(\.url)
+ )
}
static func key(from fileName: String, kind: SearchLocation.Kind) -> String {
@@ -213,6 +227,7 @@ extension LeftoverMatcher {
/// The team Apple signs some of its own apps with, Xcode among them.
static let appleTeam = "59gab85efg."
+ let url: URL
let bundleIdentifier: String
let identifier: String
let embeddedIdentifiers: [EmbeddedIdentifier]
@@ -225,6 +240,7 @@ extension LeftoverMatcher {
let isApplesOwn: Bool
init(_ app: InstalledApp) {
+ url = app.url
bundleIdentifier = app.bundleIdentifier
identifier = app.bundleIdentifier.lowercased()
let vendor = Identifier.vendor(of: identifier)
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
index 61550cf1..ed3dd074 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
@@ -10,43 +10,55 @@ public struct LeftoverScanner: Sendable {
public let exclusions: Exclusions
private let measure: Measure
private let refuses: Refuses
- private let registeredApp: LeftoverMatcher.RegisteredApp
/// The most folders listed per location while searching inside folders the app does not claim. The default
/// is far more than a busy Application Support or Caches folder needs, and each listing is cheap.
private let nestedFolderLimit: Int
public init(environment: SearchEnvironment = .current, exclusions: Exclusions = .none) {
- self.init(environment: environment, exclusions: exclusions, measure: Self.walk, registeredApp: AppInspector.applicationURL(forBundleIdentifier:))
+ self.init(environment: environment, exclusions: exclusions, measure: Self.walk)
}
static let walk: Measure = { await FileSize.contents(of: $0) }
- /// For tests, which say how each folder answers and can count what the guard is asked. They leave out Launch
- /// Services, whose answers depend on what is installed on the Mac running them.
+ /// For tests, which say how each folder answers and can count what the guard is asked.
init(
environment: SearchEnvironment,
exclusions: Exclusions = .none,
measure: @escaping Measure,
refuses: @escaping Refuses = { ProtectedData.refuses($0, home: $1) },
- registeredApp: @escaping LeftoverMatcher.RegisteredApp = { _ in nil },
nestedFolderLimit: Int = 5_000
) {
self.environment = environment
self.exclusions = exclusions
self.measure = measure
self.refuses = refuses
- self.registeredApp = registeredApp
self.nestedFolderLimit = nestedFolderLimit
}
/// Finds the files `app` keeps outside its bundle. `installedApps` should hold every app on the Mac, so files
- /// other apps use are marked as shared. The apps macOS ships are added as rivals too: Apple keeps folders
- /// under their names (`Application Support/Music`) that an app of the same name would otherwise get outright.
+ /// other apps use are marked as shared.
@concurrent
public func scan(_ app: InstalledApp, installedApps: [InstalledApp]) async -> LeftoverScan {
- let systemApps = await AppCatalog.systemApps.value
- let matcher = LeftoverMatcher(app: app, installedApps: installedApps + systemApps, registeredApp: registeredApp)
+ await scan(app, matcher: matcher(for: app, installedApps: installedApps))
+ }
+ /// What tells `app`'s files from those of every other app. The apps macOS ships are rivals too: Apple keeps
+ /// folders under their names (`Application Support/Music`) that an app of the same name would otherwise get
+ /// outright. So is every other copy of the app macOS knows, such as an older one kept in Downloads or one on
+ /// another disk, since it carries the app's identifier and uses the same files.
+ func matcher(for app: InstalledApp, installedApps: [InstalledApp]) async -> LeftoverMatcher {
+ let known = installedApps + (await AppCatalog.systemApps.value)
+ let bundle = PathPattern.comparablePath(of: PathPattern.canonical(app.url))
+ let listed = Set(known.filter { $0.bundleIdentifier == app.bundleIdentifier }.map { PathPattern.comparablePath(of: PathPattern.canonical($0.url)) })
+ let elsewhere = AppInspector.applicationURLs(forBundleIdentifier: app.bundleIdentifier).filter { url in
+ let path = PathPattern.comparablePath(of: PathPattern.canonical(url))
+ return !listed.contains(path) && !PathComponents.isPath(path, atOrInside: bundle)
+ }
+ return LeftoverMatcher(app: app, installedApps: known + elsewhere.compactMap(AppInspector.inspect))
+ }
+
+ @concurrent
+ func scan(_ app: InstalledApp, matcher: LeftoverMatcher) async -> LeftoverScan {
let results = await withTaskGroup(of: (location: SearchLocation, result: LocationResult).self) { group in
for location in environment.locations {
let home = environment.homeDirectory.path(percentEncoded: false)
@@ -306,9 +318,10 @@ public struct LeftoverScanner: Sendable {
}
/// True for a folder another installed app claims, or one Apple named for itself. A name found inside it
- /// is only a guess: `Caches/com.apple.python/Library/Developer` is not the Developer app's.
+ /// is only a guess: `Caches/com.apple.python/Library/Developer` is not the Developer app's. Another copy of
+ /// the app is no one else.
private static func isSomebodyElses(_ name: String, kind: SearchLocation.Kind, matcher: LeftoverMatcher) -> Bool {
- ProtectedData.isApplesName(name) || !matcher.othersClaiming(fileName: name, kind: kind).isEmpty
+ ProtectedData.isApplesName(name) || !matcher.othersClaiming(fileName: name, kind: kind).apps.isEmpty
}
/// A job that runs a program inside the app is that app's, whatever it is called: `com.maker.updater.plist`
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift b/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift
index ef529b83..7dafc9d9 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift
@@ -126,8 +126,9 @@ public struct AppReset: Sendable {
// reset is for.
let usable = scan.leftovers.filter { leftover in
// Only `certain`, never `likely`: a reset ends in `defaults delete`, and a display name or an unlisted
- // prefix may also belong to something else (an app called Yarn, and the Yarn command-line tool).
- let isCertainlyTheApps = leftover.match.confidence == .certain && !leftover.match.isShared
+ // prefix may also belong to something else (an app called Yarn, and the Yarn command-line tool). Another
+ // copy of the app shares its settings, and a reset waits for every copy to quit.
+ let isCertainlyTheApps = leftover.match.confidence == .certain && leftover.match.sharedWith.isEmpty
let isOffered = leftover.match.heldBack == nil
|| (leftover.kind == .containers && [.holdsDocuments, .holdsKeys].contains(leftover.match.heldBack))
return isCertainlyTheApps && isOffered && !leftover.requiresPrivileges
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
index 5317331f..68482559 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
@@ -13,6 +13,8 @@ public struct BulkUninstallation: Sendable {
public let match: LeftoverMatch?
/// The bundle identifiers of apps outside the selection that also claim this item.
public let sharedWithOthers: [String]
+ /// Other copies of a chosen app, not chosen themselves, that use this item too.
+ public var otherCopies: [URL] = []
/// An excluded app, or an item with something excluded inside. Shown, never selected, never moved.
public var isExcluded = false
/// An app macOS protects, or an item found for one. The app stays, so none of it is a leftover to select.
@@ -29,7 +31,7 @@ public struct BulkUninstallation: Sendable {
public var isRecommended: Bool {
guard !isExcluded, !isPeels, !isKeptByMacOS, !isBeyondTheHelper else { return false }
guard let match else { return true }
- return sharedWithOthers.isEmpty && match.confidence >= .likely && match.heldBack == nil
+ return sharedWithOthers.isEmpty && otherCopies.isEmpty && match.confidence >= .likely && match.heldBack == nil
}
}
@@ -114,6 +116,7 @@ public struct BulkUninstallation: Sendable {
static func merge(_ uninstallations: [Uninstallation]) -> [Item] {
let chosen = Set(uninstallations.map(\.app.bundleIdentifier))
+ let chosenBundles = Set(uninstallations.map { PathPattern.comparablePath(of: $0.app.url) })
var byURL: [URL: Item] = [:]
var order: [URL] = []
@@ -127,6 +130,7 @@ public struct BulkUninstallation: Sendable {
apps: existing.apps + item.apps.filter { !existing.apps.contains($0) },
match: existing.match.flatMap { known in item.match.map(known.combined) } ?? existing.match ?? item.match,
sharedWithOthers: existing.sharedWithOthers.filter(item.sharedWithOthers.contains),
+ otherCopies: existing.otherCopies + item.otherCopies.filter { !existing.otherCopies.contains($0) },
isExcluded: existing.isExcluded || item.isExcluded,
isKeptByMacOS: existing.isKeptByMacOS || item.isKeptByMacOS,
isMeasured: existing.isMeasured || item.isMeasured,
@@ -150,6 +154,7 @@ public struct BulkUninstallation: Sendable {
apps: [identifier],
match: leftover.match,
sharedWithOthers: leftover.match.sharedWith.filter { !chosen.contains($0) },
+ otherCopies: leftover.match.otherCopies.filter { !chosenBundles.contains(PathPattern.comparablePath(of: $0)) },
isExcluded: leftover.match.heldBack == .holdsAnExclusion,
isKeptByMacOS: uninstallation.app.isSystemProtected,
isMeasured: leftover.isMeasured,
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
index b15e3e32..cc5d84b2 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
@@ -38,10 +38,10 @@ public struct Uninstallation: Sendable {
isAppMeasured: await bundle.map { !$0.couldNotBeRead } ?? false
)
}
- var scan = await LeftoverScanner(environment: environment, exclusions: exclusions).scan(app, installedApps: installedApps)
+ let scanner = LeftoverScanner(environment: environment, exclusions: exclusions)
+ let matcher = await scanner.matcher(for: app, installedApps: installedApps)
+ var scan = await scanner.scan(app, matcher: matcher)
if let evidence = CaskEvidence.evidence(for: app, casks: casks, home: environment.homeDirectory) {
- // The same rival apps the scanner used, including the apps that come with macOS.
- let matcher = LeftoverMatcher(app: app, installedApps: installedApps + (await AppCatalog.systemApps.value))
scan = scan.adding(await caskLeftovers(evidence, app: app, exclusions: exclusions, matcher: matcher, environment: environment))
}
scan = scan.adding(await receiptLeftovers(for: app, receipts: receipts, exclusions: exclusions, environment: environment))
@@ -103,14 +103,15 @@ public struct Uninstallation: Sendable {
let place = place(of: item.url, in: environment)
let own = matcher.match(fileName: item.url.lastPathComponent, kind: place.kind)
// Every folder on the way counts: a path inside a folder another app claims is not this app's alone.
- let rivals = Set(place.components.flatMap { matcher.othersClaiming(fileName: $0, kind: place.kind) })
+ let claims = place.components.map { matcher.othersClaiming(fileName: $0, kind: place.kind) }
let leftover = await LeftoverScanner.leftover(
at: item.url,
kind: place.kind,
match: LeftoverMatch(
reason: .homebrewCask,
confidence: item.isInLibrary && own != nil ? .likely : .possible,
- sharedWith: rivals.union(own?.sharedWith ?? []).sorted()
+ sharedWith: Set(claims.flatMap(\.apps)).union(own?.sharedWith ?? []).sorted(),
+ otherCopies: claims.flatMap(\.copies) + (own?.otherCopies ?? [])
),
parent: ParentAccess(item.url.deletingLastPathComponent()),
home: environment.homeDirectory.path(percentEncoded: false)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift
index 0458d406..cf2655b3 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift
@@ -100,6 +100,18 @@ struct AppResetTests {
#expect(reset.items.isEmpty)
}
+ /// Every copy of an app writes the same settings, and a reset quits them all first, so another copy keeps
+ /// nothing out of it. Another app's claim does.
+ @Test func anotherCopyOfTheAppKeepsNothingOutOfAReset() async throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("Library/Preferences/com.example.app.plist", bytes: 4096)
+ let copy = app(at: "/Users/x/Downloads/Example.app")
+
+ let reset = await AppReset.prepare(app(), installedApps: [app(), copy], environment: home(directory))
+
+ #expect(reset.items.map(\.kind) == [.preferences])
+ }
+
/// A container holds settings next to the user's documents, so it is opened up rather than offered whole.
@Test func opensAContainerUpAndLeavesTheUsersWorkInsideItAlone() async throws {
let directory = try TemporaryDirectory()
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift
index b172787b..de7c86db 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift
@@ -73,6 +73,25 @@ struct BulkUninstallationTests {
#expect(bulk.files(of: mail.bundleIdentifier) == [shared.url])
}
+ /// Two copies of one app share its files. Choosing one of them among several apps leaves what the other copy
+ /// uses unselected, since that copy stays; choosing both lets it go.
+ @Test func aCopyThatIsNotChosenKeepsTheFilesItUses() throws {
+ let notes = app("com.example.notes", "Notes")
+ let copy = InstalledApp(url: URL(filePath: "/Users/x/Applications/Notes.app"), bundleIdentifier: notes.bundleIdentifier, name: notes.name)
+ let mail = app("com.example.mail", "Mail")
+ let matcher = LeftoverMatcher(app: notes, installedApps: [notes, copy, mail])
+ let match = try #require(matcher.match(fileName: "com.example.notes.plist", kind: .preferences))
+ let preferences = Leftover(
+ url: URL(filePath: "/Users/x/Library/Preferences/com.example.notes.plist"),
+ kind: .preferences, match: match, size: 100, isMeasured: true, requiresPrivileges: false
+ )
+ 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])])
+ #expect(bothCopies.suggestedSelection(canUseHelper: true).contains(preferences.url))
+ }
+
/// A batch keeps the order an app's own page keeps: what could not be measured first among the leftovers, since
/// it is most likely the biggest, then the largest. The apps come after their leftovers.
@Test func listsWhatCouldNotBeMeasuredFirst() {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
index 78716166..87fcfce3 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
@@ -211,6 +211,18 @@ struct CommandLineTests {
#expect(Set(records[0].keys) == Set(records[1].keys))
}
+ /// 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 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 json = try Output.jsonText([LeftoverRecord(leftover)])
+ let records = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]])
+ #expect(records[0]["otherCopies"] as? [String] == ["/Volumes/Disk/Editor.app"])
+ #expect(records[0]["isRecommended"] as? Bool == false)
+ }
+
/// `peel leftovers --json` names the folders macOS kept Peel out of, where the app may have left more.
@Test func theLeftoversReportSaysWhereItCouldNotLook() throws {
let app = InstalledApp(url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.editor", name: "Editor")
@@ -632,8 +644,8 @@ 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] = [], heldBack: HoldBack? = nil) -> String {
- var match = LeftoverMatch(reason: .bundleIdentifier, confidence: confidence, sharedWith: sharedWith)
+ 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))
}
@@ -641,6 +653,8 @@ struct CommandLineTests {
#expect(row(.certain) == "bundle identifier")
#expect(row(.certain, heldBack: .holdsRepository) == "bundle identifier, review: holds a repository")
#expect(row(.certain, sharedWith: ["com.acme.other"]) == "bundle identifier, review: shared with com.acme.other")
+ #expect(row(.certain, otherCopies: [URL(filePath: "/Volumes/Disk/Editor.app")])
+ == "bundle identifier, review: shared with /Volumes/Disk/Editor.app")
#expect(row(.possible) == "bundle identifier, review: possible match")
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift
index 35a1e759..b3d0c9f4 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift
@@ -51,6 +51,21 @@ struct LeftoverMatcherTests {
#expect(try #require(match("com.google.Chrome.helper", in: .caches, for: chrome)).isRecommended)
}
+ /// Another copy of the app uses the same files wherever it is, so a file both claim is shared with that copy,
+ /// known by its place, since the identifier cannot tell the two apart. What only this copy embeds stays its own.
+ @Test func anotherCopyOfTheAppSharesWhatItUsesAndNothingMore() throws {
+ let sample = app("org.example.Sample", name: "Sample", embedded: ["org.example.Sample.Updater"])
+ let older = InstalledApp(url: URL(filePath: "/Volumes/Disk/Sample.app"), bundleIdentifier: sample.bundleIdentifier, name: "Sample")
+
+ let preferences = try #require(match("org.example.Sample.plist", in: .preferences, for: sample, with: [older]))
+ #expect(preferences.sharedWith.isEmpty)
+ #expect(preferences.otherCopies == [older.url])
+ #expect(!preferences.isRecommended)
+ let updater = try #require(match("org.example.Sample.Updater", in: .caches, for: sample, with: [older]))
+ #expect(updater.otherCopies.isEmpty)
+ #expect(updater.isRecommended)
+ }
+
@Test(arguments: [
("com.spotify.client.plist", SearchLocation.Kind.preferences),
("COM.SPOTIFY.CLIENT", .caches),
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
index e87f80ff..8df5ba81 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
@@ -66,6 +66,31 @@ struct LeftoverScannerTests {
)
}
+ /// Another copy of an app that macOS knows outside the Applications folders uses the same files. Every Mac has one
+ /// of the character palette in its input methods folder, so a copy of it in Applications shares its settings, and
+ /// that copy is counted once when the list of apps holds it too.
+ @Test func aCopyMacOSKnowsElsewhereSharesTheAppsFiles() async throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("home/Library/Preferences/com.apple.CharacterPaletteIM.plist", bytes: 4096)
+ let elsewhere = URL(filePath: "/System/Library/Input Methods/CharacterPalette.app")
+ // Only an app Apple signed can claim Apple's files, and this copy stands in for one.
+ let palette = InstalledApp(
+ url: URL(filePath: "/Applications/CharacterPalette.app"),
+ bundleIdentifier: "com.apple.CharacterPaletteIM",
+ name: "Character Palette",
+ teamIdentifier: "59GAB85EFG"
+ )
+ 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.isRecommended)
+ }
+ }
+
/// The guard, which reads every spelling of a path from the disk, is asked only about what the scan would take
/// or walk into, and what it refuses stays out.
@Test func asksTheGuardOnlyAboutWhatItWouldTakeOrWalkInto() async throws {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
index 16dd8f30..c230ee81 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
@@ -444,13 +444,15 @@ struct SuggestedSelectionOnThisMacTests {
}
}
- /// The other half of the same rule: nothing shared with another installed app is ever selected.
+ /// The other half of the same rule: nothing shared with another installed app, or another copy of the app, is
+ /// ever selected.
@Test func nothingSharedWithAnotherAppIsSelected() async {
for uninstallation in await Self.uninstallations.value {
let app = uninstallation.app
let suggested = uninstallation.suggestedSelection(canUseHelper: true)
for leftover in uninstallation.scan.leftovers where suggested.contains(leftover.url) {
- #expect(!leftover.match.isShared, "\(app.name): \(leftover.url.lastPathComponent) is shared with \(leftover.match.sharedWith)")
+ 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/Peel/Views/AppDetailView.swift b/Peel/Views/AppDetailView.swift
index 11011b0a..965c16d6 100644
--- a/Peel/Views/AppDetailView.swift
+++ b/Peel/Views/AppDetailView.swift
@@ -545,8 +545,9 @@ struct AppDetailView: View {
private func warning(for leftover: Leftover) -> String? {
var lines: [String] = []
if leftover.match.isShared {
- let names = leftover.match.sharedWith.map(library.name(forBundleIdentifier:)).formatted(.list(type: .and))
- lines.append(String(localized: "Also used by \(names)"))
+ let users = leftover.match.sharedWith.map(library.name(forBundleIdentifier:))
+ + leftover.match.otherCopies.map(\.abbreviatedPath)
+ lines.append(String(localized: "Also used by \(users.formatted(.list(type: .and)))"))
}
if let heldBack = leftover.match.heldBack {
lines.append(String(localized: heldBack.explanation))
diff --git a/Peel/Views/MultipleAppsView.swift b/Peel/Views/MultipleAppsView.swift
index e2ed8f28..9753cbab 100644
--- a/Peel/Views/MultipleAppsView.swift
+++ b/Peel/Views/MultipleAppsView.swift
@@ -194,8 +194,9 @@ struct MultipleAppsView: View {
if !item.isApplication, !keptBy.isEmpty, !item.isKeptByMacOS, !item.isPeels, !item.isExcluded {
lines.append(String(localized: "Not selected: it stays with \(names(of: keptBy))."))
}
- if !item.sharedWithOthers.isEmpty {
- lines.append(String(localized: "Also used by \(names(of: item.sharedWithOthers))"))
+ let users = item.sharedWithOthers.map(library.name(forBundleIdentifier:)) + item.otherCopies.map(\.abbreviatedPath)
+ if !users.isEmpty {
+ lines.append(String(localized: "Also used by \(users.formatted(.list(type: .and)))"))
}
if let heldBack = item.match?.heldBack {
lines.append(String(localized: heldBack.explanation))
diff --git a/SAFETY.md b/SAFETY.md
index b7fec8f2..6a5c6d42 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -130,13 +130,14 @@ root of another disk), asked of the folder itself with every link resolved: a fo
## What is selected for you
Only matches Peel is `certain` or `likely` about, and only when nothing else installed on the Mac uses them.
-Anything shared with another app is shown and left unselected. Something matched by the app's name alone inside
-another app's folder, or one of Apple's, is shown and never selected, since it is most likely that app's data about
-this one; so is something matched by name alone at the top of your home folder or of a Library, where a name is
-only a guess. And nothing at all is selected for an app that would stay: one macOS keeps, one the helper may not
-move, or one that needs the helper while it cannot act. When you remove several apps at once and deselect one of
-them, it stays too: its files leave the selection, those it shares with the other apps included, and selecting it
-again brings them back.
+Anything shared with another app is shown and left unselected, and so is what another copy of the app uses: one
+macOS knows anywhere, such as an older copy in Downloads or one on another disk, is named by where it is. Something
+matched by the app's name alone inside another app's folder, or one of Apple's, is shown and never selected, since
+it is most likely that app's data about this one; so is something matched by name alone at the top of your home
+folder or of a Library, where a name is only a guess. And nothing at all is selected for an app that would stay: one
+macOS keeps, one the helper may not move, or one that needs the helper while it cannot act. When you remove several
+apps at once and deselect one of them, it stays too: its files leave the selection, those it shares with the other
+apps included, and selecting it again brings them back.
Peel itself is listed on its own page with what it keeps, and nothing of it can be selected there or among other
apps. It is removed only by Remove Peel, in Settings, which takes its helper and login item away first.