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
Read the refusals again only when their file changed
Țugui Dragoș268a1873bfa8
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swiftindex 09e3fdc1..6719968a 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift@@ -54,6 +54,8 @@ public actor RefusalLog {static let maximumRecords = 5_000public let url: URL+ /// What was last read or written, kept while the file stays the same, as in `RemovalLog`.+ private var kept: (file: FileIdentity, records: [RefusalRecord])?public init(url: URL = RemovalHistory.refusalsURL) {self.url = url@@ -105,10 +107,13 @@ public actor RefusalLog {/// 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) }+ if let kept, FileIdentity.of(url) == kept.file { return (kept.records, nil) }+ guard let read = BoundedRead.contents(at: url, maximum: 16 * 1_024 * 1_024) else { return (nil, .unreadable) }+ let data = read.datalet decoder = JSONDecoder()decoder.dateDecodingStrategy = LogTime.decodingif let records = try? decoder.decode([RefusalRecord].self, from: data) {+ kept = (read.file, records)return (records, nil)}// A row that a later version wrote, or that a hand edit broke, must not cost the other rows.@@ -137,6 +142,9 @@ public actor RefusalLog {encoder.outputFormatting = [.prettyPrinted, .sortedKeys]guard let data = try? encoder.encode(records) else { return false }try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)- return (try? data.write(to: url, options: .atomic)) != nil+ guard (try? data.write(to: url, options: .atomic)) != nil else { return false }+ // Every writer takes the lock, so the file here is the one just written.+ kept = FileIdentity.of(url).map { ($0, records) }+ return true}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swiftindex 2514f9d8..f45deeeb 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift@@ -117,6 +117,23 @@ struct RefusalLogTests {#expect(Set(records.map(\.source)) == ["Older", "New"])}+ @Test func readsUnchangedRefusalsWithoutDecodingThemAgain() async throws {+ let directory = try TemporaryDirectory()+ let url = directory.url.appending(path: "refusals.json")+ let refused = (0..<(RefusalLog.maximumRecords - 1)).map { failure("/Users/me/item-\($0)", .lastCopy) }+ await RefusalLog(url: url).add(refused, source: "Old", tool: "duplicates")+ let app = RefusalLog(url: url)++ let first = await app.processorTimeToLoad()+ let again = await app.processorTimeToLoad()+ await RefusalLog(url: url).add([failure("/Users/me/new", .notPermitted)], source: "Tool", tool: "space")+ let afterAnotherWriter = await app.load().records++ #expect(again < first / 10, "read in \(first), then in \(again)")+ #expect(afterAnotherWriter?.count == RefusalLog.maximumRecords)+ #expect(afterAnotherWriter?.contains { $0.source == "Tool" } == true)+ }+/// The file is Peel's, but any process the user runs can rewrite it.@Test func aRowThatMakesNoSenseCostsThatRowAlone() async throws {let directory = try TemporaryDirectory()@@ -323,3 +340,10 @@ struct RefusalLogTests {#expect(groups.last?.parts == [RemovalPart(source: "Editor", sourceKey: nil, tool: "applications")])}}++extension RefusalLog {+ /// Measured on the actor's own thread, where the read runs.+ fileprivate func processorTimeToLoad() -> Duration {+ processorTime { _ = load() }+ }+}diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swiftindex 98343db8..ee39cf38 100644--- a/Peel/Model/RemovalHistoryStore.swift+++ b/Peel/Model/RemovalHistoryStore.swift@@ -173,6 +173,7 @@ final class RemovalHistoryStore {private(set) var putBack: [Tool: Int] = [:]/// The count each page last listed under, kept here so a page off screen at a Put Back lists it when it returns.@ObservationIgnored private var listedAfterPutBack = ScannedRevisions()+ @ObservationIgnored private var listedRefusals: [RefusalRecord] = []/// Counts each change of what History lists. The lists are prepared off the main actor, and one prepared for an/// older change must never replace a newer one.private var listedChange = 0@@ -242,8 +243,12 @@ final class RemovalHistoryStore {refusalProblem = read.problemrefusalChange += 1let change = refusalChange- let listed = await Self.listed(read.records ?? [])+ let records = read.records ?? []+ // The refusals listed already, read again, change nothing; an older listing still on its way is dropped.+ guard records != listedRefusals else { return }+ let listed = await Self.listed(records)guard change == refusalChange else { return }+ listedRefusals = recordsrefusalBatches = listed.batchesrefusalSearchKeys = listed.searchKeysrevision += 1diff --git a/PeelTests/RemovalHistoryStoreTests.swift b/PeelTests/RemovalHistoryStoreTests.swiftnew file mode 100644index 00000000..20770f06--- /dev/null+++ b/PeelTests/RemovalHistoryStoreTests.swift@@ -0,0 +1,28 @@+import Foundation+@testable import Peel+import PeelCore+import Testing++@MainActor+struct RemovalHistoryStoreTests {+ @Test func aReadThatFindsNothingNewChangesNothing() async throws {+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: folder) }+ let refusals = RefusalLog(url: folder.appending(path: "refusals.json"))+ await refusals.add(+ [TrashFailure(url: URL(filePath: "/Users/me/kept"), reason: .lastCopy)], source: "Example", tool: "duplicates"+ )+ let history = RemovalHistoryStore(+ log: RemovalLog(url: folder.appending(path: "removals.json")),+ refusals: refusals,+ knowsTheExclusions: { true }+ )+ await history.load()+ let revision = history.revision++ await history.load()++ #expect(history.revision == revision)+ #expect(history.refusalBatches.count == 1)+ }+}