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
Remove Peel leaves nothing of Peel written behind it
Țugui Dragoș3389858852b3
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/StandingWork.swift b/Packages/PeelCore/Sources/PeelCore/Support/StandingWork.swiftnew file mode 100644index 00000000..0fbd02e9--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Support/StandingWork.swift@@ -0,0 +1,33 @@+public import Observation++/// Work that belongs to Peel rather than to a window, such as watching the folders apps are installed into, started+/// once and kept running while Peel does. Remove Peel pauses it before it moves Peel's files, since a folder watcher+/// or an update round going on would write them again, and resumes it when Peel stays where it was.+@MainActor+@Observable+public final class StandingWork {+ @ObservationIgnored private var work: [@MainActor () async -> Void] = []+ @ObservationIgnored private var running: [Task<Void, Never>] = []++ public init() {}++ /// Starts each piece of work. Only the first call starts anything: a window built again calls it again.+ public func start(_ work: [@MainActor () async -> Void]) {+ guard self.work.isEmpty else { return }+ self.work = work+ resume()+ }++ /// Stops every piece. Each ends at its next wait, since a piece waits on something that ends when its task is+ /// canceled: a stream of changes, a notification, or a sleep.+ public func pause() {+ running.forEach { $0.cancel() }+ running = []+ }++ /// Starts every piece again after a pause.+ public func resume() {+ guard running.isEmpty else { return }+ running = work.map { piece in Task { await piece() } }+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/StandingWorkTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/StandingWorkTests.swiftnew file mode 100644index 00000000..0831d0dd--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/StandingWorkTests.swift@@ -0,0 +1,38 @@+@testable import PeelCore+import Testing++@MainActor+struct StandingWorkTests {+ /// Remove Peel pauses the work Peel keeps running, a folder watcher among it, so nothing writes Peel's files again+ /// while they go to the Trash, and resumes it when Peel stays where it was.+ @Test func pausesEveryPieceAndResumesThem() async {+ var started = 0+ var ended = 0+ let (changes, _) = AsyncStream<Void>.makeStream()+ let work = StandingWork()+ work.start([{+ started += 1+ for await _ in changes {}+ ended += 1+ }])+ await settle { started == 1 }++ work.pause()+ await settle { ended == 1 }+ #expect(ended == 1, "a piece went on after the pause")++ work.resume()+ await settle { started == 2 }+ #expect(started == 2)+ work.start([{ started += 10 }])+ await settle { false }+ #expect(started == 2, "a second start ran the work again")+ work.pause()+ }++ private func settle(until done: () -> Bool) async {+ for _ in 0..<1_000 where !done() {+ await Task.yield()+ }+ }+}diff --git a/Peel/Model/BackgroundWork.swift b/Peel/Model/BackgroundWork.swiftdeleted file mode 100644index 1d10b743..00000000--- a/Peel/Model/BackgroundWork.swift+++ /dev/null@@ -1,22 +0,0 @@-import Foundation-import Observation--/// Work that belongs to Peel rather than to its window: watching the folders apps are installed into, and-/// checking for updates while Peel stays open. A task attached to a view is canceled when the view goes away,-/// and Peel can keep running in the menu bar with its window closed, so this work is started once, here,-/// rather than as a view's child task.-@MainActor-@Observable-final class BackgroundWork {- private var started = false-- /// Starts each piece of work once. Peel keeps one instance for as long as it runs, and a task runs whether or- /// not its handle is kept, so none is kept: nothing ever cancels them.- func start(_ work: [@MainActor () async -> Void]) {- guard !started else { return }- started = true- for piece in work {- Task { await piece() }- }- }-}diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swiftindex 29c766db..b7701a62 100644--- a/Peel/Model/RemovalHistoryStore.swift+++ b/Peel/Model/RemovalHistoryStore.swift@@ -169,11 +169,20 @@ final class RemovalHistoryStore {/// Records a removal from one place in History, as one entry. When Peel wrote the source itself, pass it in/// English along with a `sourceKey`, so History can show it in the user's language (see- /// `RemovalRecord.sourceKey`). An item missing from `sizes` is recorded as unknown.- func record(_ result: TrashResult, tool: Tool, source: String, sourceKey: String? = nil, sizes: [URL: Int64]) async {+ /// `RemovalRecord.sourceKey`). An item missing from `sizes` is recorded as unknown. Remove Peel leaves out the+ /// lifetime totals: they live in Peel's settings, which it has just cleared, and writing them would make those+ /// settings again.+ func record(+ _ result: TrashResult,+ tool: Tool,+ source: String,+ sourceKey: String? = nil,+ sizes: [URL: Int64],+ countsTowardTotals: Bool = true+ ) async {var removal = RemovalInProgress()await record(result, part: RemovalPart(source: source, sourceKey: sourceKey, tool: tool.rawValue), sizes: sizes, in: &removal)- finish(removal)+ finish(removal, countsTowardTotals: countsTowardTotals)}/// Records in History what one part of `removal` moved, and what it refused.@@ -195,7 +204,7 @@ final class RemovalHistoryStore {/// Tells what `removal` moved once every part of it is recorded: the bar's "Moved", VoiceOver, the lifetime/// totals, and Undo.- func finish(_ removal: RemovalInProgress) {+ func finish(_ removal: RemovalInProgress, countsTowardTotals: Bool = true) {guard !removal.records.isEmpty else { return }let moved = RemovalBatch(id: removal.batch,@@ -205,10 +214,12 @@ final class RemovalHistoryStore {)justMoved = movedAccessibilityNotification.Announcement(moved.movedAnnouncement).post()- stats?.add(- TrashResult(trashed: removal.records.map(\.trashedItem)),- sizes: [URL: Int64](measured: removal.records.map { ($0.originalURL, $0.size) })- )+ if countsTowardTotals {+ stats?.add(+ TrashResult(trashed: removal.records.map(\.trashedItem)),+ sizes: [URL: Int64](measured: removal.records.map { ($0.originalURL, $0.size) })+ )+ }registerUndo(of: removal.records, source: moved.title)}diff --git a/Peel/Model/SelfUninstall.swift b/Peel/Model/SelfUninstall.swiftindex 48173a52..77333aa8 100644--- a/Peel/Model/SelfUninstall.swift+++ b/Peel/Model/SelfUninstall.swift@@ -25,16 +25,27 @@ final class SelfUninstall {/// Removes Peel. The plan is made first, and the steps nothing can undo (unregistering the helper and the/// login item) come after, so a plan that cannot be made leaves Peel as it was. A quit is refused meanwhile,- /// since Peel ends itself once it has gone.- func run(installedApps: [InstalledApp], helper: HelperModel, recording record: (TrashResult) async -> Void = { _ in }) async {+ /// since Peel ends itself once it has gone. `work` is paused from the first of those steps, since what it does+ /// on its own would write Peel's files again, and resumed if Peel stays where it was.+ func run(+ installedApps: [InstalledApp],+ helper: HelperModel,+ pausing work: StandingWork,+ recording record: (TrashResult) async -> Void = { _ in }+ ) async {isRunning = truedefer { isRunning = false }await QuitGuard.shared.runRefusingQuit {- await remove(installedApps: installedApps, helper: helper, recording: record)+ await remove(installedApps: installedApps, helper: helper, pausing: work, recording: record)}}- private func remove(installedApps: [InstalledApp], helper: HelperModel, recording record: (TrashResult) async -> Void) async {+ private func remove(+ installedApps: [InstalledApp],+ helper: HelperModel,+ pausing work: StandingWork,+ recording record: (TrashResult) async -> Void+ ) async {let bundleURL = Bundle.main.bundleURLguard let app = await AppLibrary.inspect(bundleURL) else {failure = String(localized: "Peel couldn’t read its own files.")@@ -47,6 +58,7 @@ final class SelfUninstall {return}+ work.pause()let isRegistered = { [helper] in helper.status == .enabled || helper.status == .requiresApproval }var ledger = PrivilegedHelper.LedgerMove.noneif isRegistered() {@@ -54,6 +66,7 @@ final class SelfUninstall {await helper.uninstall()// A helper still registered would point into the Trash, so Peel moves only once the helper is gone.guard !isRegistered() else {+ work.resume()let reason = helper.failure?.reason ?? String(localized: "The helper couldn’t be removed, so Peel stayed where it was.")failure = ledger == .moved ? "\(reason)\n\n\(Self.ledgerInTheTrash)" : reasonreturn@@ -65,6 +78,7 @@ final class SelfUninstall {let result = await SelfRemoval.move(urls, app: bundleURL, folder: PeelFolder.url, using: TrashService(exclusions: exclusions), recording: record)guard result.trashed.contains(where: { $0.originalURL == bundleURL }) else {+ work.resume()let lines = result.failures.map { "\($0.url.abbreviatedPath)\n\($0.reason.explanation)" }failure = (lines + (ledger == .moved ? [Self.ledgerInTheTrash] : [])).joined(separator: "\n\n")returndiff --git a/Peel/PeelApp.swift b/Peel/PeelApp.swiftindex b6f6dd32..5b98889a 100644--- a/Peel/PeelApp.swift+++ b/Peel/PeelApp.swift@@ -50,7 +50,7 @@ struct PeelApp: App {@State private var intel = IntelLibrary()@State private var space: SpaceLibrary@State private var carrier: SelectionCarrier- @State private var background = BackgroundWork()+ @State private var background = StandingWork()@State private var hasLaunched = falseprivate let exclusions = ExclusionsStore.shared@@ -95,6 +95,7 @@ struct PeelApp: App {private func followFolders() async {for await _ in FolderWatch.changes(in: AppCatalog.defaultDirectories) {try? await Task.sleep(for: .seconds(1), tolerance: .milliseconds(250))+ guard !Task.isCancelled else { return }let before = library.revisionlet changed = await library.refresh()// Any write inside a bundle wakes this loop, so Homebrew and the rest run only when the app list changed.@@ -126,6 +127,7 @@ struct PeelApp: App {/// window's scene phase is no sign of that: on macOS a window stays active while another app is in front.private func followActivations() async {for await _ in NotificationCenter.default.notifications(named: NSApplication.didBecomeActiveNotification) {+ guard !Task.isCancelled else { return }helper.refresh()// `peel exclusions` may have changed the list while another app was in front.Task { await exclusions.load() }@@ -175,6 +177,7 @@ struct PeelApp: App {private func follow(_ tool: Tool, _ looked: @escaping @MainActor @Sendable () -> Looked?) async {for await value in Observations(looked) {+ guard !Task.isCancelled else { return }if let value {found.record(value, for: tool)}@@ -238,6 +241,7 @@ struct PeelApp: App {.environment(home).environment(history).environment(intel)+ .environment(background).environment(space).environment(carrier).environment(exclusions)@@ -334,6 +338,7 @@ struct PeelApp: App {.environment(homebrew).environment(history).environment(home)+ .environment(background)}.windowResizability(.contentSize)diff --git a/Peel/Views/Settings/SettingsView.swift b/Peel/Views/Settings/SettingsView.swiftindex 9acb0129..bb407aba 100644--- a/Peel/Views/Settings/SettingsView.swift+++ b/Peel/Views/Settings/SettingsView.swift@@ -106,6 +106,7 @@ private struct GeneralSettingsView: View {@Environment(HomebrewLibrary.self) private var homebrew@Environment(HelperModel.self) private var helper@Environment(RemovalHistoryStore.self) private var history+ @Environment(StandingWork.self) private var background@Environment(HomeModel.self) private var home@State private var selfUninstall = SelfUninstall()@State private var isConfirmingSelfRemoval = false@@ -333,8 +334,8 @@ private struct GeneralSettingsView: View {.confirmationDialog("Remove Peel from this Mac?", isPresented: $isConfirmingSelfRemoval) {Button("Remove Peel", role: .destructive) {Task {- await selfUninstall.run(installedApps: library.apps, helper: helper) { result in- await history.record(result, tool: .applications, source: "Peel", sizes: [:])+ await selfUninstall.run(installedApps: library.apps, helper: helper, pausing: background) { result in+ await history.record(result, tool: .applications, source: "Peel", sizes: [:], countsTowardTotals: false)}}}