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
Move a maker's folder an uninstall leaves empty
Țugui Dragoș7600bd21b1c9
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swiftindex 26f4864f..169e040c 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift@@ -21,6 +21,7 @@ struct UninstallPlan {/// a reason other than the app's own uninstaller, which removes what it holds back.let needsReview: Intvar uninstallsItself = false+ var makersFolderNames: Set<String> = []var moving: [Item] { items.filter { $0.refusal == nil } }var staying: [Item] { items.filter { $0.refusal != nil } }@@ -59,7 +60,8 @@ struct UninstallPlan {items: items,needsAdministrator: rest.count(where: { $0.match.isRecommended && $0.requiresPrivileges }),needsReview: rest.count(where: { !$0.match.isRecommended && $0.match.heldBack != .leftToItsUninstaller }),- uninstallsItself: uninstallation.uninstallsItself != nil+ uninstallsItself: uninstallation.uninstallsItself != nil,+ makersFolderNames: uninstallation.makersFolderNames)}@@ -72,9 +74,10 @@ struct UninstallPlan {in log: RemovalLog = RemovalLog(),refusals: RefusalLog = RefusalLog()) async -> Bool {- let refused = staying.compactMap { item in item.refusal.map { TrashFailure(url: item.url, reason: $0) } }+ var result = result+ result.failures += staying.compactMap { item in item.refusal.map { TrashFailure(url: item.url, reason: $0) } }return await Removals.record(- TrashResult(trashed: result.trashed, failures: result.failures + refused),+ result,from: source,sizes: [URL: Int64](measured: items.map { ($0.url, $0.size) }),tool: "applications",@@ -93,7 +96,8 @@ struct UninstallPlan {apps: [app],thenFiles: { stayed in stayed.isEmpty ? files : [] },usingHelperFor: [],- lettingTheirProgramsRun: uninstallsItself ? [app] : []+ lettingTheirProgramsRun: uninstallsItself ? [app] : [],+ emptiedFoldersNamed: makersFolderNames)}}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swiftindex d94e303c..6ae7aab2 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift@@ -176,7 +176,8 @@ public struct BulkUninstallation: Sendable {return order.filter { !apps.contains($0) && !(owners[$0] ?? []).contains(where: kept.contains) }},usingHelperFor: privilegedURLs,- lettingTheirProgramsRun: Set(uninstallations.filter { $0.uninstallsItself != nil }.map(\.app.url))+ lettingTheirProgramsRun: Set(uninstallations.filter { $0.uninstallsItself != nil }.map(\.app.url)),+ emptiedFoldersNamed: MakersFolders.names(of: uninstallations.map(\.app)))}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/MakersFolders.swift b/Packages/PeelCore/Sources/PeelCore/Removal/MakersFolders.swiftnew file mode 100644index 00000000..b2e088ba--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Removal/MakersFolders.swift@@ -0,0 +1,51 @@+import Darwin+import Foundation+internal import PeelPrivileged++/// The folders of the apps or their makers between a file an uninstall moved and its Library location, such as+/// `Application Support/MediaHuman`.+struct MakersFolders {+ /// Never the home folder's own top or `/Users/Shared`, which every account uses.+ static let kinds: Set<SearchLocation.Kind> = [.applicationSupport, .caches, .logs, .plugIns, .library]++ let environment: SearchEnvironment+ /// Lowercased, since disks ignore case by default.+ let names: Set<String>++ /// Each app's identifier and name, its maker's part of the identifier, and that part's last name. Never Apple's.+ static func names(of apps: [InstalledApp]) -> Set<String> {+ Set(apps.flatMap { app -> [String] in+ guard !ProtectedData.isApplesName(app.bundleIdentifier) else { return [] }+ let maker = Identifier.vendor(of: app.bundleIdentifier)+ return [app.bundleIdentifier, app.name, maker, maker?.split(separator: ".").last.map(String.init)]+ .compactMap { $0?.lowercased() }+ })+ }++ /// Deepest first. A folder with another name stops the walk, since it may be any app's.+ func above(_ moved: [URL]) -> [URL] {+ let locations = environment.locations+ let ends = Set(locations.map { PathPattern.comparablePath(of: $0.url) })+ let places = locations.filter { Self.kinds.contains($0.kind) }.map { PathPattern.comparablePath(of: $0.url) }+ var folders: [String: URL] = [:]+ for url in moved {+ var folder = url.deletingLastPathComponent()+ var path = PathPattern.comparablePath(of: folder)+ while !ends.contains(path), places.contains(where: { PathComponents.isPath(path, inside: $0) }),+ names.contains(folder.lastPathComponent.lowercased()) {+ folders[path] = folder+ folder = folder.deletingLastPathComponent()+ path = PathPattern.comparablePath(of: folder)+ }+ }+ return folders.sorted { PathComponents.of($0.key).count > PathComponents.of($1.key).count }.map(\.value)+ }++ /// Read without the trailing slash, which would follow a link.+ static func isEmpty(_ folder: URL) -> Bool {+ let path = PathPattern.comparablePath(of: folder)+ var info = stat()+ guard lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR else { return false }+ return (try? FileManager.default.contentsOfDirectory(atPath: path))?.isEmpty == true+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swiftindex ca9c192f..6e9ee984 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift@@ -99,7 +99,7 @@ extension RemovalPart {RemovalRecord(batch: batch,item: $0,- size: sizes[$0.originalURL],+ size: sizes[$0.originalURL] ?? (result.emptied.contains($0.originalURL) ? 0 : nil),source: source,sourceKey: sourceKey,tool: tooldiff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex 1a0af0ee..552392e9 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -169,6 +169,8 @@ public enum RestoreFailure: Sendable, Hashable {public struct TrashResult: Sendable {public var trashed: [TrashedItem] = []public var failures: [TrashFailure] = []+ /// The folders an uninstall left empty and moved too, which free nothing.+ public internal(set) var emptied: Set<URL> = []public init(trashed: [TrashedItem] = [], failures: [TrashFailure] = []) {self.trashed = trashed@@ -392,13 +394,15 @@ public struct TrashService: Sendable {/// Moves `apps` first, then what `files` returns for the apps that stayed, as one removal. An app's files wait/// for it, so an app that stays keeps everything of its own. A program running from inside one of- /// `lettingTheirProgramsRun` doesn't keep it, since that app uninstalls itself once it has moved.+ /// `lettingTheirProgramsRun` doesn't keep it, since that app uninstalls itself once it has moved. A folder+ /// named in `emptiedFoldersNamed` (`MakersFolders.names`) that the files leave empty goes too.@concurrentpublic func trash(apps: [URL],thenFiles files: @Sendable (_ appsThatStayed: Set<URL>) -> [URL],usingHelperFor privilegedURLs: Set<URL>,- lettingTheirProgramsRun running: Set<URL>+ lettingTheirProgramsRun running: Set<URL>,+ emptiedFoldersNamed names: Set<String> = []) async -> TrashResult {let removal = UUID()var result = apps.isEmpty@@ -410,6 +414,13 @@ public struct TrashService: Sendable {let more = await trash(rest, usingHelperFor: privilegedURLs, removal: removal, lettingTheirProgramsRun: [])result.trashed += more.trashedresult.failures += more.failures+ // Nobody asked for these folders, so one that stays is no failure.+ for folder in MakersFolders(environment: environment, names: names).above(more.trashed.map(\.originalURL))+ where MakersFolders.isEmpty(folder) {+ let moved = await trash([folder], usingHelperFor: [], removal: removal, lettingTheirProgramsRun: []).trashed+ result.trashed += moved+ result.emptied.formUnion(moved.map(\.originalURL))+ }return result}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swiftindex d631e15e..baeb386d 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift@@ -343,10 +343,16 @@ public struct Uninstallation: Sendable {apps: order.filter { $0 == app.url },thenFiles: { stayed in stayed.isEmpty ? files : [] },usingHelperFor: throughTheHelper ? privilegedURLs : [],- lettingTheirProgramsRun: uninstallsItself == nil ? [] : [app.url]+ lettingTheirProgramsRun: uninstallsItself == nil ? [] : [app.url],+ emptiedFoldersNamed: makersFolderNames)}+ /// The names of the app's and its maker's folders, one of which goes too once the uninstall leaves it empty.+ public var makersFolderNames: Set<String> {+ MakersFolders.names(of: [app])+ }+/// Whether the app stayed while files of its own were selected, which then stayed with it.public func keptItsFiles(after result: TrashResult, selection: Set<URL>) -> Bool {selection.contains(app.url) && result.failures.contains { $0.url == app.url }diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swiftindex 62ddc148..fb997632 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift@@ -237,6 +237,23 @@ struct CleanupTests {#expect(await RefusalLog(url: refusals.url).load().records?.map(\.url) == [documents])}+ @Test func anUninstallRecordsAMakersFolderItLeftEmptyAsFreeingNothing() async throws {+ let directory = try TemporaryDirectory()+ let app = try directory.directory("home/Applications/Notes.app")+ let data = try directory.directory("home/Library/Application Support/Example/org.example.Notes")+ let log = RemovalLog(url: directory.url.appending(path: "Peel/removals.json"))+ let plan = UninstallPlan(app: app, items: [+ UninstallPlan.Item(url: app, size: 4_096, refusal: nil),+ UninstallPlan.Item(url: data, size: 64, refusal: nil),+ ], needsAdministrator: 0, needsReview: 0, makersFolderNames: ["example"])++ #expect(await plan.record(await plan.move(using: try service(in: directory)), from: "Notes", in: log))++ let records = await RemovalLog(url: log.url).load().records ?? []+ #expect(records.first { $0.originalURL.lastPathComponent == "Example" }?.size == 0)+ #expect(records.count == 3)+ }+/// `peel uninstall` writes down what the guard refused before the move beside what moved, as every other/// command does, and an app the guard keeps where it is is written down too, though nothing moved.@Test func anUninstallWritesDownWhatTheGuardRefusedBeforeTheMove() async throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swiftindex b51ad68e..4043c4fc 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift@@ -608,6 +608,94 @@ struct UninstallationTests {#expect(!plan.keptItsFiles(after: went, selection: [bundle, cache]))}+ private func file(_ url: URL, _ kind: SearchLocation.Kind) -> Leftover {+ Leftover(+ url: url,+ kind: kind,+ match: LeftoverMatch(reason: .bundleIdentifier, confidence: .certain, sharedWith: []),+ size: 16,+ isMeasured: true,+ requiresPrivileges: false+ )+ }++ @Test func aMakersFolderTheUninstallLeavesEmptyGoesToo() async throws {+ let directory = try TemporaryDirectory()+ let bundle = try directory.directory("Applications/Notes.app")+ let support = "home/Library/Application Support"+ let product = try directory.directory("\(support)/Example/Notes")+ try directory.file("\(support)/Example/Notes/data")+ let top = try directory.directory("\(support)/org.example.Notes")+ let help = try directory.directory("home/Library/Caches/com.apple.helpd/Generated/org.example.Notes")+ let plan = uninstallation(+ app: InstalledApp(url: bundle, bundleIdentifier: "org.example.Notes", name: "Notes"),+ leftovers: [file(product, .applicationSupport), file(top, .applicationSupport), file(help, .caches)]+ )++ let went = await plan.move([bundle, product, top, help], using: try service(in: directory, refusing: nil))++ let maker = directory.url.appending(path: "\(support)/Example")+ #expect(Set(went.trashed.map { PathPattern.comparablePath(of: $0.originalURL) })+ == Set([bundle, product, top, help, maker].map(PathPattern.comparablePath(of:))))+ let records = RemovalPart(source: "Notes", sourceKey: nil, tool: "applications")+ .records(of: went, sizes: [bundle: 4_096], batch: UUID())+ let size = { (url: URL) in+ let path = PathPattern.comparablePath(of: url)+ return records.first { PathPattern.comparablePath(of: $0.originalURL) == path }?.size+ }+ #expect(size(maker) == 0)+ #expect(size(product) == nil)+ #expect(size(bundle) == 4_096)+ #expect(!directory.url.appending(path: "home/Library/Caches/com.apple.helpd/Generated").isMissing)+ #expect(!directory.url.appending(path: support).isMissing)+ #expect(went.failures.isEmpty)+ }++ @Test func onlyAnEmptyFolderInsideALibraryLocationEverGoes() async throws {+ let directory = try TemporaryDirectory()+ let bundle = try directory.directory("Applications/Notes.app")+ let cache = try directory.directory("home/Library/Caches/org.example.Notes")+ let config = try directory.directory("home/.config/Example/org.example.Notes")+ let logs = try directory.directory("home/Library/Logs/Example/Notes")+ try directory.file("home/Library/Logs/Example/.DS_Store")+ let target = try directory.directory("home/Library/Application Support/Linked/Notes")+ try FileManager.default.createSymbolicLink(+ at: directory.url.appending(path: "home/Library/Application Support/Example"),+ withDestinationURL: target.deletingLastPathComponent()+ )+ let throughLink = directory.url.appending(path: "home/Library/Application Support/Example/Notes")+ let app = InstalledApp(url: bundle, bundleIdentifier: "org.example.Notes", name: "Notes")+ let plan = uninstallation(app: app, leftovers: [+ file(cache, .caches), file(config, .hiddenHomeFiles), file(logs, .logs),+ file(throughLink, .applicationSupport),+ ])+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ )++ let candidates = MakersFolders(environment: environment, names: plan.makersFolderNames)+ .above([cache, config, logs])+ #expect(+ candidates.map(PathPattern.comparablePath(of:))+ == [PathPattern.comparablePath(of: logs.deletingLastPathComponent())]+ )+ #expect(MakersFolders(environment: environment, names: ["caches", "library"]).above([cache]).isEmpty)++ let all = [bundle, cache, config, logs, throughLink]+ let went = await plan.move(Set(all), using: try service(in: directory, refusing: nil))++ #expect(Set(went.trashed.map { PathPattern.comparablePath(of: $0.originalURL) })+ == Set(all.map(PathPattern.comparablePath(of:))))+ let kept = [+ "home/Library/Caches", "home/.config/Example", "home/Library/Logs/Example",+ "home/Library/Application Support/Example",+ ]+ for kept in kept {+ #expect(!directory.url.appending(path: kept).isMissing, "\(kept) went")+ }+ }+/// The receipt is what keeps macOS counting the package as installed, so it goes with the app. A receipt/// proves an app only up to a separator: `com.example.app2.pkg` is another package's.@Test func offersTheInstallerReceiptWithTheApp() async throws {diff --git a/Peel/Model/BulkRemovalPlan.swift b/Peel/Model/BulkRemovalPlan.swiftindex 29893abe..7bc1f68c 100644--- a/Peel/Model/BulkRemovalPlan.swift+++ b/Peel/Model/BulkRemovalPlan.swift@@ -127,8 +127,10 @@ final class BulkRemovalPlan {var removal = RemovalInProgress()let moved = bulk?.apps(owning: result.trashed.map(\.originalURL)) ?? []let stayed = bulk?.apps(owning: result.failures.map(\.url)) ?? []+ var trashed = result+ trashed.failures = []let parts = [- (TrashResult(trashed: result.trashed), part(naming: moved)),+ (trashed, part(naming: moved)),(TrashResult(failures: result.failures), part(naming: stayed)),]for (result, part) in parts {diff --git a/SAFETY.md b/SAFETY.mdindex 805740ee..f568ec83 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -215,7 +215,10 @@ And nothing at all is selected for an app that would stay: one macOS keeps, onehelper may not move, or one that needs the helper while it cannot act. An app that is part of another, such as ahelper app inside the app it serves, is never moved on its own, from the app or from `peel`: it would be cut out ofthe app it belongs to. 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.+the selection, those it shares with the other apps included, and selecting it again brings them back. A folder in+your Library named for the app or its maker, such as `Application Support/<Maker>`, that an uninstall leaves empty+goes to the Trash with it; one with anything left inside, a hidden file included, one with another name, and the+Library folder itself stay.Peel itself is listed on its own page with what it keeps, and nothing of it can be selected there or among otherapps. It is removed only from Settings: by Remove Peel, which takes its helper and login item away first, or,