Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

History keeps each item's time to the millisecond

Țugui Dragoșc4293420b714
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/LogTime.swift b/Packages/PeelCore/Sources/PeelCore/Removal/LogTime.swift
new file mode 100644
index 00000000..3d16ef1e
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/LogTime.swift
@@ -0,0 +1,21 @@
+import Foundation
+
+/// How History's logs write a time: ISO 8601 to the millisecond, since one removal moves every part within a
+/// second and names them in the order they moved. A time written to the second reads as well.
+enum LogTime {
+ static let encoding = JSONEncoder.DateEncodingStrategy.custom { date, encoder in
+ var container = encoder.singleValueContainer()
+ try container.encode(date.formatted(milliseconds))
+ }
+
+ static let decoding = JSONDecoder.DateDecodingStrategy.custom { decoder in
+ let container = try decoder.singleValueContainer()
+ let text = try container.decode(String.self)
+ guard let date = (try? Date(text, strategy: milliseconds)) ?? (try? Date(text, strategy: .iso8601)) else {
+ throw DecodingError.dataCorruptedError(in: container, debugDescription: "Not an ISO 8601 time.")
+ }
+ return date
+ }
+
+ private static let milliseconds = Date.ISO8601FormatStyle(includingFractionalSeconds: true)
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
index 14f58d97..1c71f83c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
@@ -69,7 +69,7 @@ public actor RefusalLog {
guard url.isThere else { return [] }
guard let data = BoundedRead.data(at: url, maximum: 16 * 1_024 * 1_024) else { return nil }
let decoder = JSONDecoder()
- decoder.dateDecodingStrategy = .iso8601
+ decoder.dateDecodingStrategy = LogTime.decoding
if let records = try? decoder.decode([RefusalRecord].self, from: data) {
return records
}
@@ -94,7 +94,7 @@ public actor RefusalLog {
private func write(_ records: [RefusalRecord]) {
let encoder = JSONEncoder()
- encoder.dateEncodingStrategy = .iso8601
+ encoder.dateEncodingStrategy = LogTime.encoding
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
guard let data = try? encoder.encode(records) else { return }
try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
index a31c5da7..8d87d747 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
@@ -93,7 +93,7 @@ public actor RemovalLog {
return nil
}
let decoder = JSONDecoder()
- decoder.dateDecodingStrategy = .iso8601
+ decoder.dateDecodingStrategy = LogTime.decoding
if let records = try? decoder.decode([RemovalRecord].self, from: data) {
note(nil)
return records
@@ -120,7 +120,7 @@ public actor RemovalLog {
private func write(_ records: [RemovalRecord], orNote failure: RemovalLogProblem) -> Bool {
let encoder = JSONEncoder()
- encoder.dateEncodingStrategy = .iso8601
+ encoder.dateEncodingStrategy = LogTime.encoding
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
do {
let data = try encoder.encode(records)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
index 0ac289eb..71dc274e 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
@@ -163,6 +163,27 @@ struct RefusalLogTests {
])
}
+ /// The log keeps each refusal's time to the millisecond, so the parts of one removal, refused within a second,
+ /// keep the order they moved in however often the log is written again. A log written to the second reads too.
+ @Test func refusalsKeepTheOrderTheyWereRefusedInWithinASecond() async throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "refusals.json")
+ let batch = UUID()
+ let stored = """
+ [{"id":"\(UUID())","batch":"\(batch)","url":"file:///Users/me/a","reason":"claimed-since-scan","date":"2026-09-20T10:00:00.100Z","source":"com.gone.app","tool":"orphans"},
+ {"id":"\(UUID())","batch":"\(batch)","url":"file:///Users/me/b","reason":"last-copy","date":"2026-09-20T10:00:00.300Z","source":"Duplicates","sourceKey":"tool","tool":"duplicates"},
+ {"id":"\(UUID())","url":"file:///Users/me/old","reason":"not-permitted","date":"2026-09-19T10:00:00Z","source":"Editor","tool":"applications"}]
+ """
+ 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()
+
+ #expect(records.count == 4)
+ #expect(RefusalRecord.grouped(records).first { $0.id == batch }?.parts.map(\.tool) == ["orphans", "duplicates"])
+ #expect(records.contains { $0.date == ISO8601DateFormatter().date(from: "2026-09-19T10:00:00Z") })
+ }
+
/// History lists what was refused one removal to an entry, newest first. A record kept without a batch is an
/// entry of its own.
@Test func historyShowsEachRemovalsRefusalsAsOneEntry() throws {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
index 726b827b..e65671a5 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
@@ -36,6 +36,30 @@ struct RemovalHistoryTests {
#expect(loaded[0].trashedItem.originalURL.lastPathComponent.hasSuffix(".app"))
}
+ /// The log keeps each item's time to the millisecond, since one removal moves every part within a second and
+ /// names them in the order they moved. A log written to the second reads as well.
+ @Test func aRemovalsPartsKeepTheOrderTheyMovedInOnceTheLogIsReadAgain() async throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "removals.json")
+ let older = UUID()
+ let stored = """
+ [{"id":"\(UUID())","batch":"\(older)","originalURL":"file:///Applications/Old.app","trashedURL":"file:///Users/x/.Trash/Old.app","date":"2026-09-20T10:00:00Z","size":1,"source":"Old.app","tool":"applications"}]
+ """
+ try Data(stored.utf8).write(to: url)
+ let log = RemovalLog(url: url)
+ let batch = UUID()
+ let moment = Date(timeIntervalSince1970: 1_800_000_000)
+ for (offset, source, tool) in [(0.1, "com.gone.app", "orphans"), (0.2, "App Caches", "space"), (0.3, "SwiftTool", "projects"), (0.4, "Duplicates", "duplicates")] {
+ let item = TrashedItem(originalURL: URL(filePath: "/Users/x/\(source)"), trashedURL: URL(filePath: "/Users/x/.Trash/\(source)"), date: moment.addingTimeInterval(offset))
+ _ = await log.add([RemovalRecord(batch: batch, item: item, size: 1, source: source, tool: tool)])
+ }
+
+ let groups = RemovalRecord.grouped(try #require(await RemovalLog(url: url).load().records))
+
+ #expect(groups.first { $0.id == batch }?.parts.map(\.tool) == ["orphans", "space", "projects", "duplicates"])
+ #expect(groups.first { $0.id == older }?.date == ISO8601DateFormatter().date(from: "2026-09-20T10:00:00Z"))
+ }
+
@Test func removesOnlyTheRecordsAskedFor() async throws {
let directory = try TemporaryDirectory()
let log = RemovalLog(url: directory.url.appending(path: "removals.json"))
@@ -58,20 +82,20 @@ struct RemovalHistoryTests {
#expect(!trimmed.contains { $0.source == "Old0.app" })
}
- /// The log on disk uses these field names and ISO 8601 dates. Changing either would make every existing
- /// log unreadable.
+ /// The log on disk uses these field names and ISO 8601 times. Changing either would make every existing log
+ /// unreadable.
@Test func keepsTheStoredShapeOfARecord() throws {
let encoder = JSONEncoder()
- encoder.dateEncodingStrategy = .iso8601
- let stored = try encoder.encode([record("One.app", date: Date(timeIntervalSince1970: 5))])
+ encoder.dateEncodingStrategy = LogTime.encoding
+ let stored = try encoder.encode([record("One.app", date: Date(timeIntervalSince1970: 5.25))])
let fields = try #require((JSONSerialization.jsonObject(with: stored) as? [[String: Any]])?.first)
#expect(Set(fields.keys) == ["id", "batch", "originalURL", "trashedURL", "date", "size", "source", "tool"])
- #expect(fields["date"] as? String == "1970-01-01T00:00:05Z")
+ #expect(fields["date"] as? String == "1970-01-01T00:00:05.250Z")
let decoder = JSONDecoder()
- decoder.dateDecodingStrategy = .iso8601
- #expect(try decoder.decode([RemovalRecord].self, from: stored).first?.date == Date(timeIntervalSince1970: 5))
+ decoder.dateDecodingStrategy = LogTime.decoding
+ #expect(try decoder.decode([RemovalRecord].self, from: stored).first?.date == Date(timeIntervalSince1970: 5.25))
}
/// `removals.json` is a file any process can rewrite, and Swift's `+` traps on overflow, so the sizes read