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.

Keep the journal of removals as sure as History itself

Țugui Dragoșcded4d2646ff
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
index ed22260c..2c0ad521 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
@@ -33,13 +33,14 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {
source: String,
sourceKey: String? = nil,
tool: String,
- sharedStorage: Bool? = nil
+ sharedStorage: Bool? = nil,
+ disk: TrashedDisk? = nil
) {
self.id = id
self.batch = batch
originalURL = item.originalURL
trashedURL = item.trashedURL
- disk = TrashedDisk(of: item.trashedURL)
+ self.disk = disk ?? TrashedDisk(of: item.trashedURL)
date = item.date
identity = item.identity
self.size = size
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift
index d3e34daf..0fce5152 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift
@@ -52,6 +52,8 @@ struct RemovalJournal: Sendable {
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
+ /// The disk the item moved on, read then: that disk may be gone when the line is taken in.
+ var disk: TrashedDisk? = nil
/// 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.
@@ -59,7 +61,8 @@ struct RemovalJournal: Sendable {
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
+ batch: batch, item: item, size: nil, source: part.source, sourceKey: part.sourceKey, tool: part.tool,
+ disk: disk
)
}
}
@@ -88,6 +91,22 @@ struct RemovalJournal: Sendable {
self.history = history
}
+ /// Whether a line can be written here: there is no journal yet, or it opens as the file it should be.
+ var canBeWritten: Bool {
+ url.isMissing || (canBeRead && access(url.path(percentEncoded: false), W_OK) == 0)
+ }
+
+ private var canBeRead: Bool {
+ BoundedRead.opens(url, maximum: Self.maximumBytes)
+ }
+
+ /// Keeps a journal that can't be read beside a new one, under another name, and answers that name: while it stands
+ /// in its place, what a removal cut short leaves behind would be lost.
+ func setAsideIfUnreadable() -> URL? {
+ guard !url.isMissing, !canBeRead else { return nil }
+ return DamagedFile.setAside(url)
+ }
+
/// Whether History can be read, and so take in what is written here.
var historyCanBeRead: Bool {
RemovalLog.canBeRead(at: history)
@@ -105,7 +124,12 @@ struct RemovalJournal: Sendable {
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 entry = { item in
+ Entry(
+ writer: writer, batch: recorded?.batch ?? batch, item: item, part: recorded?.part,
+ disk: TrashedDisk(of: item.trashedURL)
+ )
+ }
let lines = items
.filter { !PathComponents.isPath(journal, atOrInside: $0.originalURL.path(percentEncoded: false)) }
.compactMap { item in (try? Self.encoder.encode(entry(item))) }
@@ -189,10 +213,12 @@ struct RemovalJournal: Sendable {
}
private func read() -> [Entry] {
- guard let data = BoundedRead.data(at: url, maximum: 64 * 1_024 * 1_024) else { return [] }
+ guard let data = BoundedRead.data(at: url, maximum: Self.maximumBytes) else { return [] }
return data.split(separator: UInt8(ascii: "\n")).compactMap { try? Self.decoder.decode(Entry.self, from: $0) }
}
+ private static let maximumBytes = 64 * 1_024 * 1_024
+
private static let encoder: JSONEncoder = {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = LogTime.encoding
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
index 4417c487..63affec4 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
@@ -125,8 +125,9 @@ public actor RemovalLog {
url.isMissing || BoundedRead.opens(url, maximum: maximumBytes)
}
- /// Whether a removal could be recorded in History at `url` now: the folder it is written into can be written, and
- /// its disk has room for the copy a safe write makes of the whole file, with a megabyte to spare.
+ /// Whether a removal could be recorded in History at `url` now: the folder it is written into can be written, its
+ /// disk has room for the copy a safe write makes of the whole file, with a megabyte to spare, and the journal
+ /// beside it can take what moves meanwhile.
public static func canBeWritten(
at url: URL = RemovalHistory.defaultURL,
freeSpace: (URL) -> UInt64? = RemovalLog.freeSpace(at:)
@@ -135,7 +136,7 @@ public actor RemovalLog {
while folder.isMissing, folder.path(percentEncoded: false) != "/" { folder = folder.deletingLastPathComponent() }
guard access(folder.path(percentEncoded: false), W_OK) == 0, let free = freeSpace(folder) else { return false }
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize).map { UInt64($0) } ?? 0
- return free >= size + 1_000_000
+ return free >= size + 1_000_000 && RemovalJournal(beside: url).canBeWritten
}
/// The space free on the disk holding `folder`, as `statfs(2)` gives it.
@@ -199,6 +200,9 @@ public actor RemovalLog {
/// lines go. An item History already has is not recorded again: a process may have stopped after writing
/// History and before letting its lines go.
private func takingInInterrupted(_ records: [RemovalRecord]) -> [RemovalRecord] {
+ if let setAside = journal.setAsideIfUnreadable() {
+ note(.damaged(setAside: setAside))
+ }
let left = journal.left()
guard !left.isEmpty else { return records }
let recorded = Set(records.map { RemovalJournal.Key($0.trashedItem) })
@@ -212,7 +216,9 @@ public actor RemovalLog {
updated = written
RemovalTotals.change(at: totals) { $0.add(interrupted) }
}
- journal.forget(Set(left))
+ if flush(url.path(percentEncoded: false)) {
+ journal.forget(Set(left))
+ }
return updated
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
index 063eb16d..05b383d0 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
@@ -779,6 +779,7 @@ public struct TrashService: Sendable {
func restore(_ item: TrashedItem, canUseHelper: Bool = false) async -> RestoreFailure? {
let failure = await moveBack(item, canUseHelper: canUseHelper)
if failure == nil {
+ journal?.forget([item])
// The label comes from History, which any process of the user can rewrite, so the job starts only as the
// file now back in place declares it.
if let label = item.stoppedJob,
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift
index 1ed09f2f..1fd28b8b 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalJournalTests.swift
@@ -133,6 +133,100 @@ struct RemovalJournalTests {
#expect(flushed.withLock { $0.first?.waiting } == 1, "the journal let the item go before History was on the drive")
}
+ @Test func historyIsOnTheDriveBeforeTheJournalLetsGoOfARemovalCutShort() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let journal = RemovalJournal(beside: history)
+ journal.note([item("com.example.app", in: directory)], batch: UUID(), by: try endedProcess())
+ let flushed = Mutex<[Int]>([])
+ let log = RemovalLog(url: history) { _ in
+ flushed.withLock { $0.append(journal.entries().count) }
+ return true
+ }
+
+ _ = await log.load()
+
+ #expect(flushed.withLock { $0 } == [1], "the journal let the item go before History was on the drive")
+ #expect(journal.entries().isEmpty)
+ }
+
+ @Test func aRemovalCutShortStaysInTheJournalWhileHistoryIsNotOnTheDrive() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let journal = RemovalJournal(beside: history)
+ let moved = item("com.example.app", in: directory)
+ journal.note([moved], batch: UUID(), by: try endedProcess())
+ let log = RemovalLog(url: history) { _ in false }
+
+ let first = await log.load()
+ let second = await log.load()
+
+ #expect(journal.entries().count == 1)
+ #expect(first.records?.count == 1)
+ #expect(second.records?.count == 1, "it was taken in twice")
+ }
+
+ @Test func nothingMovesWhileTheJournalCannotBeWritten() throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let journal = RemovalJournal(beside: history)
+ try FileManager.default.createDirectory(at: journal.url, withIntermediateDirectories: true)
+
+ #expect(!RemovalLog.canBeWritten(at: history))
+ #expect(!journal.historyCanBeWritten)
+ }
+
+ @Test func aJournalThatCannotBeReadIsKeptAsideAndSaid() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let journal = RemovalJournal(beside: history)
+ try FileManager.default.createDirectory(at: journal.url, withIntermediateDirectories: true)
+
+ let outcome = await RemovalLog(url: history).load()
+
+ guard case .damaged(let aside) = outcome.problem else {
+ Issue.record("nothing said: \(String(describing: outcome.problem))")
+ return
+ }
+ #expect(aside.isThere)
+ #expect(journal.url.isMissing)
+ #expect(RemovalLog.canBeWritten(at: history))
+ }
+
+ @Test func anItemPutBackLeavesTheJournal() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "home/Peel/removals.json")
+ let journal = RemovalJournal(beside: history)
+ let trash = try directory.directory("home/.Trash")
+ let file = try directory.file("home/Library/Caches/com.example.app/file", bytes: 10)
+ let folder = file.deletingLastPathComponent()
+ let service = service(in: directory, journal: journal) { url in
+ let destination = trash.appending(path: url.lastPathComponent)
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+
+ let moved = await service.trash([folder])
+ let item = try #require(moved.trashed.first)
+ #expect(journal.entries().count == 1)
+
+ #expect(await service.restore(item) == nil)
+
+ #expect(journal.entries().isEmpty, "it would come back as a removal whose items are no longer in the Trash")
+ }
+
+ @Test func anItemsDiskIsTheOneItMovedOn() throws {
+ let directory = try TemporaryDirectory()
+ let disk = try JSONDecoder().decode(
+ TrashedDisk.self, from: Data(#"{"volume": "ABC", "path": ".Trashes/501/file"}"#.utf8)
+ )
+ let entry = RemovalJournal.Entry(
+ writer: .current, batch: UUID(), item: item("com.example.app", in: directory), disk: disk
+ )
+
+ #expect(entry.recordToTakeIn.disk == disk)
+ }
+
/// An item History already has is never recorded twice, as when a process wrote History and stopped before it
/// could let the journal go.
@Test func anItemHistoryHasIsNotRecordedAgain() async throws {