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.

Never write History or Not Moved bigger than Peel reads them back

Țugui Dragoșd55a59043331
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 37ac75c5..978753fc 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -159,8 +159,9 @@ the Homebrew page's uninstall and cleanups are Homebrew's own.
(`ShellReferences`, which reads the files zsh, bash, and fish start with and never changes them).
7. **Record.**
- Every removal goes into History (`removals.json`, through `RemovalLog`), with where each item came from and
- where it went, so it can be put back; History keeps the most recent 20,000 items. A removal is one entry,
- even when it moved what was selected on several pages.
+ where it went, so it can be put back; History keeps the most recent 20,000 items, fewer when their paths are
+ very long, since it never writes more than it reads back (`Batches.fitting`). A removal is one entry, even when
+ it moved what was selected on several pages.
- As it records, History adds what moved to the totals Home and the menu bar panel show (`totals.json`, through
`RemovalTotals`), so the app and `peel` count alike.
- Each item is also written down the moment it moves, and what the helper moves as soon as it answers each
diff --git a/GUIDE.md b/GUIDE.md
index 47baffa5..ccb231a6 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -307,8 +307,8 @@ It sets up the command line as well:
- **History:** everything Peel moved to the Trash, ready to put back, from the app and from Terminal alike, and
what it was asked to move and wouldn't, with the reason for each item. It puts back what is still in the Trash
- and keeps the latest 20,000 items, and, while Peel stays open, Undo in the Edit menu puts back the last removal
- you made in it.
+ and keeps the latest 20,000 items, fewer when their paths are very long, and, while Peel stays open, Undo in the
+ Edit menu puts back the last removal you made in it.
- **Exclusions:** files, folders, and apps Peel must never touch. An excluded app still appears in Applications, but
Peel won't offer to remove or reset it, and leaves out of every page the folders named with its identifier, such as
its caches; to keep its other files, such as plug-ins or a folder named after it, exclude them too. Add them in
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift
index 21e4a609..aa8b6cbb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift
@@ -3,28 +3,58 @@ import Foundation
/// The rule History and the refusal log share for staying quick to read: past a cap, the oldest removals are
/// dropped whole, because an entry cut in part would read as all there was.
enum Batches {
- /// Sorts `records` newest first and drops the oldest batches beyond `maximum`, each whole, never one in
- /// `protected`. A batch is dated by its oldest record, the date History shows for it.
+ /// Sorts `records` newest first and drops the oldest batches while what they `weigh` together is beyond
+ /// `maximum`, each whole, never one in `protected`. A batch is dated by its oldest record, the date History shows
+ /// for it.
static func trimmed<Record, Batch: Hashable>(
_ records: [Record],
maximum: Int,
+ weighing weight: (Record) -> Int = { _ in 1 },
batch: (Record) -> Batch,
date: (Record) -> Date,
keeping protected: Set<Batch> = []
) -> [Record] {
let sorted = records.sorted { date($0) > date($1) }
- guard sorted.count > maximum else { return sorted }
+ var total = sorted.reduce(0) { $0 + weight($1) }
+ guard total > maximum else { return sorted }
let batches = Dictionary(grouping: sorted, by: batch)
let dates = batches.mapValues { $0.map(date).min() ?? .distantPast }
- var total = sorted.count
var dropped: Set<Batch> = []
for key in batches.keys.sorted(by: { dates[$0] ?? .distantPast < dates[$1] ?? .distantPast })
where total > maximum {
guard !protected.contains(key) else { continue }
dropped.insert(key)
- total -= batches[key]?.count ?? 0
+ total -= batches[key]?.reduce(0) { $0 + weight($1) } ?? 0
}
return sorted.filter { !dropped.contains(batch($0)) }
}
+
+ /// `records` as `encode` writes them, in at most `limit` bytes: the oldest batches are dropped whole until they
+ /// fit, so the file is never bigger than its reader reads back. Batches in `protected` stay even when they alone
+ /// are bigger. Once over, it keeps to nine tenths of `limit`, so the removals that follow don't each pay for a fit.
+ static func fitting<Record, Batch: Hashable>(
+ _ records: [Record],
+ within limit: Int,
+ batch: (Record) -> Batch,
+ date: (Record) -> Date,
+ keeping protected: Set<Batch>,
+ encode: ([Record]) throws -> Data
+ ) rethrows -> (records: [Record], data: Data) {
+ var kept = records
+ var data = try encode(kept)
+ while data.count > limit {
+ // Each record weighs what it takes written alone, so one pass drops about as much as is too much.
+ let weighed = try kept.map { (record: $0, weight: try encode([$0]).count) }
+ let total = weighed.reduce(0) { $0 + $1.weight }
+ let fewer = trimmed(
+ weighed, maximum: total - (data.count - limit / 10 * 9), weighing: \.weight,
+ batch: { batch($0.record) }, date: { date($0.record) }, keeping: protected
+ ).map(\.record)
+ guard fewer.count < kept.count else { break }
+ kept = fewer
+ data = try encode(kept)
+ }
+ return (kept, data)
+ }
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
index d3acccee..cbd91e88 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
@@ -63,14 +63,21 @@ public enum RefusalLogProblem: Sendable, Equatable {
/// advisory lock on the file, as in `RemovalLog`, because the `peel` tool writes here too.
public actor RefusalLog {
static let maximumRecords = 5_000
+ static let maximumBytes = 16 * 1_024 * 1_024
public 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])?
private var problem: RefusalLogProblem?
+ private let readLimit: Int
public init(url: URL = RemovalHistory.refusalsURL) {
+ self.init(url: url, readLimit: Self.maximumBytes)
+ }
+
+ init(url: URL, readLimit: Int) {
self.url = url
+ self.readLimit = readLimit
}
/// The records, with what is still to be said about the file (`note`). Nil records when the file could not be
@@ -100,7 +107,7 @@ public actor RefusalLog {
existing + records, maximum: Self.maximumRecords, batch: { $0.batch ?? $0.id }, date: \.date,
keeping: [batch]
)
- guard write(kept) else {
+ guard write(kept, keeping: [batch]) else {
note(.couldNotRecord)
return problem
}
@@ -154,7 +161,7 @@ public actor RefusalLog {
note(nil)
return kept.records
}
- guard let read = BoundedRead.contents(at: url, maximum: 16 * 1_024 * 1_024) else {
+ guard let read = BoundedRead.contents(at: url, maximum: readLimit) else {
note(.unreadable)
return nil
}
@@ -199,16 +206,20 @@ public actor RefusalLog {
}
}
+ /// Writes `records`, less the oldest removals that wouldn't fit in what is read back, never one in `protected`.
@discardableResult
- private func write(_ records: [RefusalRecord]) -> Bool {
+ private func write(_ records: [RefusalRecord], keeping protected: Set<UUID> = []) -> Bool {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = LogTime.encoding
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
- guard let data = try? encoder.encode(records) else { return false }
+ guard let fitted = try? Batches.fitting(
+ records, within: readLimit, batch: { $0.batch ?? $0.id }, date: \.date, keeping: protected,
+ encode: { try encoder.encode($0) }
+ ) else { return false }
try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
- guard (try? data.write(to: url, options: .atomic)) != nil else { return false }
+ guard (try? fitted.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) }
+ kept = FileIdentity.of(url).map { ($0, fitted.records) }
return true
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
index e26ed42b..42a7cb10 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
@@ -29,8 +29,8 @@ public struct RemovalLogOutcome: Sendable {
public actor RemovalLog {
/// The most records the file keeps. Past this, the oldest batches are dropped whole, never in part.
static let maximumRecords = 20_000
- /// The largest file read as History. The file is Peel's, but any process of the user can rewrite it, and
- /// 20,000 records take about 6 MB.
+ /// The largest file read as History, since any process of the user can rewrite it. Peel never writes more:
+ /// records with long paths take several times what short ones do, and the oldest removals go first.
static let maximumBytes = 64 * 1_024 * 1_024
public nonisolated let url: URL
@@ -42,16 +42,18 @@ public actor RemovalLog {
private let journal: RemovalJournal
private let totals: URL
private let flush: @Sendable (String) -> Bool
+ private let readLimit: Int
public init(url: URL = RemovalHistory.defaultURL) {
self.init(url: url, flush: DriveFlush.file(at:))
}
- init(url: URL, flush: @escaping @Sendable (String) -> Bool) {
+ init(url: URL, flush: @escaping @Sendable (String) -> Bool, readLimit: Int = maximumBytes) {
self.url = url
journal = RemovalJournal(beside: url)
totals = RemovalTotals.url(beside: url)
self.flush = flush
+ self.readLimit = readLimit
}
/// Reads the log. The read takes the lock too, because reading a damaged file sets it aside and writes back
@@ -71,8 +73,9 @@ public actor RemovalLog {
whileNoOtherProcessWrites {
guard !records.isEmpty else { return RemovalLogOutcome(records: current(), problem: problem) }
guard let existing = current() else { return RemovalLogOutcome(records: nil, problem: problem) }
- let updated = Self.trimmed(existing + records, keeping: Set(records.map(\.batch)))
- guard write(updated, orNote: .couldNotRecord) else {
+ let new = Set(records.map(\.batch))
+ let trimmed = Self.trimmed(existing + records, keeping: new)
+ guard let updated = write(trimmed, keeping: new, orNote: .couldNotRecord) else {
journal.keep(records)
return RemovalLogOutcome(records: nil, problem: problem)
}
@@ -133,7 +136,7 @@ public actor RemovalLog {
whileNoOtherProcessWrites {
guard let existing = current() else { return RemovalLogOutcome(records: nil, problem: problem) }
let updated = existing.filter { !ids.contains($0.id) }
- return RemovalLogOutcome(records: write(updated, orNote: .couldNotUpdate) ? updated : nil, problem: problem)
+ return RemovalLogOutcome(records: write(updated, orNote: .couldNotUpdate), problem: problem)
}
}
@@ -172,8 +175,10 @@ public actor RemovalLog {
let interrupted = left.filter { !recorded.contains(RemovalJournal.Key($0.item)) }.map(\.recordToTakeIn)
var updated = records
if !interrupted.isEmpty {
- updated = Self.trimmed(records + interrupted, keeping: Set(interrupted.map(\.batch)))
- guard write(updated, orNote: .couldNotRecord) else { return records }
+ let taken = Set(interrupted.map(\.batch))
+ let trimmed = Self.trimmed(records + interrupted, keeping: taken)
+ guard let written = write(trimmed, keeping: taken, orNote: .couldNotRecord) else { return records }
+ updated = written
RemovalTotals.change(at: totals) { $0.add(interrupted) }
}
journal.forget(Set(left))
@@ -190,7 +195,7 @@ public actor RemovalLog {
note(nil)
return kept.records
}
- guard let read = BoundedRead.contents(at: url, maximum: Self.maximumBytes) else {
+ guard let read = BoundedRead.contents(at: url, maximum: readLimit) else {
note(.unreadable)
return nil
}
@@ -209,8 +214,8 @@ public actor RemovalLog {
return nil
}
note(.damaged(setAside: setAside))
- guard !readable.isEmpty, write(readable, orNote: .damaged(setAside: setAside)) else { return [] }
- return readable
+ guard !readable.isEmpty, let written = write(readable, orNote: .damaged(setAside: setAside)) else { return [] }
+ return written
}
/// A row of the file. `record` is nil when the row does not decode.
@@ -222,25 +227,32 @@ public actor RemovalLog {
}
}
- private func write(_ records: [RemovalRecord], orNote failure: RemovalLogProblem) -> Bool {
+ /// Writes `records`, less the oldest removals that wouldn't fit in what is read back, never one in `protected`,
+ /// and answers what it wrote, or nil when it couldn't.
+ private func write(
+ _ records: [RemovalRecord], keeping protected: Set<UUID> = [], orNote failure: RemovalLogProblem
+ ) -> [RemovalRecord]? {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = LogTime.encoding
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
do {
- let data = try encoder.encode(records)
+ let fitted = try Batches.fitting(
+ records, within: readLimit, batch: \.batch, date: \.date, keeping: protected,
+ encode: { try encoder.encode($0) }
+ )
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true
)
// `.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)
+ try fitted.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
+ kept = FileIdentity.of(url).map { ($0, fitted.records) }
+ return fitted.records
} catch {
// An unrecorded removal is the most serious problem, so a later failure never replaces it.
if problem != .couldNotRecord { note(failure) }
- return false
+ return nil
}
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BatchesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BatchesTests.swift
new file mode 100644
index 00000000..b564eae7
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BatchesTests.swift
@@ -0,0 +1,39 @@
+import Foundation
+@testable import PeelCore
+import Testing
+
+struct BatchesTests {
+ private struct Row {
+ let batch: Int
+ let date: Date
+ let bytes: Int
+ }
+
+ private func encode(_ rows: [Row]) -> Data {
+ Data(count: rows.reduce(0) { $0 + $1.bytes })
+ }
+
+ private func rows(batch: Int, count: Int, bytes: Int) -> [Row] {
+ (0..<count).map { _ in Row(batch: batch, date: Date(timeIntervalSince1970: Double(batch)), bytes: bytes) }
+ }
+
+ @Test func fitsWithRoomForWhatComesNextAndKeepsTheNewestWhole() {
+ let all = (0..<10).flatMap { rows(batch: $0, count: 3, bytes: 100) }
+
+ let fitted = Batches.fitting(
+ all, within: 2_000, batch: \.batch, date: \.date, keeping: [9], encode: encode
+ )
+
+ #expect(fitted.data.count <= 1_800)
+ #expect(fitted.records.filter { $0.batch == 9 }.count == 3)
+ #expect(!fitted.records.contains { $0.batch == 0 })
+ }
+
+ @Test func keepsWhatIsProtectedEvenWhenItAloneIsTooBig() {
+ let all = rows(batch: 1, count: 2, bytes: 100) + rows(batch: 2, count: 30, bytes: 100)
+
+ let fitted = Batches.fitting(all, within: 1_000, batch: \.batch, date: \.date, keeping: [2], encode: encode)
+
+ #expect(fitted.records.map(\.batch) == Array(repeating: 2, count: 30))
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
index 11983d89..dbf8be80 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
@@ -103,6 +103,24 @@ struct RefusalLogTests {
/// Past its cap the log drops the oldest removals whole, as History does: an entry cut in part would read as
/// all that was refused.
+ @Test func neverWritesMoreThanItReadsBack() async throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "Peel/refusals.json")
+ let log = RefusalLog(url: url, readLimit: 4_096)
+ let removals = [UUID(), UUID(), UUID()]
+ for (index, batch) in removals.enumerated() {
+ let failures = (0..<8).map { failure("/Users/me/書類書類書類/\(index)/\($0)", .lastCopy) }
+ let date = Date(timeIntervalSince1970: Double(index) * 60)
+ await log.add(failures, source: "Editor", tool: "duplicates", batch: batch, date: date)
+ }
+
+ let read = await RefusalLog(url: url, readLimit: 4_096).load()
+
+ let batches = try #require(read.records, "the list grew past what it reads back").map(\.batch)
+ #expect(batches.filter { $0 == removals[2] }.count == 8, "the newest removal was not kept whole")
+ #expect(!batches.contains(removals[0]), "the oldest removal was kept past the limit")
+ }
+
@Test func dropsTheOldestRemovalsWhole() async throws {
let directory = try TemporaryDirectory()
let log = RefusalLog(url: directory.url.appending(path: "refusals.json"))
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
index 7ec5e2f8..8323854c 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift
@@ -375,6 +375,23 @@ struct RemovalHistoryTests {
#expect(await log.add([Self.record(batch: UUID())]).records?.count == 1)
}
+ @Test func neverWritesMoreThanItReadsBack() async throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "Peel/removals.json")
+ let log = RemovalLog(url: url, flush: { _ in true }, readLimit: 4_096)
+ let removals = [UUID(), UUID(), UUID()]
+ for (index, batch) in removals.enumerated() {
+ let date = Date(timeIntervalSince1970: Double(index) * 60)
+ _ = await log.add((0..<4).map { Self.record(batch: batch, date: date, name: "書類書類書類 \(index) \($0)") })
+ }
+
+ let read = await RemovalLog(url: url, flush: { _ in true }, readLimit: 4_096).load()
+
+ let batches = try #require(read.records, "History grew past what it reads back").map(\.batch)
+ #expect(batches.filter { $0 == removals[2] }.count == 4, "the newest removal was not kept whole")
+ #expect(!batches.contains(removals[0]), "the oldest removal was kept past the limit")
+ }
+
@Test func startsNothingOverWhileHistoryCanBeRead() async throws {
let directory = try TemporaryDirectory()
let url = try directory.file("Peel/removals.json", contents: Data("[]".utf8))
diff --git a/README.md b/README.md
index 18aa9f63..0c2a0c49 100644
--- a/README.md
+++ b/README.md
@@ -165,9 +165,10 @@ and choose Uninstall with Peel, once the Finder extension is on in System Settin
<br>
Peel moves files to the Trash instead of deleting them, and History can put them back while they are still there
-(it keeps the latest 20,000 items). What can't be undone, such as Homebrew's own uninstall, Peel names before you
-confirm it. Peel selects for you only what it is sure, or nearly sure, belongs to the app, never a file another app
-uses, and refuses to touch places like iCloud Drive, your keychains, Mail, Messages, and photo libraries.
+(it keeps the latest 20,000 items, fewer when their paths are very long). What can't be undone, such as Homebrew's
+own uninstall, Peel names before you confirm it. Peel selects for you only what it is sure, or nearly sure, belongs
+to the app, never a file another app uses, and refuses to touch places like iCloud Drive, your keychains, Mail,
+Messages, and photo libraries.
</details>
diff --git a/SAFETY.md b/SAFETY.md
index f4838a1a..713064e2 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -140,7 +140,8 @@ link moves the link.
## Nothing of yours is deleted permanently
Peel never deletes anything of yours. Everything it removes goes to the Trash, and everything is recorded so
-History can put it back; History keeps the most recent 20,000 items, and what it forgets is still in the Trash.
+History can put it back; History keeps the most recent 20,000 items, fewer when their paths are very long, and
+what it forgets is still in the Trash.
The space is freed when *you* empty the Trash: Peel never does that for you.
That includes what `pkgutil` and Homebrew would delete:
diff --git a/docs/index.html b/docs/index.html
index f8f4d2be..78503c66 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -74,7 +74,7 @@
"@id": "https://peel.tuguidragos.com/#app"
},
"primaryImageOfPage": "https://peel.tuguidragos.com/images/social.png",
- "dateModified": "2026-10-22"
+ "dateModified": "2026-10-27"
},
{
"@type": "Person",
@@ -213,7 +213,7 @@
"name": "Can Peel delete something I need?",
"acceptedAnswer": {
"@type": "Answer",
- "text": "Peel moves files to the Trash instead of deleting them, and History can put them back while they’re still there (it keeps the latest 20,000 items). What can’t be undone, such as Homebrew’s own uninstall, Peel names before you confirm it. It never selects a file another app uses, and refuses to move iCloud Drive, your keychains, Mail, Messages, and photo libraries."
+ "text": "Peel moves files to the Trash instead of deleting them, and History can put them back while they’re still there (it keeps the latest 20,000 items, fewer when their paths are very long). What can’t be undone, such as Homebrew’s own uninstall, Peel names before you confirm it. It never selects a file another app uses, and refuses to move iCloud Drive, your keychains, Mail, Messages, and photo libraries."
}
},
{
@@ -864,7 +864,7 @@
</details>
<details>
<summary>Can Peel delete something I need?</summary>
- <p>Peel moves files to the Trash instead of deleting them, and History can put them back while they’re still there (it keeps the latest 20,000 items). What can’t be undone, such as Homebrew’s own uninstall, Peel names before you confirm it. It never selects a file another app uses, and refuses to move iCloud Drive, your keychains, Mail, Messages, and photo libraries.</p>
+ <p>Peel moves files to the Trash instead of deleting them, and History can put them back while they’re still there (it keeps the latest 20,000 items, fewer when their paths are very long). What can’t be undone, such as Homebrew’s own uninstall, Peel names before you confirm it. It never selects a file another app uses, and refuses to move iCloud Drive, your keychains, Mail, Messages, and photo libraries.</p>
</details>
<details>
<summary>Why does Peel show a smaller size than Finder?</summary>
diff --git a/docs/sitemap.xml b/docs/sitemap.xml
index fe2d5274..f0e0de2f 100644
--- a/docs/sitemap.xml
+++ b/docs/sitemap.xml
@@ -3,6 +3,6 @@
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://peel.tuguidragos.com/</loc>
- <lastmod>2026-10-22</lastmod>
+ <lastmod>2026-10-27</lastmod>
</url>
</urlset>