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 the steps of an app's reset into PeelCore
Țugui Dragoșa882637a1f44
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift b/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swiftindex 7196d7ac..730628d8 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift@@ -74,8 +74,83 @@ public struct AppReset: Sendable {}/// True when moving `urls` is followed by a `defaults delete` of at least one preference domain.- public func clearsSettings(moving urls: [URL]) -> Bool {- !PreferenceCleanup.domains(for: urls, ownedBy: app.bundleIdentifier).isEmpty+ public func clearsSettings(moving urls: [URL], home: URL = .homeDirectory) -> Bool {+ !PreferenceCleanup.domains(for: urls, ownedBy: app.bundleIdentifier, home: home).isEmpty+ }++ /// What a reset did, or why it did nothing.+ public struct Outcome: Sendable {+ public enum Stop: Sendable, Equatable {+ case settingsNotSaved+ case appOpened+ }++ public var stop: Stop?+ public var backup: URL?+ public var result = TrashResult()+ public var askedToMove = 0+ public var clearedSettings = false+ public var privacy: PrivacyReset.Result?++ /// The copy Put Settings Back takes the settings from.+ public var settingsToPutBack: URL? { backup }+ }++ /// Copies the settings in `selection`, asks again whether the app is open, since the copy takes a moment, then+ /// moves the selection to the Trash and resets the privacy permissions when asked. Nothing moves when the copy+ /// fails or the app opened meanwhile, and the copy then stays.+ @concurrent+ public func run(+ _ selection: Set<URL>,+ resettingPrivacy: Bool,+ exclusions: Exclusions,+ isOpen: @Sendable () async -> Bool+ ) async -> Outcome {+ let app = app+ return await run(+ selection,+ resettingPrivacy: resettingPrivacy,+ through: TrashService(exclusions: exclusions),+ isOpen: isOpen,+ save: { await PreferenceBackup.save($0, for: app, exclusions: exclusions) },+ resetPrivacy: { await PrivacyReset.reset(bundleIdentifier: $0) }+ )+ }++ func run(+ _ selection: Set<URL>,+ resettingPrivacy: Bool,+ through service: TrashService,+ isOpen: @Sendable () async -> Bool,+ save: @Sendable ([URL]) async -> PreferenceBackup.Saved,+ resetPrivacy: @Sendable (String) async -> PrivacyReset.Result+ ) async -> Outcome {+ var outcome = Outcome()+ let urls = selected(selection)+ switch await save(urls) {+ case .failed:+ outcome.stop = .settingsNotSaved+ return outcome+ case .saved(let folder):+ outcome.backup = folder+ case .nothingToSave:+ break+ }+ guard await !isOpen() else {+ outcome.stop = .appOpened+ return outcome+ }+ outcome.result = await service.trash(urls, ownedBy: app.bundleIdentifier)+ outcome.askedToMove = urls.count+ outcome.clearedSettings = clearsSettings(+ moving: outcome.result.trashed.map(\.originalURL),+ home: service.environment.homeDirectory+ )+ // The app stays installed, so `tccutil` still finds it after the move.+ if resettingPrivacy, let identifier = app.bundleIdentifier {+ outcome.privacy = await resetPrivacy(identifier)+ }+ return outcome}/// Returns the selected items in the order the sheet lists them. Preference domains are forgotten only afterdiff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swiftindex 30ca299f..529102e0 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppResetTests.swift@@ -1,5 +1,6 @@import Foundation@testable import PeelCore+import Synchronizationimport Testingstruct AppResetTests {@@ -284,4 +285,118 @@ struct AppResetTests {#expect(reset.items.map(\.url.lastPathComponent) == ["com.example.app.plist"])#expect(AppReset.group(for: .plugIns) == nil)}++ private func service(in directory: borrowing TemporaryDirectory) throws -> TrashService {+ let trash = try directory.directory("Trash")+ return TrashService(environment: home(directory)) { url in+ let destination = trash.appending(path: url.lastPathComponent)+ try FileManager.default.moveItem(at: url, to: destination)+ return destination+ }+ }++ @Test func aResetCopiesTheSettingsThenMovesTheSelectionAndResetsThePermissionsAsked() async throws {+ let directory = try TemporaryDirectory()+ let settings = try directory.file("Library/Preferences/com.example.app.plist", bytes: 4096)+ try directory.file("Library/Caches/com.example.app/cache", bytes: 4096)+ let reset = await AppReset.prepare(app(), installedApps: [app()], environment: home(directory))+ let copy = try directory.directory("Copy")+ let asked = Mutex<[String]>([])++ let outcome = await reset.run(+ reset.suggestedSelection,+ resettingPrivacy: true,+ through: try service(in: directory),+ isOpen: { false },+ save: { _ in .saved(copy) },+ resetPrivacy: { identifier in+ asked.withLock { $0.append(identifier) }+ return .reset+ }+ )++ #expect(outcome.stop == nil)+ #expect(outcome.result.trashed.count == 2)+ #expect(outcome.askedToMove == 2)+ #expect(outcome.clearedSettings)+ #expect(outcome.settingsToPutBack == copy)+ #expect(outcome.privacy == .reset)+ #expect(asked.withLock { $0 } == ["com.example.app"])+ #expect(settings.isMissing)+ }++ @Test func aResetMovesNothingWhenTheSettingsCouldNotBeCopied() async throws {+ let directory = try TemporaryDirectory()+ let settings = try directory.file("Library/Preferences/com.example.app.plist", bytes: 4096)+ let reset = await AppReset.prepare(app(), installedApps: [app()], environment: home(directory))+ let asked = Mutex(false)++ let outcome = await reset.run(+ reset.suggestedSelection,+ resettingPrivacy: true,+ through: try service(in: directory),+ isOpen: { false },+ save: { _ in .failed },+ resetPrivacy: { _ in+ asked.withLock { $0 = true }+ return .reset+ }+ )++ #expect(outcome.stop == .settingsNotSaved)+ #expect(outcome.result.trashed.isEmpty)+ #expect(!asked.withLock { $0 })+ #expect(settings.isThere)+ }++ @Test func aResetMovesNothingWhenTheAppOpenedWhileItsSettingsWereCopied() async throws {+ let directory = try TemporaryDirectory()+ let settings = try directory.file("Library/Preferences/com.example.app.plist", bytes: 4096)+ let reset = await AppReset.prepare(app(), installedApps: [app()], environment: home(directory))+ let copy = try directory.directory("Copy")+ let asked = Mutex(false)++ let outcome = await reset.run(+ reset.suggestedSelection,+ resettingPrivacy: true,+ through: try service(in: directory),+ isOpen: { true },+ save: { _ in .saved(copy) },+ resetPrivacy: { _ in+ asked.withLock { $0 = true }+ return .reset+ }+ )++ #expect(outcome.stop == .appOpened)+ #expect(outcome.backup == copy)+ #expect(outcome.result.trashed.isEmpty)+ #expect(!asked.withLock { $0 })+ #expect(settings.isThere)+ }++ @Test func aResetLeavesThePermissionsAloneUnlessAsked() async throws {+ let directory = try TemporaryDirectory()+ try directory.file("Library/Caches/com.example.app/cache", bytes: 4096)+ let reset = await AppReset.prepare(app(), installedApps: [app()], environment: home(directory))+ let asked = Mutex(false)++ let outcome = await reset.run(+ reset.suggestedSelection,+ resettingPrivacy: false,+ through: try service(in: directory),+ isOpen: { false },+ save: { _ in .nothingToSave },+ resetPrivacy: { _ in+ asked.withLock { $0 = true }+ return .reset+ }+ )++ #expect(outcome.result.trashed.count == 1)+ #expect(outcome.privacy == nil)+ #expect(!asked.withLock { $0 })+ #expect(!outcome.clearedSettings)+ #expect(outcome.settingsToPutBack == nil)+ }}diff --git a/Peel/Model/ResetPlan.swift b/Peel/Model/ResetPlan.swiftindex 173b6796..844e3b97 100644--- a/Peel/Model/ResetPlan.swift+++ b/Peel/Model/ResetPlan.swift@@ -10,19 +10,9 @@ final class ResetPlan {/// The scan the sheet runs. A new scan, such as the one after the exclusions change, replaces the one before.let scanRun = ScanRun()private(set) var isResetting = false- private(set) var backup: URL?- private(set) var failures: [TrashFailure] = []- private(set) var didReset = false- /// True when the settings could not be backed up, so nothing was moved. The backup is what restores them- /// once the app has written new ones, which History cannot do.- private(set) var couldNotSaveSettings = false- private(set) var movedCount = 0- /// How many files the reset asked to move: a reset of privacy permissions alone asks for none.- private(set) var askedToMove = 0- private(set) var didClearSettings = false+ private(set) var outcome: AppReset.Outcome?/// Off until chosen: History can't bring the permissions back.var resetsPrivacy = false- private(set) var privacy: PrivacyReset.Result?/// Stored rather than computed, so the sheet can observe it: reading the workspace in a computed property/// gives Observation nothing to track. `refreshRunningState()` keeps it current.private(set) var isAppRunning = false@@ -64,6 +54,41 @@ final class ResetPlan {PrivacyReset.isAllowed(for: app)}+ var didReset: Bool {+ outcome.map { $0.stop == nil } ?? false+ }++ /// True when the settings could not be backed up, so nothing was moved. The backup is what restores them+ /// once the app has written new ones, which History cannot do.+ var couldNotSaveSettings: Bool {+ outcome?.stop == .settingsNotSaved+ }++ var backup: URL? {+ outcome?.settingsToPutBack+ }++ var failures: [TrashFailure] {+ outcome?.result.failures ?? []+ }++ var movedCount: Int {+ outcome?.result.trashed.count ?? 0+ }++ /// How many files the reset asked to move: a reset of privacy permissions alone asks for none.+ var askedToMove: Int {+ outcome?.askedToMove ?? 0+ }++ var didClearSettings: Bool {+ outcome?.clearedSettings ?? false+ }++ var privacy: PrivacyReset.Result? {+ outcome?.privacy+ }+/// Nothing is, until the scan has said what the reset would take: `performReset()` has nothing to go on before.var hasAnythingToReset: Bool {reset != nil && (!selectedURLs.isEmpty || (resetsPrivacy && canResetPrivacy))@@ -90,43 +115,24 @@ final class ResetPlan {}/// Backs up the app's settings, then moves the selection to the Trash, which also makes cfprefsd forget the- /// app's preference domains. Checks that the app is not running before the copy and again before the move,- /// since the copy takes a moment: an app opened meanwhile would have its files moved from under it, and would- /// write its settings back when it quits. Then nothing moves, and the copy stays.+ /// app's preference domains. The app must be closed before the copy and still be after it: an app opened+ /// meanwhile would have its files moved from under it, and would write its settings back when it quits.func performReset() async -> TrashResult {refreshRunningState()guard let reset, !isAppRunning else { return TrashResult() }isResetting = truedefer { isResetting = false }- let urls = reset.selected(selectedURLs)- switch await PreferenceBackup.save(urls, for: app, exclusions: ExclusionsStore.shared.exclusions) {- case .failed:- couldNotSaveSettings = true- return TrashResult()- case .saved(let folder):- backup = folder- case .nothingToSave:- backup = nil- }- couldNotSaveSettings = false- refreshRunningState()- guard !isAppRunning else { return TrashResult() }- let result = await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash(- urls,- ownedBy: app.bundleIdentifier- )- failures = result.failures- movedCount = result.trashed.count- askedToMove = urls.count- didClearSettings = reset.clearsSettings(moving: result.trashed.map(\.originalURL))- // The app stays installed, so `tccutil` still finds it after the move.- privacy = nil- if resetsPrivacy, canResetPrivacy, let identifier = app.bundleIdentifier {- privacy = await PrivacyReset.reset(bundleIdentifier: identifier)+ let outcome = await reset.run(+ selectedURLs,+ resettingPrivacy: resetsPrivacy && canResetPrivacy,+ exclusions: ExclusionsStore.shared.exclusions+ ) { @MainActor in+ self.refreshRunningState()+ return self.isAppRunning}- didReset = true- return result+ self.outcome = outcome+ return outcome.result}/// Puts the settings saved in `backup` back, unless the app is open, which would write its own over them.