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
An orphaned folder with a wallet or a repository inside is chosen only by hand
Țugui Dragoș68d6a76163b4
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swiftindex 9cfc81a7..58ce51ed 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift@@ -6,7 +6,7 @@ struct OrphansCommand: AsyncParsableCommand {static let configuration = CommandConfiguration(commandName: "orphans",abstract: "List files left by apps that are no longer installed, and move a group to the Trash.",- discussion: "Nothing here is ever suggested, so --remove takes the identifier of one group. What Peel refuses to move, and what needs administrator access, stays."+ discussion: "Nothing here is ever suggested, so --remove takes the identifier of one group. What Peel refuses to move, what it leaves for you to choose in the app, and what needs administrator access, stays.")@Argument(help: "The group to move, as `peel orphans` names it in its first column.")@@ -74,7 +74,9 @@ struct OrphansCommand: AsyncParsableCommand {}static func rows(for group: OrphanGroup) -> [[String]] {- group.items.map { [Output.size($0.size), Output.path($0.url)] }+ group.items.map { item in+ [Output.size(item.size), Output.path(item.url)] + (item.heldBack.map { ["stays: \($0.summary)"] } ?? [])+ }}func clean(@@ -90,9 +92,12 @@ struct OrphansCommand: AsyncParsableCommand {guard let group = wanted.first else {throw CommandFailure("Nothing orphaned is called \(Output.quoted(identifier)). See `peel orphans`.")}- let items = group.items.filter { $0.leftAlone == nil }+ let items = group.items.filter { $0.heldBack == nil }+ // Nobody asked for a held back file on its own, so it is said here and never recorded as refused.+ let staying = group.items.compactMap { item in item.heldBack.map { "\(Output.path(item.url)) stays: \($0.summary)" } }guard !items.isEmpty else {Output.line("Every file of \(group.identifier) is one Peel leaves alone. See `peel orphans`.")+ staying.forEach(Output.note)return}let cleanup = Cleanup.of(@@ -104,6 +109,7 @@ struct OrphansCommand: AsyncParsableCommand {)try await cleanup.run(question: "Move \(Output.count(cleanup.moving.count, "item", "items")) of \(group.title) to the Trash?",+ notes: staying,dryRun: removal.dryRun,yes: removal.yes,using: service,diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Cleanup.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Cleanup.swiftindex 02cc5885..daa06959 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Cleanup.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Cleanup.swift@@ -52,10 +52,11 @@ struct Cleanup {throw ValidationError("--json lists what is there. Leave --remove off to get the list, or leave --json off to move it.")}- /// Prints the list and, unless `dryRun` is set, asks, moves what can go, and records it in History. A declined- /// answer exits 2, and a failed move exits 1.+ /// Prints the list, with `notes` under it, and, unless `dryRun` is set, asks, moves what can go, and records it+ /// in History. A declined answer exits 2, and a failed move exits 1.func run(question: String,+ notes: [String] = [],dryRun: Bool,yes: Bool,using service: TrashService,@@ -69,6 +70,7 @@ struct Cleanup {[Output.size(item.size), Output.path(item.url)] + (saysWhyItStays ? [item.refusal.map { "stays: \($0.summary)" } ?? "moves"] : [])})Output.line("Total: \(Output.size(total))")+ notes.forEach(Output.note)guard !dryRun else {Output.line(moving.isEmpty ? "Nothing here can be moved." : "Dry run: nothing was moved.")diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/Orphan.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/Orphan.swiftindex 62c16d10..36bc6cc7 100644--- a/Packages/PeelCore/Sources/PeelCore/Orphans/Orphan.swift+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/Orphan.swift@@ -8,9 +8,14 @@ public struct OrphanItem: Sendable, Hashable, Identifiable {/// When the item or anything inside it was last modified. Only its own date if it was not measured in time.public let modificationDate: Date?public let requiresPrivileges: Bool- /// Why the item cannot be moved, when `RemovalGuard` or the helper would refuse it. The item is still listed,- /// with this reason, but cannot be selected.- public var leftAlone: HoldBack?+ /// Why the item is left for the user to choose by hand, or nil. Select All passes it by, and `peel orphans+ /// --remove` leaves it where it is.+ public var heldBack: HoldBack?++ /// Why the item cannot be selected at all: `RemovalGuard` or the helper would refuse it.+ public var leftAlone: HoldBack? {+ heldBack?.cannotBeMoved == true ? heldBack : nil+ }public var id: URL { url }}diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swiftindex f2eeefb1..f069af7d 100644--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift@@ -81,7 +81,7 @@ public struct OrphanScanner: Sendable {.map { entry inguard entry.item.requiresPrivileges, entry.item.leftAlone == nil, reach.isBeyond(entry.item.url) else { return entry }var item = entry.item- item.leftAlone = .beyondTheHelper+ item.heldBack = .beyondTheHelperreturn (entry.identifier, item)}let teams = Set(installedApps.compactMap(\.teamIdentifier))@@ -239,6 +239,15 @@ public struct OrphanScanner: Sendable {return identifier}+ /// Why what the walk saw leaves an item to be chosen by hand: a wallet, a signing key, or a repository inside+ /// may exist nowhere else, and a folder the walk could not see into is not known to be empty.+ private static func heldBack(by contents: FolderContents?) -> HoldBack? {+ guard let contents else { return .notMeasured }+ if contents.couldNotBeRead { return .couldNotBeRead }+ if contents.holdsWallet { return .holdsAWallet }+ return contents.holdsRepository ? .holdsRepository : nil+ }+private enum LocationResult: Sendable {case found([(identifier: String, item: OrphanItem)])case unreadable(SearchLocation)@@ -275,12 +284,14 @@ public struct OrphanScanner: Sendable {let own = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDatelet contents = await walk(url)let path = url.path(percentEncoded: false)- let leftAlone: HoldBack? = if location.kind == .containers, ProtectedData.holdsAContainersDocuments(path) {+ let heldBack: HoldBack? = if location.kind == .containers, ProtectedData.holdsAContainersDocuments(path) {.holdsDocuments} else if ProtectedData.holds(path, home: home) {.holdsKeys+ } else if ProtectedData.holdsALibrary(path) {+ .holdsALibrary} else {- ProtectedData.holdsALibrary(path) ? .holdsALibrary : nil+ Self.heldBack(by: contents)}let item = OrphanItem(url: url,@@ -288,7 +299,7 @@ public struct OrphanScanner: Sendable {size: contents.flatMap { $0.couldNotBeRead ? nil : $0.size },modificationDate: [own, contents?.newestChange].compactMap(\.self).max(),requiresPrivileges: parent.requiresPrivileges(toRemove: url),- leftAlone: leftAlone+ heldBack: heldBack)found.append((identifier, item))}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swiftindex 1198e945..6d36d75d 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift@@ -161,14 +161,14 @@ struct FileCommandTests {// MARK: Orphaned files- private func orphan(_ name: String, in directory: borrowing TemporaryDirectory, leftAlone: HoldBack? = nil, requiresPrivileges: Bool = false) throws -> OrphanItem {+ private func orphan(_ name: String, in directory: borrowing TemporaryDirectory, heldBack: HoldBack? = nil, requiresPrivileges: Bool = false) throws -> OrphanItem {OrphanItem(url: try directory.file("home/Library/Application Support/\(name)/blob", bytes: 10).deletingLastPathComponent(),kind: .applicationSupport,size: 10,modificationDate: .now,requiresPrivileges: requiresPrivileges,- leftAlone: leftAlone+ heldBack: heldBack)}@@ -198,7 +198,7 @@ struct FileCommandTests {let logs = logs(in: directory)let wanted = OrphanGroup(identifier: "com.example.gone", items: [try orphan("com.example.gone", in: directory),- try orphan("com.example.gone.documents", in: directory, leftAlone: .holdsDocuments),+ try orphan("com.example.gone.documents", in: directory, heldBack: .holdsDocuments),])let other = OrphanGroup(identifier: "com.example.other", items: [try orphan("com.example.other", in: directory)])let scan = OrphanScan(groups: [wanted, other], unreadableLocations: [])@@ -234,16 +234,43 @@ struct FileCommandTests {let directory = try TemporaryDirectory()let logs = logs(in: directory)let group = OrphanGroup(identifier: "com.example.gone", items: [- try orphan("com.example.gone", in: directory, leftAlone: .holdsALibrary),+ try orphan("com.example.gone", in: directory, heldBack: .holdsALibrary),])let scan = OrphanScan(groups: [group], unreadableLocations: [])+ let collected = Output.Collected()- try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand)- .clean("com.example.gone", in: scan, apps: [], scanner: scanner(in: directory), using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)+ try await Output.$collected.withValue(collected) {+ try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand)+ .clean("com.example.gone", in: scan, apps: [], scanner: scanner(in: directory), using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)+ }#expect(await moved(logs).isEmpty)#expect(await logs.refusals.load().isEmpty)#expect(FileManager.default.fileExists(atPath: group.items[0].url.path(percentEncoded: false)))+ #expect(collected.notes == "\(Output.path(group.items[0].url)) stays: holds a photo, music, or video library\n")+ }++ /// A folder with a wallet or a repository inside is moved only when chosen by hand in the app, so naming its+ /// group moves the rest, says why it stays, and records no refusal, since nobody asked for it on its own.+ @Test func leavesWhatIsHeldBackAndSaysWhy() async throws {+ let directory = try TemporaryDirectory()+ let logs = logs(in: directory)+ let group = OrphanGroup(identifier: "com.example.gone", items: [+ try orphan("com.example.gone", in: directory),+ try orphan("com.example.gone.wallet", in: directory, heldBack: .holdsAWallet),+ ])+ let scan = OrphanScan(groups: [group], unreadableLocations: [])+ let collected = Output.Collected()++ try await Output.$collected.withValue(collected) {+ try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand)+ .clean("com.example.gone", in: scan, apps: [], scanner: scanner(in: directory), using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)+ }++ #expect(await moved(logs) == ["com.example.gone"])+ #expect(await logs.refusals.load().isEmpty)+ #expect(FileManager.default.fileExists(atPath: group.items[1].url.path(percentEncoded: false)))+ #expect(collected.notes == "\(Output.path(group.items[1].url)) stays: holds a wallet or a signing key\n")}// MARK: What the listings say@@ -333,6 +360,22 @@ struct FileCommandTests {#expect(OrphansCommand.rows(for: group) == [["10 bytes", Output.path(group.items[0].url)]])}+ /// The list says which files `--remove` leaves where they are, and why.+ @Test func saysWhichOrphanedFilesStayAndWhy() throws {+ let directory = try TemporaryDirectory()+ let group = OrphanGroup(identifier: "com.example.gone", items: [+ try orphan("com.example.gone", in: directory),+ try orphan("com.example.gone.wallet", in: directory, heldBack: .holdsAWallet),+ try orphan("com.example.gone.photos", in: directory, heldBack: .holdsALibrary),+ ])++ #expect(OrphansCommand.rows(for: group) == [+ ["10 bytes", Output.path(group.items[0].url)],+ ["10 bytes", Output.path(group.items[1].url), "stays: holds a wallet or a signing key"],+ ["10 bytes", Output.path(group.items[2].url), "stays: holds a photo, music, or video library"],+ ])+ }+@Test func saysEveryCacheLocationWithItsKind() throws {let directory = try TemporaryDirectory()let tool = try environment("Rust", id: "rust", locations: [diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swiftindex 14d9f86c..c19846fd 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift@@ -60,7 +60,8 @@ struct OrphanScannerTests {}/// What an app left behind can be the biggest folder in the Library. A folder that did not answer in time- /// is listed first with an unknown size, and the group's total says it is incomplete.+ /// is listed first with an unknown size, and the group's total says it is incomplete. It may hold a wallet+ /// all the same, so it is left to be chosen by hand.@Test func anItemThatDidNotAnswerInTimeIsNotReadAsEmpty() async throws {let directory = try TemporaryDirectory()try directory.file("home/Library/Application Support/com.gone.app/library.db", bytes: 400_000)@@ -79,6 +80,7 @@ struct OrphanScannerTests {#expect(group.items.first?.size == nil)#expect(!group.total.isComplete)#expect(group.total.known >= 50_000)+ #expect(group.items.map(\.heldBack) == [.notMeasured, nil])}/// A crash reporter keeps a folder for each app inside its own. When macOS will not let Peel list that folder,@@ -100,6 +102,7 @@ struct OrphanScannerTests {let directory = try TemporaryDirectory()let served = try directory.directory("root/Library/Application Support/com.gone.app")let beyond = try directory.directory("root/Users/Shared/com.gone.app")+ try directory.file("root/Users/Shared/com.gone.app/wallet.dat")for folder in [served, beyond] {try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: folder.path(percentEncoded: false))}@@ -120,6 +123,55 @@ struct OrphanScannerTests {#expect(try item(beyond).leftAlone == .beyondTheHelper)}+ /// What the walk saw inside may exist nowhere else. A folder with a wallet, a signing key, or a repository+ /// in it says so and is moved only when chosen by hand: Select All and `peel orphans --remove` pass it by.+ @Test func aFolderWithAWalletOrARepositoryInsideIsChosenOnlyByHand() async throws {+ let directory = try TemporaryDirectory()+ try directory.file("home/Library/Application Support/com.gone.coin/wallet.dat")+ try directory.file("home/Library/Application Support/com.gone.code/work/.git/HEAD")+ try directory.file("home/Library/Application Support/com.gone.cache/cache.db")++ let items = await scanner(in: directory).scan(installedApps: installed).groups.flatMap(\.items)+ func item(_ name: String) throws -> OrphanItem {+ try #require(items.first { $0.url.lastPathComponent == name })+ }++ #expect(try item("com.gone.coin").heldBack == .holdsAWallet)+ #expect(try item("com.gone.code").heldBack == .holdsRepository)+ #expect(try item("com.gone.cache").heldBack == nil)+ #expect(items.allSatisfy { $0.leftAlone == nil })+ }++ /// A folder macOS would not open is not known to be empty either.+ @Test func aFolderMacOSWouldNotOpenIsChosenOnlyByHand() async throws {+ let directory = try TemporaryDirectory()+ try directory.file("home/Library/Application Support/com.gone.app/blob")+ let environment = SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ )+ let scanner = OrphanScanner(environment: environment, isRegisteredApp: { _ in false }) { _ in+ FolderContents(size: 0, holdsRepository: false, couldNotBeRead: true)+ }++ let item = try #require(await scanner.scan(installedApps: installed).groups.first?.items.first)++ #expect(item.heldBack == .couldNotBeRead)+ #expect(item.leftAlone == nil)+ #expect(item.size == nil)+ }++ /// A reason that keeps a folder where it is outranks what the walk saw, which only leaves it to be chosen.+ @Test func whatKeepsAFolderInPlaceOutranksWhatTheWalkSaw() async throws {+ let directory = try TemporaryDirectory()+ try directory.file("home/Library/Application Support/com.gone.photos/Main.photoslibrary/database/Photos.sqlite")+ try directory.file("home/Library/Application Support/com.gone.photos/.git/HEAD")++ let items = await scanner(in: directory).scan(installedApps: installed).groups.flatMap(\.items)++ #expect(items.map(\.leftAlone) == [.holdsALibrary])+ }+/// An agent writes to a log two folders down, while the folder's own date is from the day of the install.@Test func readsTheNewestWriteInsideAFolderNotTheFoldersOwnDate() async throws {let directory = try TemporaryDirectory()diff --git a/Peel/Views/Orphans/OrphanDetailView.swift b/Peel/Views/Orphans/OrphanDetailView.swiftindex 6cc0044e..c2d440a9 100644--- a/Peel/Views/Orphans/OrphanDetailView.swift+++ b/Peel/Views/Orphans/OrphanDetailView.swift@@ -31,7 +31,7 @@ struct OrphanDetailView: View {icon: .symbol(item.kind.symbolName),detail: item.modificationDate.map { "Modified \($0, format: .relative(presentation: .named))" },kind: item.kind.title,- warning: item.leftAlone.map { String(localized: $0.explanation) },+ warning: item.heldBack.map { String(localized: $0.explanation) },size: item.size ?? 0,isMeasured: item.size != nil,isLocked: item.requiresPrivileges && !helper.canAct,@@ -74,7 +74,7 @@ struct OrphanDetailView: View {}private var hasNoteColumn: Bool {- group.items.contains { $0.modificationDate != nil || $0.leftAlone != nil }+ group.items.contains { $0.modificationDate != nil || $0.heldBack != nil }}/// The total size that can be moved to the Trash. Items Peel leaves alone are listed but not counted, as@@ -118,8 +118,10 @@ struct OrphanDetailView: View {SizeTotal(orphans.selected(in: group).map(\.size))}+ /// What Select All selects. A row held back waits to be chosen by hand, as Review Before Removing does on an+ /// app's page.private var selectableURLs: [URL] {- group.items.filter { $0.leftAlone == nil && (helper.canAct || !$0.requiresPrivileges) }.map(\.url)+ group.items.filter { $0.heldBack == nil && (helper.canAct || !$0.requiresPrivileges) }.map(\.url)}private func remove() async {diff --git a/SAFETY.md b/SAFETY.mdindex 2f3d7acd..ef69ff2a 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -144,6 +144,10 @@ last two are shown with their size as "Unknown", never as zero, in every tool anmoved: a folder too big to read quickly may be exactly the one with work inside, and nothing is selected for youwithout saying how much it is. A total that leaves such a folder out reads "Over" what is known.+Orphaned Files selects nothing for you, and its Select All and `peel orphans --remove` leave these folders out as+well: one with a repository, a wallet, or a signing key inside, or one Peel could not read or measure in time,+moves only when you select it yourself.+In Duplicates, one copy of every group always stays, and a file that changed since the scan is refused.Some things are shown and never removed at all, because the removal cannot be undone: local Time Machine