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.

Read History again only when its file changed

Țugui Dragoș57fcfd4dea91
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
index 6a554420..aab16e6e 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
@@ -35,6 +35,9 @@ public actor RemovalLog {
public nonisolated let url: URL
public private(set) var problem: RemovalLogProblem?
+ /// The records last read from the file or written to it, and the file they are in. A read of the same file,
+ /// unchanged, takes them instead of decoding it again; a write by any other process changes the file.
+ private var kept: (file: FileIdentity, records: [RemovalRecord])?
/// What removals moved and have not recorded yet, item by item.
private let journal: RemovalJournal
private let totals: URL
@@ -183,14 +186,20 @@ public actor RemovalLog {
note(nil)
return []
}
- guard let data = BoundedRead.data(at: url, maximum: Self.maximumBytes) else {
+ if let kept, FileIdentity.of(url) == kept.file {
+ note(nil)
+ return kept.records
+ }
+ guard let read = BoundedRead.contents(at: url, maximum: Self.maximumBytes) else {
note(.unreadable)
return nil
}
+ let data = read.data
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = LogTime.decoding
if let records = try? decoder.decode([RemovalRecord].self, from: data) {
note(nil)
+ kept = (read.file, records)
return records
}
// A row this version cannot read (written by a later version, or broken by hand) must not cost the rest.
@@ -225,6 +234,8 @@ public actor RemovalLog {
)
// `.atomic` writes a temporary file and renames it, so a crash leaves either the old log or the new one.
try data.write(to: url, options: .atomic)
+ // Every writer takes the lock, so the file here is the one just written.
+ kept = FileIdentity.of(url).map { ($0, records) }
return true
} catch {
// An unrecorded removal is the most serious problem, so a later failure never replaces it.
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/BoundedRead.swift b/Packages/PeelCore/Sources/PeelCore/Support/BoundedRead.swift
index 2f62a60a..dfa2e14f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/BoundedRead.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/BoundedRead.swift
@@ -16,7 +16,14 @@ enum BoundedRead {
/// after would let the file be swapped for a pipe in between. A symbolic link is followed, since users
/// link launch agents and settings in from a repository.
static func data(at url: URL, maximum: Int = maximumBytes, read: Read = { Darwin.read($0, $1, $2) }) -> Data? {
- guard let descriptor = openRegularFile(at: url, maximum: maximum) else { return nil }
+ contents(at: url, maximum: maximum, read: read)?.data
+ }
+
+ /// The bytes `data(at:maximum:read:)` reads, and the file they were read from as it was when it was opened.
+ static func contents(
+ at url: URL, maximum: Int = maximumBytes, read: Read = { Darwin.read($0, $1, $2) }
+ ) -> (data: Data, file: FileIdentity)? {
+ guard let (descriptor, info) = openRegularFile(at: url, maximum: maximum) else { return nil }
defer { close(descriptor) }
var data = Data()
@@ -32,12 +39,12 @@ enum BoundedRead {
return nil
}
}
- return data.count <= maximum ? data : nil
+ return data.count <= maximum ? (data, FileIdentity(info)) : nil
}
/// The first `count` bytes of the regular file at `url`, or the whole file when it is shorter, whatever its size.
static func prefix(of url: URL, count: Int) -> Data? {
- guard let descriptor = openRegularFile(at: url, maximum: .max) else { return nil }
+ guard let descriptor = openRegularFile(at: url, maximum: .max)?.descriptor else { return nil }
defer { close(descriptor) }
var buffer = [UInt8](repeating: 0, count: count)
@@ -60,13 +67,14 @@ enum BoundedRead {
/// Whether `url` opens as a regular file of at most `maximum` bytes, which is what `data(at:maximum:)` asks
/// before it reads.
static func opens(_ url: URL, maximum: Int = maximumBytes) -> Bool {
- guard let descriptor = openRegularFile(at: url, maximum: maximum) else { return false }
+ guard let descriptor = openRegularFile(at: url, maximum: maximum)?.descriptor else { return false }
close(descriptor)
return true
}
- /// A descriptor for the regular file at `url` when it is at most `maximum` bytes, which the caller closes.
- private static func openRegularFile(at url: URL, maximum: Int) -> Int32? {
+ /// A descriptor for the regular file at `url` when it is at most `maximum` bytes, which the caller closes, and
+ /// what `fstat(2)` says of it.
+ private static func openRegularFile(at url: URL, maximum: Int) -> (descriptor: Int32, info: stat)? {
let descriptor = open(url.path(percentEncoded: false), O_RDONLY | O_NONBLOCK | O_CLOEXEC)
guard descriptor >= 0 else { return nil }
var info = stat()
@@ -74,7 +82,7 @@ enum BoundedRead {
close(descriptor)
return nil
}
- return descriptor
+ return (descriptor, info)
}
static func propertyList(at url: URL, maximum: Int = maximumBytes) -> [String: Any]? {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
index 0d16f1a8..bf3759f6 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
@@ -436,6 +436,24 @@ struct RemovalHistoryTests {
#expect(await RemovalLog(url: url).load().records?.count == 80)
}
+ @Test func readsAnUnchangedHistoryWithoutDecodingItAgain() async throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "removals.json")
+ let batch = UUID()
+ let records = (0..<(RemovalLog.maximumRecords - 1)).map { Self.record(batch: batch, name: "Item\($0)") }
+ _ = await RemovalLog(url: url).add(records)
+ let app = RemovalLog(url: url)
+
+ let first = await app.processorTimeToLoad()
+ let again = await app.processorTimeToLoad()
+ _ = await RemovalLog(url: url).add([Self.record(batch: UUID(), name: "Tool")])
+ let afterAnotherWriter = await app.load().records
+
+ #expect(again < first / 10, "read in \(first), then in \(again)")
+ #expect(afterAnotherWriter?.count == RemovalLog.maximumRecords)
+ #expect(afterAnotherWriter?.contains { $0.source == "Tool" } == true)
+ }
+
@Test func keepsEveryRecordWhenAddsOverlap() async throws {
let directory = try TemporaryDirectory()
let log = RemovalLog(url: directory.url.appending(path: "Peel/removals.json"))
@@ -450,3 +468,10 @@ struct RemovalHistoryTests {
#expect(outcome.records?.count == 50, "kept \(outcome.records?.count ?? -1) of 50")
}
}
+
+extension RemovalLog {
+ /// Measured on the actor's own thread, where the read runs.
+ fileprivate func processorTimeToLoad() -> Duration {
+ processorTime { _ = load() }
+ }
+}