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
The Not Moved list keeps whole removals and says when it fails
Țugui Dragoș9e027deb583f
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 040c9335..2ed63e8f 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -88094,6 +88094,112 @@}}},+ "Peel kept the old file and continued with what it could still read." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel starý soubor ponechal a pokračoval s tím, co se ještě dalo přečíst."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel hat die alte Datei behalten und mit dem weitergemacht, was noch lesbar war."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel ha conservado el archivo antiguo y ha seguido con lo que aún podía leer."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel a conservé l’ancien fichier et a continué avec ce qu’il pouvait encore lire."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel ha conservato il vecchio file ed è andato avanti con ciò che riusciva ancora a leggere."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peelは古いファイルを保管し、読み取れた部分で処理を続けました。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel은 이전 파일을 보관한 채 아직 읽을 수 있는 내용으로 계속 진행했습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel heeft het oude bestand bewaard en is verdergegaan met wat nog leesbaar was."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel zachował stary plik i korzysta z tego, co dało się jeszcze odczytać."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O Peel guardou o arquivo antigo e continuou com o que ainda conseguia ler."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel a păstrat fișierul vechi și a continuat cu ce a mai putut citi."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel сохранил старый файл и продолжил работу с тем, что еще смог прочитать."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel behöll den gamla filen och fortsatte med det som fortfarande gick att läsa."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel eski dosyayı sakladı ve hâlâ okuyabildikleriyle devam etti."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel зберегла старий файл і працює далі з тим, що ще вдалося прочитати."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel保留了旧文件,并继续使用其中仍可读取的部分。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel保留了舊檔案,並以仍可讀取的內容繼續運作。"+ }+ }+ }+ },"Peel kept the old file and continued with what it could still read. Items already in the Trash are still there: you can drag them back out in Finder." : {"localizations" : {"cs" : {@@ -89538,6 +89644,112 @@}}},+ "Peel leaves the file as it is and adds nothing to it, since it is the only record of what stayed." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel soubor ponechává tak, jak je, a nic do něj nepřidává, protože je to jediný záznam o tom, co zůstalo."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel lässt die Datei, wie sie ist, und fügt ihr nichts hinzu, da sie die einzige Aufzeichnung dessen ist, was geblieben ist."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel deja el archivo tal como está y no le añade nada, ya que es el único registro de lo que se quedó sin trasladar."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel laisse le fichier tel quel et n’y ajoute rien, car c’est la seule trace de ce qui est resté en place."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel lascia il file com’è e non vi aggiunge nulla, perché è l’unico registro di ciò che è rimasto."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "このファイルは残った項目の唯一の記録であるため、Peelはファイルをそのままにし、何も書き加えません。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel은 파일을 그대로 두고 아무것도 추가하지 않습니다. 이 파일이 그대로 남은 항목에 대한 유일한 기록이기 때문입니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel laat het bestand zoals het is en voegt er niets aan toe, omdat het de enige registratie is van wat er is blijven staan."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel zostawia plik bez zmian i nic do niego nie dopisuje, bo to jedyny zapis tego, co zostało na miejscu."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O Peel deixa o arquivo como está e não acrescenta nada a ele, pois é o único registro do que permaneceu."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel lasă fișierul așa cum este și nu adaugă nimic în el, deoarece este singura evidență a ceea ce a rămas pe loc."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel оставляет файл как есть и ничего в него не добавляет, поскольку это единственная запись о том, что осталось на месте."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel lämnar filen som den är och lägger inte till något i den, eftersom den är den enda förteckningen över det som blev kvar."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel dosyayı olduğu gibi bırakır ve ona hiçbir şey eklemez, çünkü yerinde kalanların tek kaydı odur."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel лишає файл без змін і нічого до нього не додає, бо лише в ньому записано те, що лишилося на місці."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel会保持该文件原样,不向其中添加任何内容,因为它是哪些项目留在原处的唯一记录。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel會保持檔案原樣,不會加入任何內容,因為這是留在原處之項目的唯一記錄。"+ }+ }+ }+ },"Peel lists at most ^[%lld file](inflect: true), yours first and largest first. Narrow the search to see the rest." : {"localizations" : {"cs" : {@@ -121702,6 +121914,324 @@}}},+ "The Not Moved list can’t be read" : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seznam Nepřesunuto nelze přečíst"+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Die Liste „Nicht verschoben“ kann nicht gelesen werden"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "No se puede leer la lista “Sin trasladar”"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Impossible de lire la liste « Non déplacés »"+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Impossibile leggere l’elenco “Non spostati”"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "“移動されなかった項目”のリストを読み取れません"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "‘이동되지 않음’ 목록을 읽을 수 없음"+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "De lijst 'Niet verplaatst' kan niet worden gelezen"+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nie można odczytać listy „Nie przeniesiono”"+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Não é possível ler a lista “Não Movidos”"+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Lista „Nu au fost mutate” nu poate fi citită"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не удается прочитать список «Не перемещено»"+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Listan Inte flyttat kan inte läsas"+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Taşınmayanlar listesi okunamıyor"+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не вдається прочитати список «Не переміщено»"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法读取“未移动”列表"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "無法讀取「未移動」清單"+ }+ }+ }+ },+ "The Not Moved list couldn’t be saved" : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seznam Nepřesunuto se nepodařilo uložit"+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Die Liste „Nicht verschoben“ konnte nicht gesichert werden"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "No se ha podido guardar la lista “Sin trasladar”"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Impossible d’enregistrer la liste « Non déplacés »"+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Impossibile salvare l’elenco “Non spostati”"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "“移動されなかった項目”のリストを保存できませんでした"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "‘이동되지 않음’ 목록을 저장할 수 없음"+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "De lijst 'Niet verplaatst' kon niet worden bewaard"+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nie udało się zachować listy „Nie przeniesiono”"+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Não foi possível salvar a lista “Não Movidos”"+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Lista „Nu au fost mutate” nu a putut fi salvată"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не удалось сохранить список «Не перемещено»"+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Listan Inte flyttat kunde inte sparas"+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Taşınmayanlar listesi kaydedilemedi"+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не вдалося зберегти список «Не переміщено»"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未能保存“未移动”列表"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "無法儲存「未移動」清單"+ }+ }+ }+ },+ "The Not Moved list was damaged" : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seznam Nepřesunuto byl poškozený"+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Die Liste „Nicht verschoben“ war beschädigt"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "La lista “Sin trasladar” estaba dañada"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "La liste « Non déplacés » était endommagée"+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "L’elenco “Non spostati” era danneggiato"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "“移動されなかった項目”のリストが破損していました"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "‘이동되지 않음’ 목록이 손상됨"+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "De lijst 'Niet verplaatst' was beschadigd"+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Lista „Nie przeniesiono” była uszkodzona"+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "A lista “Não Movidos” estava danificada"+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Lista „Nu au fost mutate” a fost deteriorată"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Список «Не перемещено» был поврежден"+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Listan Inte flyttat var skadad"+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Taşınmayanlar listesi bozuktu"+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Список «Не переміщено» пошкоджено"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "“未移动”列表已损坏"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "「未移動」清單已損毀"+ }+ }+ }+ },"The address written inside the app, and wherever it redirects." : {"localizations" : {"cs" : {@@ -141265,6 +141795,112 @@}}},+ "What stayed in the last removal is where it was, but it isn’t listed here." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Co při posledním odstranění zůstalo, je tam, kde bylo, ale není tu uvedeno."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Was beim letzten Entfernen geblieben ist, ist noch dort, wo es war, wird hier aber nicht angezeigt."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Lo que se quedó sin trasladar en la última eliminación sigue donde estaba, pero no aparece aquí."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ce qui est resté en place lors de la dernière suppression s’y trouve toujours, mais n’est pas listé ici."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ciò che è rimasto nell’ultima rimozione è ancora dov’era, ma non è elencato qui."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "前回ゴミ箱に入れた際に移動されなかった項目は元の場所にありますが、ここには表示されていません。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "마지막 제거에서 그대로 남은 항목은 원래 위치에 있지만, 여기에는 표시되지 않습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Wat bij de laatste verwijdering is blijven staan, staat nog op dezelfde plek, maar wordt hier niet vermeld."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "To, co zostało przy ostatnim przeniesieniu do Kosza, jest tam, gdzie było, ale nie ma tego tutaj na liście."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O que permaneceu na última remoção continua onde estava, mas não está listado aqui."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ce a rămas pe loc la ultima eliminare este tot acolo unde era, dar nu este listat aici."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "То, что осталось на месте при последнем удалении, находится там же, где и было, но здесь не показывается."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Det som blev kvar vid den senaste borttagningen ligger kvar där det var, men det finns inte med i listan här."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Son kaldırma işleminde taşınmayan öğeler hâlâ yerinde, ancak burada listelenmiyor."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Те, що лишилося після останнього вилучення, досі на своєму місці, але тут не показується."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "上一次移除中未移动的项目仍在原处,但此处没有列出它们。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "上一次移除中留下的項目仍在原處,但未列在此處。"+ }+ }+ }+ },"What the App Keeps for You" : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swiftindex 376c694f..a0b3e628 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift@@ -220,7 +220,11 @@ struct HistoryCommand: AsyncParsableCommand {Output.line("Forgot every refusal on record.")return}- let removals = Array(RefusalRecord.grouped(await log.load()).prefix(limit))+ let read = await log.load()+ if let problem = read.problem {+ Output.note(problem.summary)+ }+ let removals = Array(RefusalRecord.grouped(read.records).prefix(limit))if output.json {try Output.json(removals.map { removal indiff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Cleanup.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Cleanup.swiftindex 72302b75..b7858196 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Cleanup.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Cleanup.swift@@ -91,7 +91,9 @@ struct Cleanup {let refused = items.compactMap { item in item.refusal.map { TrashFailure(url: item.url, reason: $0) } }guard !moving.isEmpty else {Output.line("Nothing here can be moved.")- await refusals.add(refused, source: source, sourceKey: sourceKey, tool: tool)+ if let problem = await refusals.add(refused, source: source, sourceKey: sourceKey, tool: tool) {+ Output.note(problem.summary)+ }return}if !yes {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swiftindex c0db7706..71835bc2 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift@@ -226,6 +226,18 @@ extension RemovalLogProblem {}}+extension RefusalLogProblem {+ var summary: String {+ switch self {+ case .damaged(let setAside):+ "The list of refusals was damaged, so it was kept as \(Output.plain(Output.path(setAside)))"+ + " and started again."+ case .unreadable: "The list of refusals couldn't be read, so Peel keeps it as it is and writes nothing to it."+ case .couldNotRecord: "The list of refusals couldn't be saved, so what stayed this time isn't in it."+ }+ }+}+extension MatchReason {var summary: String {switch self {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Removals.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Removals.swiftindex 9860d7d2..96054caa 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Removals.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Removals.swift@@ -19,7 +19,9 @@ enum Removals {let part = RemovalPart(source: source, sourceKey: sourceKey, tool: tool)isRecorded = await log.add(part.records(of: result, sizes: sizes, batch: UUID())).records != nil}- await refusals.add(result.failures, source: source, sourceKey: sourceKey, tool: tool)+ if let problem = await refusals.add(result.failures, source: source, sourceKey: sourceKey, tool: tool) {+ Output.note(problem.summary)+ }return isRecorded}}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swiftnew file mode 100644index 00000000..315c1504--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift@@ -0,0 +1,29 @@+import Foundation++/// The rule History and the refusal log share for staying quick to read: past a cap, the oldest removals are+/// dropped whole, because an entry cut in part would read as all there was.+enum Batches {+ /// Sorts `records` newest first and drops the oldest batches beyond `maximum`, each whole, never one in+ /// `protected`. A batch is dated by its oldest record, the date History shows for it.+ static func trimmed<Record, Batch: Hashable>(+ _ records: [Record],+ maximum: Int,+ batch: (Record) -> Batch,+ date: (Record) -> Date,+ keeping protected: Set<Batch> = []+ ) -> [Record] {+ let sorted = records.sorted { date($0) > date($1) }+ guard sorted.count > maximum else { return sorted }++ let batches = Dictionary(grouping: sorted, by: batch)+ let dates = batches.mapValues { $0.map(date).min() ?? .distantPast }+ var total = sorted.count+ var dropped: Set<Batch> = []+ for key in batches.keys.sorted(by: { dates[$0] ?? .distantPast < dates[$1] ?? .distantPast }) where total > maximum {+ guard !protected.contains(key) else { continue }+ dropped.insert(key)+ total -= batches[key]?.count ?? 0+ }+ return sorted.filter { !dropped.contains(batch($0)) }+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swiftindex bbe3eed8..87988644 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift@@ -29,6 +29,17 @@ public struct RefusalRecord: Sendable, Codable, Hashable, Identifiable {}}+/// What went wrong reading or writing the refusal log, for History to say.+public enum RefusalLogProblem: Sendable, Equatable {+ /// The file could not be decoded. It was set aside under this name, and the rows that could be read were kept.+ case damaged(setAside: URL)+ /// The file could not be read or set aside, so nothing is written to it: it is the only copy of what was+ /// refused.+ case unreadable+ /// What the last removal refused could not be written down.+ case couldNotRecord+}+/// A record of what Peel was asked to move and refused, so the decisions can be read back. Only refusals of/// items the user asked to move go in, never what a scan held back. Access goes through an actor and an/// advisory lock on the file, as in `RemovalLog`, because the `peel` tool writes here too.@@ -41,21 +52,33 @@ public actor RefusalLog {self.url = url}- public func load() -> [RefusalRecord] {- FileLock.whileHeld(beside: url) { current() ?? [] }+ public func load() -> (records: [RefusalRecord], problem: RefusalLogProblem?) {+ FileLock.whileHeld(beside: url) {+ let read = current()+ return (read.records ?? [], read.problem)+ }}- /// Writes down what one removal refused. The parts of one pass through several tools share its `batch`, so- /// History shows them as one entry.+ /// Writes down what one removal refused, and says what kept it from being written. The parts of one pass+ /// through several tools share its `batch`, so History shows them as one entry. Past the cap, the oldest+ /// removals are dropped whole.+ @discardableResultpublic func add(_ failures: [TrashFailure], source: String, sourceKey: String? = nil, tool: String, batch: UUID = UUID(),date: Date = .now- ) {- let records = failures.map { RefusalRecord(failure: $0, date: date, source: source, sourceKey: sourceKey, tool: tool, batch: batch) }- guard !records.isEmpty else { return }- FileLock.whileHeld(beside: url) {- guard let existing = current() else { return }- write(Array((existing + records).sorted { $0.date > $1.date }.prefix(Self.maximumRecords)))+ ) -> RefusalLogProblem? {+ let records = failures.map {+ RefusalRecord(failure: $0, date: date, source: source, sourceKey: sourceKey, tool: tool, batch: batch)+ }+ guard !records.isEmpty else { return nil }+ return FileLock.whileHeld(beside: url) {+ let read = current()+ guard let existing = read.records else { return read.problem }+ let kept = Batches.trimmed(+ existing + records, maximum: Self.maximumRecords, batch: { $0.batch ?? $0.id }, date: \.date,+ keeping: [batch]+ )+ return write(kept) ? read.problem : .couldNotRecord}}@@ -66,23 +89,23 @@ public actor RefusalLog {}}- /// The records in the file. A file that fails to decode is set aside and its readable rows kept. Nil when the- /// file could not be read or set aside, so it must not be written over.- private func current() -> [RefusalRecord]? {- guard !url.isMissing else { return [] }- guard let data = BoundedRead.data(at: url, maximum: 16 * 1_024 * 1_024) else { return nil }+ /// The records in the file. A file that fails to decode is set aside and its readable rows kept. Nil records+ /// when the file could not be read or set aside, so it must not be written over.+ private func current() -> (records: [RefusalRecord]?, problem: RefusalLogProblem?) {+ guard !url.isMissing else { return ([], nil) }+ guard let data = BoundedRead.data(at: url, maximum: 16 * 1_024 * 1_024) else { return (nil, .unreadable) }let decoder = JSONDecoder()decoder.dateDecodingStrategy = LogTime.decodingif let records = try? decoder.decode([RefusalRecord].self, from: data) {- return records+ return (records, nil)}// A row that a later version wrote, or that a hand edit broke, must not cost the other rows.let readable = (try? decoder.decode([Row].self, from: data))?.compactMap(\.record) ?? []- guard DamagedFile.setAside(url) != nil else { return nil }+ guard let setAside = DamagedFile.setAside(url) else { return (nil, .unreadable) }if !readable.isEmpty {write(readable)}- return readable+ return (readable, .damaged(setAside: setAside))}/// One row of the file. A row with a missing or malformed field is dropped and the others are kept: any@@ -95,12 +118,13 @@ public actor RefusalLog {}}- private func write(_ records: [RefusalRecord]) {+ @discardableResult+ private func write(_ records: [RefusalRecord]) -> Bool {let encoder = JSONEncoder()encoder.dateEncodingStrategy = LogTime.encodingencoder.outputFormatting = [.prettyPrinted, .sortedKeys]- guard let data = try? encoder.encode(records) else { return }+ guard let data = try? encoder.encode(records) else { return false }try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)- try? data.write(to: url, options: .atomic)+ return (try? data.write(to: url, options: .atomic)) != nil}}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swiftindex 26221539..fe4dd699 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift@@ -192,19 +192,6 @@ public actor RemovalLog {/// to read. A batch is dropped whole, and never one in `protected`: a removal is recorded completely or not/// at all, because a half-recorded one looks complete to the user.static func trimmed(_ records: [RemovalRecord], keeping protected: Set<UUID>) -> [RemovalRecord] {- let sorted = records.sorted { $0.date > $1.date }- guard sorted.count > maximumRecords else { return sorted }-- let batches = Dictionary(grouping: sorted, by: \.batch)- // Oldest first, by the date History shows for a batch.- let dates = batches.mapValues { $0.map(\.date).min() ?? .distantPast }- var total = sorted.count- var dropped: Set<UUID> = []- for batch in batches.keys.sorted(by: { dates[$0] ?? .distantPast < dates[$1] ?? .distantPast }) where total > maximumRecords {- guard !protected.contains(batch) else { continue }- dropped.insert(batch)- total -= batches[batch]?.count ?? 0- }- return sorted.filter { !dropped.contains($0.batch) }+ Batches.trimmed(records, maximum: maximumRecords, batch: \.batch, date: \.date, keeping: protected)}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swiftindex b14a5738..cbbc2c4d 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CleanupTests.swift@@ -61,7 +61,7 @@ struct CleanupTests {}}#expect(FileManager.default.fileExists(atPath: cache.path(percentEncoded: false)))- #expect(await refusals.load().isEmpty)+ #expect(await refusals.load().records.isEmpty)}/// While History cannot be read nothing moves, and the command says so above the list, with the way out.@@ -134,7 +134,7 @@ struct CleanupTests {#expect(!FileManager.default.fileExists(atPath: cache.path(percentEncoded: false)))#expect(records.map(\.originalURL) == [cache])#expect(records.allSatisfy { $0.source == "Editor" && $0.tool == "developer" && $0.size == 20 })- #expect(await RefusalLog(url: refusals.url).load().isEmpty)+ #expect(await RefusalLog(url: refusals.url).load().records.isEmpty)}/// A removal that could not finish exits 1, and every item that stayed is recorded as refused.@@ -153,7 +153,7 @@ struct CleanupTests {}#expect(await RemovalLog(url: log.url).load().records?.isEmpty == true)- #expect(await RefusalLog(url: refusals.url).load().map(\.reason) == ["changed-since-scan"])+ #expect(await RefusalLog(url: refusals.url).load().records.map(\.reason) == ["changed-since-scan"])#expect(FileManager.default.fileExists(atPath: cache.path(percentEncoded: false)))}@@ -169,7 +169,7 @@ struct CleanupTests {try await plan.run(question: "?", dryRun: false, yes: true, using: try service(in: directory), recordingIn: log, refusals: refusals)#expect(await RemovalLog(url: log.url).load().records?.isEmpty == true)- #expect(await RefusalLog(url: refusals.url).load().map(\.reason) == ["stays-in-place"])+ #expect(await RefusalLog(url: refusals.url).load().records.map(\.reason) == ["stays-in-place"])#expect(FileManager.default.fileExists(atPath: documents.path(percentEncoded: false)))}@@ -182,7 +182,7 @@ struct CleanupTests {try await plan.run(question: "?", dryRun: true, yes: true, using: try service(in: directory), refusals: refusals)- #expect(await RefusalLog(url: refusals.url).load().isEmpty)+ #expect(await RefusalLog(url: refusals.url).load().records.isEmpty)}/// A refusal known before the move is shown in the plan, and is still recorded when the other items move.@@ -200,6 +200,6 @@ struct CleanupTests {try await plan.run(question: "?", dryRun: false, yes: true, using: service, recordingIn: log, refusals: refusals)#expect(await RemovalLog(url: log.url).load().records?.map(\.originalURL) == [cache])- #expect(await RefusalLog(url: refusals.url).load().map(\.url) == [documents])+ #expect(await RefusalLog(url: refusals.url).load().records.map(\.url) == [documents])}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swiftindex 25261e4c..1a42353a 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift@@ -279,7 +279,7 @@ struct FileCommandTests {.clean("com.example.gone", in: scan, apps: [], scanner: scanner(in: directory), using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)#expect(await moved(logs).isEmpty)- #expect(await logs.refusals.load().map(\.reason) == ["needs-helper"])+ #expect(await logs.refusals.load().records.map(\.reason) == ["needs-helper"])#expect(FileManager.default.fileExists(atPath: group.items[0].url.path(percentEncoded: false)))}@@ -300,7 +300,7 @@ struct FileCommandTests {}#expect(await moved(logs).isEmpty)- #expect(await logs.refusals.load().isEmpty)+ #expect(await logs.refusals.load().records.isEmpty)#expect(FileManager.default.fileExists(atPath: group.items[0].url.path(percentEncoded: false)))#expect(collected.notes == "\(Output.path(group.items[0].url)) stays: holds a photo, music, or video library\n")}@@ -323,7 +323,7 @@ struct FileCommandTests {}#expect(await moved(logs) == ["com.example.gone"])- #expect(await logs.refusals.load().isEmpty)+ #expect(await logs.refusals.load().records.isEmpty)#expect(FileManager.default.fileExists(atPath: group.items[1].url.path(percentEncoded: false)))#expect(collected.notes == "\(Output.path(group.items[1].url)) stays: holds a wallet or a signing key\n")}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swiftindex 6661ca62..cb9560fc 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift@@ -286,7 +286,7 @@ struct HistoryCommandTests {try await (command(["history", "--refused", "--clear"]) as HistoryCommand).run(in: logs.removals, refusals: logs.refusals)- #expect(await logs.refusals.load().isEmpty)+ #expect(await logs.refusals.load().records.isEmpty)}/// A History file that cannot be read is reported as an error, never shown as an empty History.diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swiftindex 45d3cf61..3cd9721b 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift@@ -21,7 +21,7 @@ struct RefusalLogTests {tool: "applications")- let records = await RefusalLog(url: log.url).load()+ let records = await RefusalLog(url: log.url).load().records#expect(records.count == 2)#expect(records.allSatisfy { $0.source == "Editor" && $0.tool == "applications" })#expect(Set(records.map(\.reason)) == ["protected-place", "failed"])@@ -40,7 +40,7 @@ struct RefusalLogTests {#expect(await Removals.record(result, from: "Editor", sizes: [:], tool: "applications", in: log, refusals: refusals))#expect(await RemovalLog(url: log.url).load().records?.isEmpty == true)- #expect(await RefusalLog(url: refusals.url).load().map(\.reason) == ["protected-place"])+ #expect(await RefusalLog(url: refusals.url).load().records.map(\.reason) == ["protected-place"])}/// History is the way back for what just moved, so it is written before the refusals: while the refusal log@@ -88,17 +88,21 @@ struct RefusalLogTests {#expect(!FileManager.default.fileExists(atPath: url.path(percentEncoded: false)))}- @Test func keepsTheNewestAndDropsTheOldest() async throws {+ /// Past its cap the log drops the oldest removals whole, as History does: an entry cut in part would read as+ /// all that was refused.+ @Test func dropsTheOldestRemovalsWhole() async throws {let directory = try TemporaryDirectory()let log = RefusalLog(url: directory.url.appending(path: "refusals.json"))- let older = (0..<RefusalLog.maximumRecords).map { failure("/Users/me/old-\($0)", .lastCopy) }+ let oldest = (0..<3_000).map { failure("/Users/me/oldest-\($0)", .lastCopy) }+ let older = (0..<2_000).map { failure("/Users/me/older-\($0)", .lastCopy) }- await log.add(older, source: "Old", tool: "duplicates")+ await log.add(oldest, source: "Oldest", tool: "duplicates", date: .now.addingTimeInterval(-120))+ await log.add(older, source: "Older", tool: "duplicates", date: .now.addingTimeInterval(-60))await log.add([failure("/Users/me/new", .notPermitted)], source: "New", tool: "space")- let records = await log.load()- #expect(records.count == RefusalLog.maximumRecords)- #expect(records.contains { $0.source == "New" })+ let records = await log.load().records+ #expect(records.count == 2_001)+ #expect(Set(records.map(\.source)) == ["Older", "New"])}/// The file is Peel's, but any process the user runs can rewrite it.@@ -111,9 +115,11 @@ struct RefusalLogTests {"""try Data("[\(good), {\"id\":\"not a uuid\"}]".utf8).write(to: url)- let records = await RefusalLog(url: url).load()+ let outcome = await RefusalLog(url: url).load()- #expect(records.map(\.reason) == ["last-copy"])+ #expect(outcome.records.map(\.reason) == ["last-copy"])+ guard case .damaged(let setAside) = outcome.problem else { Issue.record("no damage reported"); return }+ #expect(setAside.lastPathComponent.contains("damaged"))#expect(try FileManager.default.contentsOfDirectory(atPath: url.deletingLastPathComponent().path(percentEncoded: false)).contains { $0.contains("damaged") }, "the file it could not read was thrown away")}@@ -126,10 +132,27 @@ struct RefusalLogTests {try directory.setPermissions(0, of: url)defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path(percentEncoded: false)) }- await RefusalLog(url: url).add([failure("/Users/me/a", .lastCopy)], source: "Editor", tool: "applications")+ let problem = await RefusalLog(url: url)+ .add([failure("/Users/me/a", .lastCopy)], source: "Editor", tool: "applications")+ let outcome = await RefusalLog(url: url).load()try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path(percentEncoded: false))#expect(try Data(contentsOf: url) == Data("[]".utf8), "an unreadable record was written over")+ #expect(problem == .unreadable)+ #expect(outcome.problem == .unreadable && outcome.records.isEmpty)+ }++ /// A refusal that could not be written down is said, rather than lost without a word.+ @Test(.permissionsHold) func saysWhenWhatWasRefusedCouldNotBeWritten() async throws {+ let directory = try TemporaryDirectory()+ let folder = try directory.directory("Peel")+ try directory.setPermissions(0o500, of: "Peel")+ defer { try? directory.setPermissions(0o700, of: "Peel") }++ let problem = await RefusalLog(url: folder.appending(path: "refusals.json"))+ .add([failure("/Users/me/a", .lastCopy)], source: "Editor", tool: "applications")++ #expect(problem == .couldNotRecord)}/// A record in a folder that cannot be searched may be there, so it is not called cleared.@@ -149,7 +172,7 @@ struct RefusalLogTests {await log.add([failure("/Users/me/a", .lastCopy)], source: "Editor", tool: "applications")#expect(await log.clear())- #expect(await log.load().isEmpty)+ #expect(await log.load().records.isEmpty)#expect(await log.clear(), "forgetting what is already forgotten is no failure")}@@ -191,7 +214,7 @@ struct RefusalLogTests {await log.add([failure("/Users/me/a", .lastCopy), failure("/Users/me/b", .lastCopy)], source: "Duplicates", sourceKey: "tool", tool: "duplicates")await log.add([failure("/Users/me/c", .notPermitted)], source: "Editor", tool: "applications")- let records = await log.load()+ let records = await log.load().recordslet first = records.filter { $0.source == "Duplicates" }#expect(first.count == 2)#expect(Set(first.map(\.batch)).count == 1)@@ -233,7 +256,7 @@ struct RefusalLogTests {try Data(stored.utf8).write(to: url)await RefusalLog(url: url).add([failure("/Users/me/new", .notPermitted)], source: "Editor", tool: "applications")- let records = await RefusalLog(url: url).load()+ let records = await RefusalLog(url: url).load().records#expect(records.count == 4)#expect(RefusalRecord.grouped(records).first { $0.id == batch }?.parts.map(\.tool) == ["orphans", "duplicates"])diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swiftindex 1d38b0ad..bf7dd9cf 100644--- a/Peel/Model/RemovalHistoryStore.swift+++ b/Peel/Model/RemovalHistoryStore.swift@@ -113,6 +113,8 @@ final class RemovalHistoryStore {/// What Peel was asked to move and did not, one removal to an entry, newest first.private(set) var refusalBatches: [RefusalBatch] = []private(set) var refusalSearchKeys: [RefusalBatch.ID: String] = [:]+ /// What the last read or change of the refusal log met, which the Not Moved list says.+ private(set) var refusalProblem: RefusalLogProblem?private(set) var problem: RemovalLogProblem?/// Whether History cannot be read, which holds every removal back, as the Trash service does. Known without/// reading it: at launch, when Peel comes forward, and with every read or change of History.@@ -162,7 +164,9 @@ final class RemovalHistoryStore {}private func loadRefusals() async {- refusalBatches = RefusalRecord.grouped(await refusals.load()).map(RefusalBatch.init)+ let read = await refusals.load()+ refusalProblem = read.problem+ refusalBatches = RefusalRecord.grouped(read.records).map(RefusalBatch.init)refusalSearchKeys = Dictionary(uniqueKeysWithValues: refusalBatches.map {($0.id, Self.searchKey(title: $0.title, names: $0.records.map(\.url.lastPathComponent)))})@@ -196,10 +200,15 @@ final class RemovalHistoryStore {}// Refusals are logged whether or not anything moved: a removal where nothing moved is the one most worth a// record.- await refusals.add(result.failures, source: part.source, sourceKey: part.sourceKey, tool: part.tool, batch: removal.refusals)+ let refusalProblem = await refusals.add(+ result.failures, source: part.source, sourceKey: part.sourceKey, tool: part.tool, batch: removal.refusals+ )if !result.failures.isEmpty {await loadRefusals()}+ if let refusalProblem {+ self.refusalProblem = refusalProblem+ }checkReadability()}diff --git a/Peel/Views/History/HistoryList.swift b/Peel/Views/History/HistoryList.swiftindex 5b4a4ba5..15ed47d9 100644--- a/Peel/Views/History/HistoryList.swift+++ b/Peel/Views/History/HistoryList.swift@@ -43,15 +43,20 @@ struct HistoryList: View {}.columnSearch(text: $searchText, prompt: "Search History", when: !history.batches.isEmpty || !history.refusalBatches.isEmpty).safeAreaBar(edge: .top) {- Group {+ VStack(spacing: 8) {if let problem = history.shownProblem {HistoryProblemNotice(problem: problem)- .padding(.horizontal, 12)- .padding(.bottom, 8)+ .transition(.opacity)+ }+ if let problem = history.refusalProblem {+ RefusalProblemNotice(problem: problem).transition(.opacity)}}+ .padding(.horizontal, 12)+ .padding(.bottom, history.shownProblem != nil || history.refusalProblem != nil ? 8 : 0).motion(.settle, .movement, value: history.shownProblem != nil)+ .motion(.settle, .movement, value: history.refusalProblem != nil)}.overlay {if !history.hasLoaded {@@ -120,6 +125,35 @@ private struct HistoryProblemNotice: View {}}+/// What kept the list under Not Moved from being read or saved.+private struct RefusalProblemNotice: View {+ let problem: RefusalLogProblem++ var body: some View {+ switch problem {+ case .damaged(let setAside):+ Notice(+ title: Text("The Not Moved list was damaged"),+ detail: Text("Peel kept the old file and continued with what it could still read.")+ ) {+ Button("Show in Finder", systemImage: "folder") {+ NSWorkspace.shared.activateFileViewerSelecting([setAside])+ }+ }+ case .unreadable:+ Notice(+ title: Text("The Not Moved list can’t be read"),+ detail: Text("Peel leaves the file as it is and adds nothing to it, since it is the only record of what stayed.")+ ) { EmptyView() }+ case .couldNotRecord:+ Notice(+ title: Text("The Not Moved list couldn’t be saved"),+ detail: Text("What stayed in the last removal is where it was, but it isn’t listed here.")+ ) { EmptyView() }+ }+ }+}+private struct HistoryBatchRow: View {let batch: RemovalBatch