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
Put Back saves the settings an app has now, and asks first
Țugui Dragoșdb6bf47b15d6
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c03eb9f2..d0781f4c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -9,13 +9,13 @@ from happening, and they are not up for negotiation.## The rule everything else serves**Nothing of the user's is ever deleted for good.** Every removal goes to the Trash through `TrashService` and is-recorded, so History can put it back. No code path in Peel deletes anything of the user's, and a change that adds-one won't be accepted; the one file Peel deletes outright is its own list of refusals, when-`peel history --refused --clear` is asked to forget it. Three things Peel starts can't be undone by History, and-each says so where the user confirms it: Homebrew's own uninstall and clean up, and resetting an app's privacy-permissions. `defaults delete` for an app's preferences runs only once their file is in the Trash, and a reset-exports the domain first, so putting the file back undoes it. Every `brew` call runs with-`HOMEBREW_NO_INSTALL_CLEANUP`, so an upgrade never cleans up on its own.+recorded, so History can put it back. No code path in Peel deletes anything of the user's, and a change that adds one+won't be accepted; the one file Peel deletes outright is its own list of refusals, when `peel history --refused --clear`+is asked to forget it. Three things Peel starts can't be undone by History, and each says so where the user confirms it:+Homebrew's own uninstall and clean up, and resetting an app's privacy permissions. `defaults delete` for an app's+preferences runs only once their file is in the Trash, and a reset exports the domain first, so putting the file back+undoes it; putting saved settings back clears a domain only once it has been saved as a copy of its own, and asks first.+Every `brew` call runs with `HOMEBREW_NO_INSTALL_CLEANUP`, so an upgrade never cleans up on its own.## What you needdiff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex dd618ff1..2bcc451c 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -75915,6 +75915,112 @@}}},+ "Peel couldn’t save the settings %@ has now, so it put nothing back." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel nemohl uložit současná nastavení aplikace %@, a proto nic nevrátil zpět."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel konnte die aktuellen Einstellungen von „%@“ nicht sichern, daher wurde nichts zurückgelegt."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel no ha podido guardar los ajustes que %@ tiene ahora, así que no ha restaurado nada."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel n’a pas pu enregistrer les réglages actuels de %@ : il n’a donc rien remis en place."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel non è riuscito a salvare le impostazioni attuali di %@, quindi non ha ripristinato nulla."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peelは“%@”の現在の設定を保存できなかったため、何も戻しませんでした。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel이 ‘%@’의 현재 설정을 저장할 수 없었으므로 아무것도 되돌려 놓지 않았습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel kon de huidige instellingen van %@ niet bewaren, dus er is niets teruggezet."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel nie mógł zachować obecnych ustawień aplikacji %@, więc niczego nie przywrócił."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O Peel não conseguiu salvar os ajustes atuais de %@, então não colocou nada de volta."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel nu a putut salva configurările pe care %@ le are acum, așa că nu a pus nimic înapoi."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel не удалось сохранить текущие настройки приложения «%@», поэтому он ничего не восстановил."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel kunde inte spara de nuvarande inställningarna för %@, så inget lades tillbaka."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel, %@ uygulamasının şu anki ayarlarını kaydedemedi, bu yüzden hiçbir şeyi yerine koymadı."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel не вдалося зберегти поточні налаштування програми «%@», тому нічого не повернуто."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel未能保存“%@”当前的设置,因此没有放回任何内容。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel無法儲存「%@」目前的設定,因此沒有還原任何設定。"+ }+ }+ }+ },"Peel didn’t look everywhere" : {"localizations" : {"cs" : {@@ -76445,6 +76551,112 @@}}},+ "Peel first saves the settings %@ has now, as a copy of their own, then puts these in their place." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel nejprve uloží současná nastavení aplikace %@ jako samostatnou kopii a pak je nahradí těmito."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel sichert zuerst die aktuellen Einstellungen von „%@“ als eigene Kopie und setzt dann die gesicherten an ihre Stelle."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel guarda primero en una copia aparte los ajustes que %@ tiene ahora y después los sustituye por estos."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel enregistre d’abord les réglages actuels de %@ dans une copie distincte, puis les remplace par ces réglages."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel salva prima le impostazioni attuali di %@ in una copia a parte, poi le sostituisce con queste."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peelはまず、“%@”の現在の設定を別のコピーとして保存してから、これらの設定に置き換えます。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel은 먼저 ‘%@’의 현재 설정을 별도의 복사본으로 저장한 다음, 그 자리에 이 설정을 되돌려 놓습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel bewaart eerst de huidige instellingen van %@ als een eigen kopie, en vervangt ze daarna door deze instellingen."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel najpierw zachowuje obecne ustawienia aplikacji %@ jako osobną kopię, a potem przywraca te w ich miejsce."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O Peel primeiro salva os ajustes atuais de %@, como uma cópia à parte, e depois coloca estes no lugar deles."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel salvează mai întâi configurările pe care %@ le are acum, ca o copie separată, apoi le pune pe acestea în locul lor."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel сначала сохраняет текущие настройки приложения «%@» в виде отдельной копии, а затем заменяет их этими."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel sparar först de nuvarande inställningarna för %@ som en egen kopia och ersätter dem sedan med de här."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel önce %@ uygulamasının şu anki ayarlarını ayrı bir kopya olarak kaydeder, sonra bu ayarları onların yerine koyar."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel спершу збереже поточні налаштування програми «%@» як окрему копію, а потім замінить їх цими."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel会先将“%@”当前的设置单独保存为一份副本,再用这些设置替换它们。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel會先將「%@」目前的設定另存為一份副本,再用這些設定取代它們。"+ }+ }+ }+ },"Peel found no apps in the Applications folders, which on a Mac in use means it couldn’t read them." : {"localizations" : {"cs" : {@@ -84890,108 +85102,220 @@}}},- "Puts these settings back. Whatever the app set since is cleared first." : {+ "Put back the settings saved for %@ on %@?" : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vrátit zpět nastavení uložená pro aplikaci %@ dne %@?"+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Die am %2$@ für „%1$@“ gesicherten Einstellungen zurücklegen?"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "Put back the settings saved for %1$@ on %2$@?"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "¿Restaurar los ajustes de %@ guardados el %@?"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Remettre les réglages de %@ enregistrés le %@ ?"+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vuoi ripristinare le impostazioni salvate per %@ in data %@?"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%2$@に“%1$@”用に保存された設定を戻しますか?"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%2$@에 저장된 ‘%1$@’의 설정을 되돌려 놓겠습니까?"+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Instellingen van %@, bewaard op %@, terugzetten?"+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Przywrócić ustawienia aplikacji %@ zachowane %@?"+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Colocar de volta os ajustes salvos de %@ em %@?"+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Puneți înapoi configurările salvate pentru %@ pe %@?"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Восстановить настройки приложения «%@», сохраненные %@?"+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vill du lägga tillbaka inställningarna som sparades för %@ den %@?"+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ için %@ tarihinde kaydedilen ayarlar yerine konsun mu?"+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Повернути назад налаштування програми «%@», збережені %@?"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要将于%2$@为“%1$@”保存的设置放回原处吗?"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要將為「%@」於%@儲存的設定還原嗎?"+ }+ }+ }+ },+ "Puts these settings back, after saving the ones the app has now." : {"localizations" : {"cs" : {"stringUnit" : {"state" : "translated",- "value" : "Vrátí tato nastavení zpět. Cokoli aplikace mezitím nastavila, se nejprve vymaže."+ "value" : "Vrátí tato nastavení zpět, ale nejprve uloží současná nastavení aplikace."}},"de" : {"stringUnit" : {"state" : "translated",- "value" : "Legt diese Einstellungen zurück. Was die App seitdem festgelegt hat, wird zuerst entfernt."+ "value" : "Legt diese Einstellungen zurück und sichert vorher die aktuellen Einstellungen der App."}},"es" : {"stringUnit" : {"state" : "translated",- "value" : "Restaura estos ajustes. Antes se borra todo lo que la app haya ajustado desde entonces."+ "value" : "Restaura estos ajustes después de guardar los que la app tiene ahora."}},"fr" : {"stringUnit" : {"state" : "translated",- "value" : "Remet ces réglages en place. Ce que l’app a défini depuis est d’abord effacé."+ "value" : "Remet ces réglages en place, après avoir enregistré les réglages actuels de l’app."}},"it" : {"stringUnit" : {"state" : "translated",- "value" : "Ripristina queste impostazioni. Prima viene cancellato tutto ciò che l’app ha impostato nel frattempo."+ "value" : "Ripristina queste impostazioni, dopo aver salvato quelle attuali dell’app."}},"ja" : {"stringUnit" : {"state" : "translated",- "value" : "これらの設定を戻します。その後にアプリが設定した内容は、先に消去されます。"+ "value" : "アプリの現在の設定を保存してから、これらの設定を戻します。"}},"ko" : {"stringUnit" : {"state" : "translated",- "value" : "이 설정을 되돌려 놓습니다. 그 이후에 앱이 설정한 내용은 먼저 지워집니다."+ "value" : "앱의 현재 설정을 저장한 후 이 설정을 되돌려 놓습니다."}},"nl" : {"stringUnit" : {"state" : "translated",- "value" : "Zet deze instellingen terug. Wat de app sindsdien heeft ingesteld, wordt eerst gewist."+ "value" : "Zet deze instellingen terug, nadat de huidige instellingen van de app zijn bewaard."}},"pl" : {"stringUnit" : {"state" : "translated",- "value" : "Przywraca te ustawienia. Wszystko, co aplikacja ustawiła od tego czasu, zostanie najpierw wyczyszczone."+ "value" : "Przywraca te ustawienia po zachowaniu tych, które aplikacja ma teraz."}},"pt" : {"stringUnit" : {"state" : "translated",- "value" : "Coloca estes ajustes de volta. O que o app definiu desde então é limpo primeiro."+ "value" : "Coloca estes ajustes de volta, depois de salvar os atuais do app."}},"ro" : {"stringUnit" : {"state" : "translated",- "value" : "Pune înapoi aceste configurări. Tot ce a configurat aplicația între timp este eliminat mai întâi."+ "value" : "Pune înapoi aceste configurări, după ce le salvează pe cele pe care aplicația le are acum."}},"ru" : {"stringUnit" : {"state" : "translated",- "value" : "Восстанавливает эти настройки. Все, что приложение настроило с тех пор, сначала очищается."+ "value" : "Восстанавливает эти настройки, предварительно сохранив текущие настройки приложения."}},"sv" : {"stringUnit" : {"state" : "translated",- "value" : "Lägger tillbaka de här inställningarna. Det som appen har ställt in sedan dess rensas först."+ "value" : "Lägger tillbaka de här inställningarna efter att ha sparat appens nuvarande inställningar."}},"tr" : {"stringUnit" : {"state" : "translated",- "value" : "Bu ayarları yerine koyar. Uygulamanın o zamandan beri ayarladığı her şey önce temizlenir."+ "value" : "Uygulamanın şu anki ayarlarını kaydettikten sonra bu ayarları yerine koyar."}},"uk" : {"stringUnit" : {"state" : "translated",- "value" : "Повертає ці налаштування. Усе, що програма змінила відтоді, спершу буде очищено."+ "value" : "Повертає ці налаштування, спершу зберігши поточні."}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "将这些设置放回原处。App此后设定的内容会先被清除。"+ "value" : "先保存App当前的设置,再将这些设置放回原处。"}},"zh-Hant" : {"stringUnit" : {"state" : "translated",- "value" : "還原這些設定。App在那之後設定的內容會先清除。"+ "value" : "先儲存App目前的設定,再還原這些設定。"}}}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/PreferenceBackup.swift b/Packages/PeelCore/Sources/PeelCore/Removal/PreferenceBackup.swiftindex 3041de0e..62518315 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/PreferenceBackup.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/PreferenceBackup.swift@@ -40,8 +40,20 @@ public enum PreferenceBackup {/// cannot be copied, the result is `failed` and nothing may be cleared: the copy is what makes clearing safe.@concurrentstatic func save(_ urls: [URL], for app: InstalledApp, in directory: URL, through service: TrashService = TrashService(), run: Run) async -> Saved {+ let domains = PreferenceCleanup.domains(for: urls, ownedBy: app.bundleIdentifier)+ return await save(domains, of: app.bundleIdentifier, in: directory, through: service, run: run)+ }++ /// Exports every one of `candidates` that exists into a new folder in `directory`, named for `bundleIdentifier`.+ private static func save(+ _ candidates: [PreferenceCleanup.Domain],+ of bundleIdentifier: String,+ in directory: URL,+ through service: TrashService,+ run: Run+ ) async -> Saved {var domains: [PreferenceCleanup.Domain] = []- for domain in PreferenceCleanup.domains(for: urls, ownedBy: app.bundleIdentifier) {+ for domain in candidates {switch await run(domain.command("read")) {case .yes: domains.append(domain)case .no: continue@@ -53,9 +65,9 @@ public enum PreferenceBackup {// The bundle identifier comes from the app itself and becomes part of a folder name, so it must have the// reverse DNS shape `copies` reads back, which rules out a `/`.guard- Identifier.isReverseDNS(app.bundleIdentifier),+ Identifier.isReverseDNS(bundleIdentifier),(try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)) != nil,- let folder = newFolder(for: app.bundleIdentifier, in: directory)+ let folder = newFolder(for: bundleIdentifier, in: directory)else { return .failed }for domain in domains {@@ -73,40 +85,58 @@ public enum PreferenceBackup {}/// What putting a saved copy back came to.- public struct Restored: Sendable, Equatable {+ public enum Restored: Sendable, Equatable {/// Every domain in the copy went back.- public let isComplete: Bool- /// A domain was cleared and then did not go back, so the app starts that part from scratch.- public let clearedSome: Bool+ case complete+ /// Not every domain went back. `clearedSome`: one was cleared and then did not go back, so the app starts+ /// that part from scratch.+ case incomplete(clearedSome: Bool)+ /// The settings the app has now could not be saved, so nothing was cleared or put back.+ case notSaved++ public var isComplete: Bool {+ if case .complete = self { true } else { false }+ }}- /// Puts the domains saved in `folder` back with `defaults import`. The app must not be running, or it- /// overwrites them. `defaults import` merges rather than replaces, so each domain is deleted first.+ /// Puts the domains saved in `folder` back with `defaults import`, once the settings the app has now are saved+ /// in `directory` as a copy of their own: what it set since, a license entered again or an account, would+ /// otherwise be gone. The app must not be running, or it overwrites them. `defaults import` merges rather than+ /// replaces, so each domain is deleted first.@concurrent- public static func restore(from folder: URL) async -> Restored {- await restore(from: folder, run: run)- }-- static func restore(from folder: URL, run: Run) async -> Restored {+ public static func restore(+ from folder: URL,+ of bundleIdentifier: String,+ in directory: URL = PreferenceBackup.defaultDirectory,+ exclusions: Exclusions = .none+ ) async -> Restored {+ let service = TrashService(exclusions: exclusions)+ return await restore(from: folder, of: bundleIdentifier, in: directory, through: service, run: run)+ }++ static func restore(+ from folder: URL,+ of bundleIdentifier: String,+ in directory: URL,+ through service: TrashService = TrashService(),+ run: Run+ ) async -> Restored {let files = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []let saved = files.filter { $0.pathExtension == "plist" }.compactMap { file in domain(from: file.lastPathComponent).map { ($0, file) } }- guard !saved.isEmpty else { return Restored(isComplete: false, clearedSome: false) }- var isComplete = true+ // A copy that is not a readable property list would put nothing back once the delete had cleared the+ // settings in use, so it is refused before anything is cleared.+ let readable = saved.filter { isAPropertyList($0.1) }+ guard !readable.isEmpty else { return .incomplete(clearedSome: false) }+ let current = await save(readable.map(\.0), of: bundleIdentifier, in: directory, through: service, run: run)+ guard current != .failed else { return .notSaved }var clearedSome = false- for (domain, file) in saved {- // A copy that is not a readable property list would put nothing back once the delete had cleared the- // settings in use, so it is refused before anything is cleared.- guard isAPropertyList(file) else {- isComplete = false- continue- }+ for (domain, file) in readable {_ = await run(domain.command("delete"))if await run(domain.command("import", file.path(percentEncoded: false))) != .yes {- isComplete = falseclearedSome = true}}- return Restored(isComplete: isComplete, clearedSome: clearedSome)+ return readable.count == saved.count && !clearedSome ? .complete : .incomplete(clearedSome: clearedSome)}/// Whether `file` holds a property list whose top level is a dictionary, which is what `defaults import` reads.diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swiftindex 4e31b7e8..f498e6bc 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift@@ -219,26 +219,77 @@ struct RemovalHygieneTests {/// before anything is cleared.@Test func aCopyThatCannotBeReadClearsNothing() async throws {let directory = try TemporaryDirectory()- let folder = try directory.directory("com.example.app 2026-09-24 101500")+ let backups = try directory.directory("Backups")+ let folder = try directory.directory("Backups/com.example.app 2026-09-24 101500")let good = try PropertyListSerialization.data(fromPropertyList: ["key": "value"], format: .xml, options: 0)try good.write(to: folder.appending(path: "com.example.app.plist"))try Data("not a property list".utf8).write(to: folder.appending(path: "com.example.helper.plist"))let asked = Mutex<[[String]]>([])let run: PreferenceBackup.Run = { arguments inasked.withLock { $0.append(arguments) }- return .yes+ return Self.exporting(arguments)}- let restored = await PreferenceBackup.restore(from: folder, run: run)+ let restored = await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, run: run)- #expect(restored == PreferenceBackup.Restored(isComplete: false, clearedSome: false), "a copy that could not be read was reported as put back, or as cleared")+ #expect(restored == .incomplete(clearedSome: false), "a copy that could not be read was reported as put back, or as cleared")let commands = asked.withLock { $0 }#expect(commands.contains(["delete", "com.example.app"]))#expect(!commands.contains { $0.contains("com.example.helper") }, "the settings in use were cleared for a copy that could not go back")// An import that fails after the delete has cleared that domain, and the result says so.- let failingImport: PreferenceBackup.Run = { arguments in arguments.first == "import" ? .no : .yes }- #expect(await PreferenceBackup.restore(from: folder, run: failingImport) == PreferenceBackup.Restored(isComplete: false, clearedSome: true))+ let failingImport: PreferenceBackup.Run = { arguments in arguments.first == "import" ? .no : Self.exporting(arguments) }+ #expect(await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, run: failingImport) == .incomplete(clearedSome: true))+ }++ /// Put Back replaces what the app set since the reset, which may be a license entered again, so those settings+ /// are saved first, as a copy of their own, and only then cleared.+ @Test func puttingBackSavesTheSettingsInUseFirst() async throws {+ let directory = try TemporaryDirectory()+ let backups = try directory.directory("Backups")+ let folder = try directory.directory("Backups/com.example.app 2026-09-24 101500")+ let good = try PropertyListSerialization.data(fromPropertyList: ["key": "value"], format: .xml, options: 0)+ try good.write(to: folder.appending(path: "com.example.app.plist"))+ let asked = Mutex<[[String]]>([])+ let run: PreferenceBackup.Run = { arguments in+ asked.withLock { $0.append(arguments) }+ return Self.exporting(arguments)+ }++ let restored = await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, run: run)++ #expect(restored == .complete)+ let copies = PreferenceBackup.copies(in: backups)+ #expect(copies.count == 2, "the settings in use were not kept as a copy of their own")+ let previous = try #require(copies.first { $0.folder != folder })+ #expect(FileManager.default.fileExists(atPath: previous.folder.appending(path: "com.example.app.plist").path(percentEncoded: false)))+ let verbs = asked.withLock { $0 }.map(\.[0])+ #expect(verbs == ["read", "export", "delete", "import"], "cleared before the settings in use were saved")+ }++ /// When the settings in use cannot be saved, nothing is cleared, and the saved copy is not put back.+ @Test func nothingIsClearedWhenTheSettingsInUseCannotBeSaved() async throws {+ let directory = try TemporaryDirectory()+ let backups = try directory.directory("Backups")+ let folder = try directory.directory("Backups/com.example.app 2026-09-24 101500")+ let good = try PropertyListSerialization.data(fromPropertyList: ["key": "value"], format: .xml, options: 0)+ try good.write(to: folder.appending(path: "com.example.app.plist"))+ let asked = Mutex<[[String]]>([])+ let run: PreferenceBackup.Run = { arguments in+ asked.withLock { $0.append(arguments) }+ return arguments.first == "export" ? .no : .yes+ }++ #expect(await PreferenceBackup.restore(from: folder, of: "com.example.app", in: backups, run: run) == .notSaved)+ #expect(!asked.withLock { $0 }.contains { $0.first == "delete" || $0.first == "import" })+ }++ /// A stand-in for `defaults` that answers yes, and writes the file an `export` names, as the real one does.+ private static func exporting(_ arguments: [String]) -> PreferenceBackup.Answer {+ if arguments.first == "export", let file = arguments.last {+ FileManager.default.createFile(atPath: file, contents: Data())+ }+ return .yes}/// The copy is what makes `defaults delete` safe to run, so a copy that could not be made must stop thediff --git a/Peel/Model/ResetPlan.swift b/Peel/Model/ResetPlan.swiftindex 5d3e16f0..0b51c547 100644--- a/Peel/Model/ResetPlan.swift+++ b/Peel/Model/ResetPlan.swift@@ -119,7 +119,9 @@ final class ResetPlan {func putSettingsBack() async -> Bool {refreshRunningState()guard let backup, !isAppRunning else { return false }- return await PreferenceBackup.restore(from: backup).isComplete+ return await PreferenceBackup.restore(+ from: backup, of: app.bundleIdentifier, exclusions: ExclusionsStore.shared.exclusions+ ).isComplete}/// Quits the app and the helpers it ships, so nothing writes its settings again while they are cleared.diff --git a/Peel/Views/Settings/SavedSettingsSection.swift b/Peel/Views/Settings/SavedSettingsSection.swiftindex 5da96581..3fcbfff8 100644--- a/Peel/Views/Settings/SavedSettingsSection.swift+++ b/Peel/Views/Settings/SavedSettingsSection.swift@@ -11,6 +11,7 @@ struct SavedSettingsSection: View {@State private var workingOn: PreferenceBackup.Copy.ID?@State private var failure: Failure?@State private var copyToTrash: PreferenceBackup.Copy?+ @State private var copyToPutBack: PreferenceBackup.Copy?/// The copies whose app, or a copy of it writing the same settings, is running. Stored and read again on every/// launch and quit, because a read of the workspace while drawing gives Observation nothing to follow.@State private var openApps: Set<String> = []@@ -36,6 +37,14 @@ struct SavedSettingsSection: View {.onReceive(NSWorkspace.shared.publisher(for: \.runningApplications)) { _ inrefreshOpenApps()}+ .confirmationDialog(putBackQuestion, isPresented: isAskingToPutBack, presenting: copyToPutBack) { copy in+ Button("Put Back") {+ Task { await putBack(copy, named: library.name(forBundleIdentifier: copy.bundleIdentifier)) }+ }+ Button("Cancel", role: .cancel) {}+ } message: { copy in+ Text("Peel first saves the settings \(library.name(forBundleIdentifier: copy.bundleIdentifier)) has now, as a copy of their own, then puts these in their place.")+ }.confirmationDialog(trashQuestion, isPresented: isAskingToTrash, presenting: copyToTrash) { copy inButton("Move to Trash") {Task { await moveToTrash(copy, named: library.name(forBundleIdentifier: copy.bundleIdentifier)) }@@ -55,10 +64,10 @@ struct SavedSettingsSection: View {return LabeledContent {HStack(spacing: 8) {Button("Put Back") {- Task { await putBack(copy, named: name) }+ copyToPutBack = copy}.disabled(isOpen)- .help(isOpen ? Text("Quit \(name) first, or it can write its own settings over these.") : Text("Puts these settings back. Whatever the app set since is cleared first."))+ .help(isOpen ? Text("Quit \(name) first, or it can write its own settings over these.") : Text("Puts these settings back, after saving the ones the app has now."))Button("Show in Finder", systemImage: "folder") {NSWorkspace.shared.activateFileViewerSelecting([copy.folder])}@@ -106,14 +115,23 @@ struct SavedSettingsSection: View {}workingOn = copy.iddefer { workingOn = nil }- let restored = await PreferenceBackup.restore(from: copy.folder)- if !restored.isComplete {+ let restored = await PreferenceBackup.restore(+ from: copy.folder, of: copy.bundleIdentifier, exclusions: ExclusionsStore.shared.exclusions+ )+ // The settings the app had until now may have become a copy of their own.+ reload()+ switch restored {+ case .complete:+ break+ case .incomplete(let clearedSome):failure = Failure(title: String(localized: "Not all of the settings saved for \(name) could be put back."),- message: restored.clearedSome+ message: clearedSome? String(localized: "The settings that didn’t go back were cleared first, so the app starts them from scratch. The copy is still here to try again."): "")+ case .notSaved:+ failure = Failure(title: String(localized: "Peel couldn’t save the settings \(name) has now, so it put nothing back."), message: "")}}@@ -136,6 +154,19 @@ struct SavedSettingsSection: View {return Text("Move the settings saved for \(name) on \(copy.date, format: .dateTime.day().month().year().hour().minute()) to the Trash?")}+ private var putBackQuestion: Text {+ guard let copy = copyToPutBack else { return Text(verbatim: "") }+ let name = library.name(forBundleIdentifier: copy.bundleIdentifier)+ return Text("Put back the settings saved for \(name) on \(copy.date, format: .dateTime.day().month().year().hour().minute())?")+ }++ private var isAskingToPutBack: Binding<Bool> {+ Binding(+ get: { copyToPutBack != nil },+ set: { if !$0 { copyToPutBack = nil } }+ )+ }+private var isAskingToTrash: Binding<Bool> {Binding(get: { copyToTrash != nil },diff --git a/SAFETY.md b/SAFETY.mdindex 203d5253..44fd54cb 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -233,12 +233,13 @@ start over in Settings, `peel` refuses, and the file it could not read is kept bA reset clears an app's settings and never the app itself. It lists only files that are certainly that app's, and theapp has to be quit, both when the reset starts and when saved settings are put back. Before anything moves, Peel savesthe app's settings, and if that copy fails, nothing moves; Settings lists the saved copies, where each can be put back-or cleared, since one can hold a license key, and they stay until you clear them. What the app keeps for you (its-Application Support folder, group containers, and application scripts) goes only when you select it, and is never-offered for Mail, Messages, Notes, or Photos. Inside a sandboxed app's container, a reset touches only the app's-preferences, saved state, caches, logs, and web data, never `Documents`, `Application Support`, or-`Autosave Information`; web data, which signs you out of websites, is offered but never selected for you. A folder that-holds a wallet's keys is never offered, even among those: BlueWallet keeps its wallet in its container's caches.+or cleared, since one can hold a license key, and they stay until you clear them. Putting one back asks first, and saves+the settings the app has now as a copy of their own before it replaces them. What the app keeps for you (its Application+Support folder, group containers, and application scripts) goes only when you select it, and is never offered for Mail,+Messages, Notes, or Photos. Inside a sandboxed app's container, a reset touches only the app's preferences, saved state,+caches, logs, and web data, never `Documents`, `Application Support`, or `Autosave Information`; web data, which signs+you out of websites, is offered but never selected for you. A folder that holds a wallet's keys is never offered, even+among those: BlueWallet keeps its wallet in its container's caches.## The helper that runs as root