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
peel uninstall --json reports what moved, what stayed, and why
Țugui Dragoșe819f722f8f1
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swiftindex f1af23d9..c0c3f73e 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift@@ -211,6 +211,115 @@ struct UninstallCommand: AsyncParsableCommand {@Flag(name: .shortAndLong, help: "Don't ask for confirmation.")var yes = false+ @OptionGroup var output: OutputOptions++ /// What `--json` writes once the command is done: each item and why it stays when it does, then, unless it+ /// was a dry run, what moved and what failed, and why.+ struct Report: Encodable {+ struct Item: Encodable {+ let path: String+ let size: MeasuredSize+ /// Why the item stays where it is, in the words `peel history --refused` uses, or `null` when it moves.+ let stays: String?++ private enum CodingKeys: String, CodingKey {+ case path+ case size+ case stays+ }++ func encode(to encoder: any Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(path, forKey: .path)+ try container.encode(size, forKey: .size)+ try container.encode(stays, forKey: .stays)+ }+ }++ struct Failure: Encodable {+ let path: String+ let reason: String+ let detail: String?++ private enum CodingKeys: String, CodingKey {+ case path+ case reason+ case detail+ }++ func encode(to encoder: any Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(path, forKey: .path)+ try container.encode(reason, forKey: .reason)+ try container.encode(detail, forKey: .detail)+ }+ }++ let app: AppRecord+ let dryRun: Bool+ let items: [Item]+ let moved: [String]+ let failed: [Failure]+ /// Whether the privacy permissions were reset, or `null` when that wasn't done: not asked for, or a dry run.+ let privacyReset: Bool?+ /// The leftovers that stay because they need administrator access, and those left for review.+ let needsAdministrator: Int+ let needsReview: Int+ /// The folders macOS kept Peel out of, where the app may have left more.+ let unreadableLocations: [String]++ private enum CodingKeys: String, CodingKey {+ case app+ case dryRun+ case items+ case moved+ case failed+ case privacyReset+ case needsAdministrator+ case needsReview+ case unreadableLocations+ }++ /// Encodes an unknown `privacyReset` as `null`, for the reason `AppRecord` gives.+ func encode(to encoder: any Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(app, forKey: .app)+ try container.encode(dryRun, forKey: .dryRun)+ try container.encode(items, forKey: .items)+ try container.encode(moved, forKey: .moved)+ try container.encode(failed, forKey: .failed)+ try container.encode(privacyReset, forKey: .privacyReset)+ try container.encode(needsAdministrator, forKey: .needsAdministrator)+ try container.encode(needsReview, forKey: .needsReview)+ try container.encode(unreadableLocations, forKey: .unreadableLocations)+ }+ }++ /// The report `--json` writes. `result` is nil for a dry run, which moved nothing.+ static func report(+ app: InstalledApp,+ plan: UninstallPlan,+ result: TrashResult?,+ privacy: PrivacyReset.Result?,+ unreadable: [SearchLocation]+ ) -> Report {+ Report(+ app: AppRecord(app),+ dryRun: result == nil,+ items: plan.items.map { item in+ Report.Item(path: Output.path(item.url), size: MeasuredSize(item.size), stays: item.refusal?.name)+ },+ moved: (result?.trashed ?? []).map { Output.path($0.originalURL) },+ failed: (result?.failures ?? []).map {+ Report.Failure(path: Output.path($0.url), reason: $0.reason.name, detail: $0.reason.detail)+ },+ privacyReset: privacy.map { $0 == .reset },+ needsAdministrator: plan.needsAdministrator,+ needsReview: plan.needsReview,+ unreadableLocations: unreadable.map { Output.path($0.url) }+ )+ }+func validate() throws {if !yes, !dryRun {try Output.requireConfirmable()@@ -282,19 +391,26 @@ struct UninstallCommand: AsyncParsableCommand {if let refusal = plan.appStays {throw CommandFailure("Peel won't move \(Output.path(target.url)): \(refusal.summary). Nothing of \(target.name) was touched.")}- // The third column appears only when some item stays, so an ordinary list has no trailing spaces.- let staying = !plan.staying.isEmpty- Output.table(plan.items.map { item in- [Output.size(item.size), Output.path(item.url)] + (staying ? [item.refusal.map { "stays: \($0.summary)" } ?? "moves"] : [])- })- Output.line("Total: \(Output.size(plan.total))")- if resetPrivacy {- Output.line("Peel resets \(target.name)'s privacy permissions just before it moves. The Trash can't bring them back.")+ let unreadable = uninstallation.scan.unreadableLocations+ if !output.json {+ // The third column appears only when some item stays, so an ordinary list has no trailing spaces.+ let staying = !plan.staying.isEmpty+ Output.table(plan.items.map { item in+ [Output.size(item.size), Output.path(item.url)] + (staying ? [item.refusal.map { "stays: \($0.summary)" } ?? "moves"] : [])+ })+ Output.line("Total: \(Output.size(plan.total))")+ if resetPrivacy {+ Output.line("Peel resets \(target.name)'s privacy permissions just before it moves. The Trash can't bring them back.")+ }}Self.whatStays(plan, app: target, homebrew: homebrew, scan: uninstallation.scan).forEach(Output.note)guard !dryRun else {- Output.line(resetPrivacy ? "Dry run: nothing was moved or reset." : "Dry run: nothing was moved.")+ if output.json {+ try Output.json(Self.report(app: target, plan: plan, result: nil, privacy: nil, unreadable: unreadable))+ } else {+ Output.line(resetPrivacy ? "Dry run: nothing was moved or reset." : "Dry run: nothing was moved.")+ }return}if !yes {@@ -309,16 +425,25 @@ struct UninstallCommand: AsyncParsableCommand {signal(SIGINT, SIG_IGN)signal(SIGTERM, SIG_IGN)// The privacy reset comes before the move, because `tccutil` only finds an app that is still in place.- let privacy = resetPrivacy ? Self.privacyOutcome(await PrivacyReset.reset(bundleIdentifier: target.bundleIdentifier), app: target) : nil+ let reset = resetPrivacy ? await PrivacyReset.reset(bundleIdentifier: target.bundleIdentifier) : nil+ let privacy = reset.map { Self.privacyOutcome($0, app: target) }let result = await plan.move(using: service)let sizes = [URL: Int64](measured: plan.items.map { ($0.url, $0.size) })let recorded = await Removals.record(result, from: target.name, sizes: sizes, tool: "applications")signal(SIGINT, SIG_DFL)signal(SIGTERM, SIG_DFL)- Output.line("Moved \(Output.count(result.trashed.count, "item", "items")) to the Trash.")- if let privacy {- privacy.failed ? Output.note(privacy.line) : Output.line(privacy.line)+ if output.json {+ let report = Self.report(app: target, plan: plan, result: result, privacy: reset, unreadable: unreadable)+ try Output.json(report)+ if let privacy, privacy.failed {+ Output.note(privacy.line)+ }+ } else {+ Output.line("Moved \(Output.count(result.trashed.count, "item", "items")) to the Trash.")+ if let privacy {+ privacy.failed ? Output.note(privacy.line) : Output.line(privacy.line)+ }}if !recorded {Output.note("Peel couldn't write this to its History, so drag these back out of the Trash in Finder if you need to.")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swiftindex 8c8384d0..15331ebf 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift@@ -211,6 +211,43 @@ struct CommandLineTests {#expect(json["appSize"] is NSNull)}+ /// `peel uninstall --json` says, once it is done, what was to move and what stayed and why, what moved, and+ /// what failed and why, with every key in every record.+ @Test func theUninstallReportSaysWhatMovedWhatStayedAndWhy() throws {+ let app = URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory)+ let support = URL(filePath: "/Users/me/Library/Application Support/Editor", directoryHint: .isDirectory)+ let caches = URL(filePath: "/Users/me/Library/Caches/com.example.editor", directoryHint: .isDirectory)+ let plan = UninstallPlan(app: app, items: [+ UninstallPlan.Item(url: app, size: 4_096, refusal: nil),+ UninstallPlan.Item(url: support, size: nil, refusal: nil),+ UninstallPlan.Item(url: caches, size: 10, refusal: .protectedLocation),+ ], needsAdministrator: 1, needsReview: 2)+ let result = TrashResult(trashed: [], failures: [TrashFailure(url: support, reason: .failed("disk full"))])+ let editor = InstalledApp(url: app, bundleIdentifier: "com.example.editor", name: "Editor")++ let json = try Output.jsonText(UninstallCommand.report(app: editor, plan: plan, result: result, privacy: .reset, unreadable: []))++ let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])+ let items = try #require(report["items"] as? [[String: Any]])+ #expect(items.map { $0["stays"] as? String } == [nil, nil, "protected-location"])+ #expect(items[0]["stays"] is NSNull)+ #expect(items[1]["size"] is NSNull)+ let failed = try #require(report["failed"] as? [[String: Any]])+ #expect(failed.first?["reason"] as? String == "failed")+ #expect(failed.first?["detail"] as? String == "disk full")+ #expect(report["dryRun"] as? Bool == false)+ #expect(report["privacyReset"] as? Bool == true)+ #expect(report["needsAdministrator"] as? Int == 1)+ #expect(report["needsReview"] as? Int == 2)+ #expect(report["unreadableLocations"] as? [String] == [])++ let dryRun = try Output.jsonText(UninstallCommand.report(app: editor, plan: plan, result: nil, privacy: nil, unreadable: []))+ let planned = try #require(JSONSerialization.jsonObject(with: Data(dryRun.utf8)) as? [String: Any])+ #expect(planned["dryRun"] as? Bool == true)+ #expect(planned["moved"] as? [String] == [])+ #expect(planned["privacyReset"] is NSNull)+ }+/// A script adds sizes up, so an unknown size is `null` under the same key: never zero, and never a missing/// key. In JSON a total with an unknown part is `null` too, and in text it reads "over" the known part.@Test func writesASizeNobodyKnowsAsNull() throws {@@ -622,6 +659,8 @@ struct CommandLineTests {#expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["search", "--older-than", "30"]) }#expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["uninstall"]) }+ let uninstall = try #require(try PeelCommand.parseAsRoot(["uninstall", "Editor", "--json", "--dry-run"]) as? UninstallCommand)+ #expect(uninstall.output.json)}private func record(_ batch: UUID, _ path: String, at date: Date) -> RemovalRecord {diff --git a/README.md b/README.mdindex 7e158d95..0be6b738 100644--- a/README.md+++ b/README.md@@ -231,7 +231,8 @@ Every command that moves something asks first, and takes `--dry-run` to only shoquestion. Answering no exits with code 2, so `peel uninstall Foo && next-step` stops there. The command moves onlywhat the app would suggest, through the same checks, into the same History, and leaves anything that needs anadministrator to the app. It won't run under `sudo`. Most commands take `--json`, which lists without moving, and-`peel --generate-completion-script zsh` writes completions for your shell.+`peel uninstall --json` reports what moved, what stayed, and why. `peel --generate-completion-script zsh` writes+completions for your shell.<details><summary>All commands</summary>