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.

Show the plan on a dry run of peel uninstall when the app would stay

Țugui Dragoșc8093b93d878
diff --git a/GUIDE.md b/GUIDE.md
index 6855fdbc..c4f6dbb6 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -401,10 +401,11 @@ when you open Peel again from the menu bar, Finder, or Spotlight.
and `updates` take `--json`, which lists and never moves, so `--json` with `--remove` is refused rather than guessed
at, and `uninstall --json` reports once the move is done: each item and why it stays, what moved, what failed and
why, whether the privacy reset happened, the folders Peel couldn't read, and the lines of your shell files that
- still name what moved. `leftovers --json` says in `appStays` why the app itself would stay, when it would, since
- none of its files moves then. A size nobody knows is `null`, never zero, and what a scan couldn't read is said on
- standard error too. The exit status says how it ended: 0 when it did what was asked, 1 when something failed or
- stayed where it was, 2 when you answered no, and 64 when the command is wrong or it would have to ask and can't.
+ still name what moved. `leftovers --json` and `uninstall --dry-run --json` say in `appStays` why the app itself would
+ stay, when it would, since none of its files moves then. A size nobody knows is `null`, never zero, and what a scan
+ couldn't read is said on standard error too. The exit status says how it ended: 0 when it did what was asked, which
+ for `--dry-run` is showing the plan, whatever would stay, 1 when something failed or stayed where it was, 2 when you
+ answered no, and 64 when the command is wrong or it would have to ask and can't.
- **Completions and manual.** A Homebrew install sets up its completions for zsh, bash, and fish, and its manual
page, `man peel`. Otherwise `peel --generate-completion-script zsh` (or `bash`, or `fish`) writes the
completions for your shell, and `man /Applications/Peel.app/Contents/Resources/man/peel.1` shows the manual page.
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
index 427b7967..293b49ba 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
@@ -372,6 +372,8 @@ struct UninstallCommand: AsyncParsableCommand {
let unreadableLocations: [String]
let needsFullDiskAccess: Bool
let cutShortLocations: [String]
+ /// Why the app itself would stay, which only a dry run reports: a real run refuses instead.
+ let appStays: String?
let shellReferences: [ShellReference]
struct ShellReference: Encodable {
@@ -393,6 +395,7 @@ struct UninstallCommand: AsyncParsableCommand {
case unreadableLocations
case needsFullDiskAccess
case cutShortLocations
+ case appStays
case shellReferences
}
@@ -412,6 +415,7 @@ struct UninstallCommand: AsyncParsableCommand {
try container.encode(unreadableLocations, forKey: .unreadableLocations)
try container.encode(needsFullDiskAccess, forKey: .needsFullDiskAccess)
try container.encode(cutShortLocations, forKey: .cutShortLocations)
+ try container.encode(appStays, forKey: .appStays)
try container.encode(shellReferences, forKey: .shellReferences)
}
}
@@ -423,13 +427,16 @@ struct UninstallCommand: AsyncParsableCommand {
result: TrashResult?,
privacy: PrivacyReset.Result?,
scan: LeftoverScan,
+ appStays: String? = nil,
shellReferences: [ShellReferences.Reference] = []
) -> 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)
+ Report.Item(
+ path: Output.path(item.url), size: MeasuredSize(item.size), stays: plan.whyItStays(item)?.word
+ )
},
moved: (result?.trashed ?? []).map { Output.path($0.originalURL) },
failed: (result?.failures ?? []).map {
@@ -443,6 +450,7 @@ struct UninstallCommand: AsyncParsableCommand {
unreadableLocations: scan.unreadableLocations.map { Output.path($0.url) },
needsFullDiskAccess: scan.needsFullDiskAccess,
cutShortLocations: scan.cutShortLocations.map { Output.path($0.url) },
+ appStays: appStays,
shellReferences: shellReferences.map { Report.ShellReference(file: Output.path($0.file), line: $0.line) }
)
}
@@ -487,7 +495,7 @@ struct UninstallCommand: AsyncParsableCommand {
}
/// What would stop the move now, as a note on a dry run, which moves nothing, and as the refusal otherwise.
- static func note(for failure: CommandFailure?, dryRun: Bool) throws -> String? {
+ static func note(for failure: (any Error & CustomStringConvertible)?, dryRun: Bool) throws -> String? {
guard let failure else { return nil }
guard dryRun else { throw failure }
return failure.description
@@ -643,16 +651,18 @@ struct UninstallCommand: AsyncParsableCommand {
func run() async throws {
let apps = await AppCatalog.installedApps()
let target = try AppLookup.app(matching: app, in: apps)
- let carried = await AppExtensions.installed(carriedBy: target)
- if let refusal = Self.removedElsewhere(target, installedSystemExtensions: carried)
- ?? Self.keptByMacOS(target) ?? Self.partOfAnotherPackage(target) {
- throw refusal
+ if !dryRun {
+ let carried = await AppExtensions.installed(carriedBy: target)
+ if let refusal = Self.removedElsewhere(target, installedSystemExtensions: carried)
+ ?? Self.keptByMacOS(target) ?? Self.partOfAnotherPackage(target) {
+ throw refusal
+ }
}
if resetPrivacy {
try Self.refuseIfPrivacyCannotBeReset(target)
}
let exclusions = await ExclusionStore().load()
- try AppLookup.refuseIfExcluded(target, by: exclusions)
+ let excluded = try Self.note(for: AppLookup.refusal(of: target, by: exclusions), dryRun: dryRun)
let service = TrashService(exclusions: exclusions)
let running = try Self.note(for: await Self.whileRunning(target, among: apps), dryRun: dryRun)
let homebrew = await CaskLookup.evidence(for: target)
@@ -667,44 +677,52 @@ struct UninstallCommand: AsyncParsableCommand {
}
let access = try Self.note(for: Self.whyItStays(uninstallation), dryRun: dryRun)
let inTheTrash = uninstallation.isAppInTheTrash ? LeftoversCommand.inTheTrash(target) : nil
- [running, access, inTheTrash].compactMap(\.self).forEach(Output.note)
+ [excluded, running, access, inTheTrash].compactMap(\.self).forEach(Output.note)
if let note = UnreadableHistory.note() {
Output.note(note)
}
// The removal guard judges each item before printing, so the list shows what the move will really do.
let plan = UninstallPlan.make(uninstallation, keepLeftovers: keepLeftovers, refusal: service.refusal(of:))
- if let refusal = plan.appStays {
- if !dryRun {
+ let wontMove = plan.appStays.map { "Peel won't move \(Output.plain(Output.path(target.url))): \($0.summary)." }
+ if let wontMove {
+ guard dryRun else {
_ = await plan.record(TrashResult(), from: target.name)
+ throw CommandFailure("\(wontMove) Nothing of \(Output.plain(target.name)) was touched.")
}
- throw CommandFailure("Peel won't move \(Output.plain(Output.path(target.url))): \(refusal.summary). Nothing of \(Output.plain(target.name)) was touched.")
+ Output.note("\(wontMove) While it stays, none of its files moves.")
}
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
- if plan.items.isEmpty {
- Output.line("Nothing here can be moved.")
- } else {
+ let saysWhy = plan.moving.count < plan.items.count
+ if !plan.items.isEmpty {
Output.table(plan.items.map { item in
- [Output.size(item.size), Output.path(item.url)] + (staying ? [item.refusal.map { "stays: \($0.summary)" } ?? "moves"] : [])
+ let stays = plan.whyItStays(item).map { "stays: \($0.summary)" }
+ return [Output.size(item.size), Output.path(item.url)] + (saysWhy ? [stays ?? "moves"] : [])
})
- Output.line("Total: \(Output.size(plan.total))")
}
+ Output.line(plan.moving.isEmpty ? "Nothing here can be moved." : "Total: \(Output.size(plan.total))")
}
- // With `--json`, standard output is the report alone, so the warnings go where the notes go.
- let warnings = Self.warnings(moving: Set(plan.moving.map(\.url)), of: target, resettingPrivacy: resetPrivacy)
let isInTheDock = !(await DockTiles().holding([target.url])).isEmpty
- let dock = Self.dockNote(for: target, isInTheDock: isInTheDock, keeping: keepInDock)
- let webApp = Self.browserName(of: target, among: apps).flatMap { Self.webAppNote(for: target, browserName: $0) }
- (warnings + [dock, webApp].compactMap(\.self)).forEach(output.json ? Output.note : Output.line)
+ // With `--json`, standard output is the report alone, so the warnings go where the notes go.
+ if !plan.moving.isEmpty {
+ let moving = Set(plan.moving.map(\.url))
+ let warnings = Self.warnings(moving: moving, of: target, resettingPrivacy: resetPrivacy)
+ let dock = Self.dockNote(for: target, isInTheDock: isInTheDock, keeping: keepInDock)
+ let webApp = Self.browserName(of: target, among: apps)
+ .flatMap { Self.webAppNote(for: target, browserName: $0) }
+ (warnings + [dock, webApp].compactMap(\.self)).forEach(output.json ? Output.note : Output.line)
+ }
Self.whatStays(plan, app: target, homebrew: homebrew, scan: uninstallation.scan).forEach(Output.note)
guard !dryRun else {
if output.json {
- let scan = uninstallation.scan
- try Output.json(Self.report(app: target, plan: plan, result: nil, privacy: nil, scan: scan))
- } else {
+ let report = Self.report(
+ app: target, plan: plan, result: nil, privacy: nil, scan: uninstallation.scan,
+ appStays: excluded ?? access ?? wontMove
+ )
+ try Output.json(report)
+ } else if !plan.moving.isEmpty {
Output.line(resetPrivacy ? "Dry run: nothing was moved or reset." : "Dry run: nothing was moved.")
}
return
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/AppLookup.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/AppLookup.swift
index 220a97c5..cd687d67 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/AppLookup.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/AppLookup.swift
@@ -32,9 +32,16 @@ enum AppLookup {
by exclusions: Exclusions,
savedAt url: URL = ExclusionStore.defaultURL
) throws(Failure) {
- guard !exclusions.isUnreadable else { throw .exclusionsUnreadable(url.path(percentEncoded: false)) }
- guard exclusions.excludes(app) else { return }
- throw .excluded(app.name)
+ if let refusal = refusal(of: app, by: exclusions, savedAt: url) { throw refusal }
+ }
+
+ static func refusal(
+ of app: InstalledApp,
+ by exclusions: Exclusions,
+ savedAt url: URL = ExclusionStore.defaultURL
+ ) -> Failure? {
+ guard !exclusions.isUnreadable else { return .exclusionsUnreadable(url.path(percentEncoded: false)) }
+ return exclusions.excludes(app) ? .excluded(app.name) : nil
}
/// Reads a bundle that isn't among the installed apps from the disk. Injected so a test doesn't depend on
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift
index 09cec63d..fc350976 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift
@@ -26,7 +26,7 @@ struct UninstallPlan {
var makersFolderNames: Set<String> = []
var appSharesStorage = false
- var moving: [Item] { items.filter { $0.refusal == nil } }
+ var moving: [Item] { appStays == nil ? items.filter { $0.refusal == nil } : [] }
var staying: [Item] { items.filter { $0.refusal != nil } }
var total: SizeTotal {
SizeTotal(movingItemsAt: Dictionary(moving.map { ($0.url, $0.size) }) { first, _ in first })
@@ -36,6 +36,11 @@ struct UninstallPlan {
/// app that is still installed aren't leftovers.
var appStays: TrashFailure.Reason? { items.first { $0.url == app }?.refusal }
+ func whyItStays(_ item: Item) -> (word: String, summary: String)? {
+ if let refusal = item.refusal { return (refusal.name, refusal.summary) }
+ return appStays == nil ? nil : ("app-stays", "its app stays")
+ }
+
/// Builds the plan with the bundle first. macOS refuses to move another developer's app without the App
/// Management permission, and if that refusal came last, the app would stay installed with its settings already
/// in the Trash.
@@ -46,7 +51,8 @@ struct UninstallPlan {
) -> UninstallPlan {
let app = uninstallation.app.url
// An app already in the Trash doesn't move again, and what it left behind still can.
- let bundle: Set<URL> = uninstallation.isAppInTheTrash ? [] : [app]
+ let leavesTheAppOut = uninstallation.isAppInTheTrash || uninstallation.appStays(canUseHelper: false)
+ let bundle: Set<URL> = leavesTheAppOut ? [] : [app]
let selection = keepLeftovers ? bundle : uninstallation.suggestedSelection(canUseHelper: false)
let ordered = [app] + uninstallation.removalOrder(of: selection).filter { $0 != app }
let leftovers = Dictionary(
@@ -103,7 +109,6 @@ struct UninstallPlan {
/// Moves the bundle to the Trash on its own, then the rest only if the bundle really moved. When the app itself
/// stays, nothing moves. An app already in the Trash isn't in the plan, and its files move on their own.
func move(using service: TrashService) async -> TrashResult {
- guard appStays == nil else { return TrashResult() }
let urls = moving.map(\.url)
let files = urls.filter { $0 != app }
return await service.trash(
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
index f9ac1f65..7ca6bb54 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
@@ -924,6 +924,49 @@ struct CommandLineTests {
refusal: { $0 == app.url ? .guarded(.protectedLocation) : nil }
)
#expect(refused.appStays == .guarded(.protectedLocation))
+ #expect(refused.moving.isEmpty)
+ #expect(refused.items.compactMap { refused.whyItStays($0)?.word } == ["protected-place", "app-stays"])
+ #expect(refused.items.compactMap { refused.whyItStays($0)?.summary }.last == "its app stays")
+ }
+
+ @Test func listsNothingAsMovingForAnAppThatStaysHoweverItIsAsked() {
+ let app = InstalledApp(
+ url: URL(filePath: "/Applications/Admin.app", directoryHint: .isDirectory),
+ bundleIdentifier: "org.example.admin", name: "Admin"
+ )
+ let kept = Uninstallation(
+ app: app, appSize: 0, appRequiresPrivileges: true,
+ scan: LeftoverScan(leftovers: [], unreadableLocations: [])
+ )
+
+ #expect(UninstallPlan.make(kept, keepLeftovers: true, refusal: { _ in nil }).items.isEmpty)
+ #expect(UninstallPlan.make(kept, keepLeftovers: false, refusal: { _ in nil }).items.isEmpty)
+ }
+
+ @Test func aDryRunWritesThePlanAndWhyWhenTheAppItselfWouldStay() async throws {
+ let directory = try TemporaryDirectory()
+ _ = try directory.directory("Synced/.stfolder")
+ let info: [String: Any] = ["CFBundleIdentifier": "org.example.kept", "CFBundleName": "Kept"]
+ _ = try directory.file(
+ "Synced/Kept.app/Contents/Info.plist",
+ contents: try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
+ )
+ let bundle = directory.url.appending(path: "Synced/Kept.app").path(percentEncoded: false)
+ let command = try #require(
+ try PeelCommand.parseAsRoot(["uninstall", bundle, "--dry-run", "--json"]) as? UninstallCommand
+ )
+ let collected = Output.Collected()
+
+ try await Homebrew.$standIn.withValue(directory.url.appending(path: "no-brew")) {
+ try await Output.$collected.withValue(collected) { try await command.run() }
+ }
+
+ let report = try #require(JSONSerialization.jsonObject(with: Data(collected.output.utf8)) as? [String: Any])
+ #expect(report["dryRun"] as? Bool == true)
+ #expect((report["appStays"] as? String)?.hasPrefix("Peel won't move") == true)
+ let items = try #require(report["items"] as? [[String: Any]])
+ #expect(items.map { $0["stays"] as? String } == ["in-the-cloud"])
+ #expect(collected.notes.contains("While it stays, none of its files moves."))
}
/// What stays is counted where the user can see it, and a size nobody knows is never added up as zero.