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
Keep a removal from several pages one entry when it is cut short
Țugui Dragoș7d7dd940e0cf
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 64bba564..8027a26a 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -169,8 +169,10 @@ the Homebrew page's uninstall and cleanups are Homebrew's own.- Each item is also written down the moment it moves, and what the helper moves as soon as it answers eachrequest (`removals.journal`, through `RemovalJournal`), so what a removal moved before it was cut short reachesHistory the next time History is read, as an interrupted removal, or as what it was when History couldn't write- it, since its line then keeps the record (`RemovalJournal.keep`). Quitting the app waits for a removal until- History has it (`QuitGuard`), as `peel` carries on through Control-C (`Uninterrupted`).+ it, since its line then keeps the record (`RemovalJournal.keep`). A removal recorded a part at a time writes+ its batch and the part on each line (`RecordedRemoval`), so what a part left there joins that removal under the+ part's name. Quitting the app waits for a removal until History has it (`QuitGuard`), as `peel` carries on+ through Control-C (`Uninterrupted`).- While History cannot be read nothing moves (`RemovalLog.canBeRead`, asked by `TrashService` before a removal)until Start Over, on the History page, sets the unreadable file aside, and while it cannot be written, its folderclosed or its disk without room for the copy a safe write makes, nothing moves either (`RemovalLog.canBeWritten`).diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swiftindex bd17cd51..562236b7 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift@@ -64,7 +64,7 @@ extension RefusalRecord {/// Where some of a removal's records came from: the tool, and the source it names, such as an app or a group of/// orphaned files. A removal from one page has one part, and one that moved what was selected in several tools/// has one for each, in the order they moved.-public struct RemovalPart: Sendable, Hashable {+public struct RemovalPart: Sendable, Hashable, Codable {public let source: String/// The key of a source Peel names itself, so History can show it in the user's language.public let sourceKey: String?diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swiftindex eb0beb62..feff30a2 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift@@ -1,7 +1,22 @@import Darwin-import Foundation+public import Foundationinternal import PeelPrivileged+/// The removal of History a move goes into, and its part, for a removal recorded a part at a time. The journal keeps+/// it with each item, so what a part left there when its process stopped joins that removal under the part's name.+public struct RecordedRemoval: Sendable {+ public let batch: UUID+ public let part: RemovalPart++ public init(batch: UUID, part: RemovalPart) {+ self.batch = batch+ self.part = part+ }++ /// The removal the moves in the current task go into, set by whoever records them.+ @TaskLocal public static var current: RecordedRemoval?+}+/// What a removal moved, written down item by item as it moves, beside History. History takes each item over once/// it records it; what a process that stopped before then left here goes into History the next time History is read,/// as an interrupted removal, so nothing Peel moved to the Trash is ever missing from it.@@ -35,12 +50,16 @@ struct RemovalJournal: Sendable {let item: TrashedItem/// The record History couldn't take, kept here so the item comes back as what it was.var record: RemovalRecord? = nil+ /// The part of the removal the item moved in, when the removal was recorded a part at a time.+ var part: RemovalPart? = nil- /// History's record of the item: the one kept here, or else that of an interrupted removal, which names no- /// tool, since which tool moved the item is not known.+ /// History's record of the item: the one kept here, or else one of its part, its size not known, or else+ /// that of an interrupted removal, which names no tool, since which tool moved the item is not known.var recordToTakeIn: RemovalRecord {- record ?? RemovalRecord(- batch: batch, item: item, size: nil, source: "Interrupted removal", sourceKey: "interrupted", tool: ""+ if let record { return record }+ let part = part ?? RemovalPart(source: "Interrupted removal", sourceKey: "interrupted", tool: "")+ return RemovalRecord(+ batch: batch, item: item, size: nil, source: part.source, sourceKey: part.sourceKey, tool: part.tool)}}@@ -78,14 +97,18 @@ struct RemovalJournal: Sendable {RemovalLog.canBeWritten(at: history)}- /// Writes down `items`, which moved together in `batch`, one line each. An item the journal was in, Peel's own- /// folder as Peel removes itself, is left out: History went with it, and writing the line would make the- /// folder again.- func note(_ items: [TrashedItem], batch: UUID, by writer: Writer = .current) {+ /// Writes down `items`, which moved together in `batch`, or in the removal and part `recorded` names, one line+ /// each. An item the journal was in, Peel's own folder as Peel removes itself, is left out: History went with it,+ /// and writing the line would make the folder again.+ func note(+ _ items: [TrashedItem], batch: UUID, recordedAs recorded: RecordedRemoval? = .current,+ by writer: Writer = .current+ ) {let journal = url.path(percentEncoded: false)+ let entry = { item in Entry(writer: writer, batch: recorded?.batch ?? batch, item: item, part: recorded?.part) }let lines = items.filter { !PathComponents.isPath(journal, atOrInside: $0.originalURL.path(percentEncoded: false)) }- .compactMap { item in (try? Self.encoder.encode(Entry(writer: writer, batch: batch, item: item))) }+ .compactMap { item in (try? Self.encoder.encode(entry(item))) }guard !lines.isEmpty else { return }FileLock.whileHeld(beside: url) {let descriptor = open(journal, O_RDWR | O_APPEND | O_CREAT | O_CLOEXEC, 0o600)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swiftindex 4eff4508..57301b89 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift@@ -59,6 +59,44 @@ struct RemovalJournalTests {#expect(journal.entries().isEmpty)}+ /// A removal of several parts that stops after a part moved and before it was recorded is still one entry: what+ /// the part left in the journal joins the removal under the part's own name.+ @Test func aPassStoppedBetweenPartsStaysOneRemoval() async throws {+ let directory = try TemporaryDirectory()+ let history = directory.url.appending(path: "Peel/removals.json")+ let journal = RemovalJournal(beside: history)+ let first = try directory.file("home/Library/Caches/com.example.one/cache.db").deletingLastPathComponent()+ let second = try directory.file("home/Library/Caches/com.example.two/cache.db").deletingLastPathComponent()+ let service = service(in: directory, journal: journal) { url in+ directory.url.appending(path: "home/.Trash/\(url.lastPathComponent)")+ }+ let batch = UUID()+ let developer = RemovalPart(source: "npm", sourceKey: nil, tool: "developer")+ let space = RemovalPart(source: "App Caches", sourceKey: "space.appCaches", tool: "space")+ let firstMoved = await RecordedRemoval.$current.withValue(RecordedRemoval(batch: batch, part: developer)) {+ await service.trash([first])+ }+ _ = await RemovalLog(url: history).add(developer.records(of: firstMoved, sizes: [:], batch: batch))+ _ = await RecordedRemoval.$current.withValue(RecordedRemoval(batch: batch, part: space)) {+ await service.trash([second])+ }++ let left = journal.entries()+ #expect(left.map(\.batch) == [batch])+ #expect(left.map(\.part) == [space])+ // The process stops before it records the second part.+ journal.forget(Set(left))+ for entry in left {+ let recorded = RecordedRemoval(batch: entry.batch, part: try #require(entry.part))+ journal.note([entry.item], batch: entry.batch, recordedAs: recorded, by: try endedProcess())+ }++ let records = try #require(await RemovalLog(url: history).load().records)+ let removals = RemovalRecord.grouped(records)+ #expect(removals.count == 1, "the part that stopped came back as a removal of its own")+ #expect(removals.first?.parts == [developer, space])+ }+/// While the process that moved an item still runs, it records the item itself, in its own words: a read of/// History meanwhile, from the app or from `peel`, leaves the journal alone.@Test func aRemovalStillUnderWayIsLeftToRecordItself() async throws {diff --git a/Peel/Model/SelectionCarrier.swift b/Peel/Model/SelectionCarrier.swiftindex d7974064..75fa11ab 100644--- a/Peel/Model/SelectionCarrier.swift+++ b/Peel/Model/SelectionCarrier.swift@@ -104,7 +104,14 @@ final class SelectionCarrier {var appsToQuit: [String] = []let pass = await QuitGuard.shared.run {await CarriedSelection.pass(parts) { part in- guard let tool = tool(of: part), let result = await tool.move(part, apps: apps) else {+ // What a part moves is written down with the removal and the part, so a stop before the part is+ // recorded leaves one removal in History, not two.+ let recorded = RecordedRemoval(batch: removal.batch, part: part.removalPart)+ guard let tool = tool(of: part),+ let result = await RecordedRemoval.$current.withValue(recorded, operation: {+ await tool.move(part, apps: apps)+ })+ else {appsToQuit.append(tool(of: part)?.appToQuit(for: part) ?? part.title)return nil}diff --git a/PeelTests/SelectionCarrierTests.swift b/PeelTests/SelectionCarrierTests.swiftindex eb7d6952..ff4b30a9 100644--- a/PeelTests/SelectionCarrierTests.swift+++ b/PeelTests/SelectionCarrierTests.swift@@ -15,6 +15,21 @@ struct SelectionCarrierTests {func deselect(_ part: CarriedSelection.Part) {}}+ /// A tool that moves each part at once and notes the removal its moves were written down under.+ private final class Recording: CarriesSelection {+ var seen: [RecordedRemoval?] = []+ var carriedParts: [CarriedSelection.Part] { [] }+ func move(_ part: CarriedSelection.Part, apps: AppLibrary) async -> TrashResult? {+ seen.append(RecordedRemoval.current)+ let name = part.page.scope+ let json = #"{"originalURL": "file:///Users/me/\#(name)", "trashedURL": "file:///Users/me/.Trash/\#(name)", "date": 0}"#+ let item = try? JSONDecoder().decode(TrashedItem.self, from: Data(json.utf8))+ return TrashResult(trashed: [item].compactMap(\.self))+ }+ func refresh(after parts: [CarriedSelection.Part], apps: AppLibrary) async {}+ func deselect(_ part: CarriedSelection.Part) {}+ }+private func part(_ scope: String) -> CarriedSelection.Part {CarriedSelection.Part(page: Tool.developer.page(scope), title: scope, source: scope, sourceKey: nil,@@ -46,4 +61,32 @@ struct SelectionCarrierTests {#expect(kept.map(\.part.page.scope) == ["chrome", "slack"])#expect(carrier.free(among: [part("chrome"), part("npm"), part("slack")]).map(\.page.scope) == ["npm"])}++ /// Each part moves with the removal and the part it goes into in History, which the journal keeps with what moved.+ @Test func movesEachPartAsPartOfTheRemovalHistoryRecords() async throws {+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: folder) }+ let made = try MadeUpDefaults()+ defer { made.forget() }+ let recording = Recording()+ let log = RemovalLog(url: folder.appending(path: "removals.json"))+ let carrier = SelectionCarrier(+ tools: [.developer: recording],+ apps: AppLibrary(+ defaults: made.defaults, releaseNotesStore: ReleaseNotesStore(url: folder.appending(path: "notes.json"))+ ),+ history: RemovalHistoryStore(+ log: log,+ refusals: RefusalLog(url: folder.appending(path: "refusals.json")),+ knowsTheExclusions: { true }+ ),+ outcome: RemovalOutcome()+ )++ await carrier.move([part("npm"), part("pip")])++ let batch = try #require(await log.load().records?.first?.batch)+ #expect(recording.seen.map { $0?.batch } == [batch, batch])+ #expect(recording.seen.map { $0?.part } == [part("npm").removalPart, part("pip").removalPart])+ }}diff --git a/SAFETY.md b/SAFETY.mdindex 8215747a..3ddfb9f7 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -157,8 +157,8 @@ That includes what `pkgutil` and Homebrew would delete:A removal reaches History even when something cuts it short. Quitting Peel waits until History has it, `peel`carries on through Control-C or a closed terminal until it has written History, and each item Peel moves itself iswritten down the moment it moves, and what its helper moves as soon as the helper answers each request, so one cut-short by a crash or Force Quit still reaches History, as an interrupted removal, the next time Peel or `peel` opens-it.+short by a crash or Force Quit still reaches History the next time Peel or `peel` opens it: as an interrupted+removal, or, for a removal of what was selected on several pages, in that removal under its page's name.Right before anything moves, and again once a second while a removal of many items goes on, Peel looks at the filesother programs of yours hold open, at the program each process runs, and at the script a program such as Node.js or