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.

The totals since install count what peel moves too

Țugui Dragoșf8a347d85a57
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 916df1c2..9d1e6d56 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -92,12 +92,13 @@ Take the most common case, uninstalling an app. Every other page follows the sam
6. **Finish.** Only for what really moved: the launch jobs whose files went are stopped, and macOS is told to
forget the preference domains whose files went.
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. Each item is also written down the moment it
- moves (`removals.journal`, through `RemovalJournal`), so what a removal cut short moved reaches History the
- next time it is read, as an interrupted removal, and quitting the app waits for a removal until History has it
- (`QuitGuard`). While History cannot be read nothing moves (`RemovalLog.canBeRead`, asked by `TrashService`
- before a removal) until the History page starts it over. What Peel refused to move is recorded too
+ 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. As it records, History adds what moved to the totals Home
+ shows (`totals.json`, through `RemovalTotals`), so the app and `peel` count alike. Each item is also written down
+ the moment it moves (`removals.journal`, through `RemovalJournal`), so what a removal cut short moved reaches
+ History the next time it is read, as an interrupted removal, and quitting the app waits for a removal until
+ History has it (`QuitGuard`). While History cannot be read nothing moves (`RemovalLog.canBeRead`, asked by
+ `TrashService` before a removal) until the History page starts it over. What Peel refused to move is recorded too
(`refusals.json`), and History lists it under Not Moved, one removal to an entry.
8. **Put back.** History's Put Back reads its record as a request, not as a fact: an item returns only from a
real Trash, only to a place the guard allows, only when it is the item that went (`TrashedItem.identity`,
@@ -195,6 +196,7 @@ where a Homebrew install takes them from.
| `~/Library/Application Support/Peel/removals.json` | History: every removal, so it can be put back. |
| `~/Library/Application Support/Peel/removals.journal` | What a removal has moved so far, item by item, until History has it. |
| `~/Library/Application Support/Peel/refusals.json` | What Peel was asked to move and refused, and why. |
+| `~/Library/Application Support/Peel/totals.json` | The totals Home and the menu bar panel show: what the app and `peel` moved since Peel was installed. |
| `~/Library/Application Support/Peel/exclusions.json` | The user's exclusions. |
| `~/Library/Application Support/Peel/Preference Backups/` | The settings Peel saved before resetting an app. |
| `~/Library/Application Support/Peel/digests.bin` | What Duplicates already read, so an unchanged file isn't read again. |
@@ -204,7 +206,7 @@ where a Homebrew install takes them from.
| `~/Library/Application Support/Peel/app-folders.json` | The folders the user chose for Peel to look for apps in, beside the Applications folders. |
| `~/Library/Application Support/Peel/homebrew.json` | The `brew` the user chose for a Homebrew in a folder of its own, which the app and `peel` run. |
| `/private/var/db/com.tuguidragos.Peel.Helper/` | The helper's ledger of what it moved. |
-| Peel's preferences | Settings, the totals Home shows, what each tool found the last time it looked, and the last answer of each update check. |
+| Peel's preferences | Settings, the day Peel was installed, what each tool found the last time it looked, and the last answer of each update check. |
Remove Peel, in Settings, takes all of it to the Trash. The helper moves its own ledger there, since nothing else
can, just before Peel unregisters it. It is the only way Peel is removed: Peel's own page in Applications, and
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
index fe4dd699..3194b404 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
@@ -37,10 +37,12 @@ public actor RemovalLog {
public private(set) var problem: RemovalLogProblem?
/// What removals moved and have not recorded yet, item by item.
private let journal: RemovalJournal
+ private let totals: URL
public init(url: URL = RemovalHistory.defaultURL) {
self.url = url
journal = RemovalJournal(beside: url)
+ totals = RemovalTotals.url(beside: url)
}
/// Reads the log. The read takes the lock too, because reading a damaged file sets it aside and writes back
@@ -62,6 +64,7 @@ public actor RemovalLog {
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 { return RemovalLogOutcome(records: nil, problem: problem) }
+ RemovalTotals.change(at: totals) { $0.add(records) }
journal.forget(records.map(\.trashedItem))
// A removal that is recorded clears an earlier `.couldNotRecord`.
if problem == .couldNotRecord { problem = nil }
@@ -69,6 +72,11 @@ public actor RemovalLog {
}
}
+ /// Adds totals the app kept before `peel` counted too. False when they could not be written.
+ public func takeIn(_ earlier: RemovalTotals) -> Bool {
+ whileNoOtherProcessWrites { RemovalTotals.change(at: totals) { $0.takeIn(earlier) } }
+ }
+
/// Whether History at `url` can be read, known without reading it: it is not there yet, or it opens as the file
/// it should be. A History that cannot be read is never written over, and nothing moves meanwhile.
public static func canBeRead(at url: URL = RemovalHistory.defaultURL) -> Bool {
@@ -130,6 +138,7 @@ public actor RemovalLog {
if !interrupted.isEmpty {
updated = Self.trimmed(records + interrupted, keeping: Set(interrupted.map(\.batch)))
guard write(updated, orNote: .couldNotRecord) else { return records }
+ RemovalTotals.change(at: totals) { $0.add(interrupted) }
}
journal.forget(Set(left))
return updated
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalTotals.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalTotals.swift
new file mode 100644
index 00000000..8517707a
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalTotals.swift
@@ -0,0 +1,94 @@
+public import Foundation
+internal import PeelPrivileged
+
+/// Running totals of what Peel and `peel` have moved to the Trash since Peel was installed, kept in `totals.json`
+/// beside History. They are not worked out from History, which is capped and drops whole batches once it is full,
+/// so a total taken from it would go down over time. `RemovalLog` adds to them as it records, whoever records.
+public struct RemovalTotals: Sendable, Equatable, Codable {
+ /// Incomplete once a removal held something Peel could not measure: the total is then only the least it can be.
+ public private(set) var bytes = SizeTotal(known: 0, isComplete: true)
+ public private(set) var items = 0
+ public private(set) var apps = 0
+ public private(set) var biggest = SizeTotal(known: 0, isComplete: true)
+ /// The removal counted last and what it has moved so far: a removal of several parts is recorded a part at a
+ /// time, and it is the whole of it that can be the biggest.
+ private var last: Removal?
+ /// Whether the totals the app kept on its own, before `peel` counted too, were added.
+ private var tookInEarlier = false
+
+ private struct Removal: Sendable, Equatable, Codable {
+ let batch: UUID
+ let bytes: SizeTotal
+ }
+
+ private static let maximumBytes = 64 * 1_024
+
+ public init() {}
+
+ public init(bytes: SizeTotal, items: Int, apps: Int, biggest: SizeTotal) {
+ (self.bytes, self.items, self.apps, self.biggest) = (bytes, items, apps, biggest)
+ }
+
+ /// Counts what `records` moved. Apps are counted by the bundles that moved, so five apps removed together
+ /// count as five, and a helper app kept under a Library folder is a leftover rather than an app.
+ mutating func add(_ records: [RemovalRecord]) {
+ for record in records {
+ let size = SizeTotal([record.size])
+ bytes = bytes.adding(size)
+ items = items.addingCapped(1)
+ let url = record.originalURL
+ if url.pathExtension.lowercased() == "app", !url.pathComponents.contains("Library") {
+ apps = apps.addingCapped(1)
+ }
+ let soFar = last?.batch == record.batch ? last?.bytes : nil
+ let removal = Removal(batch: record.batch, bytes: soFar.map { $0.adding(size) } ?? size)
+ last = removal
+ if removal.bytes.known > biggest.known {
+ biggest = removal.bytes
+ }
+ }
+ }
+
+ /// Adds, once, the totals the app kept before `peel` counted too, which share no removal with these.
+ mutating func takeIn(_ other: RemovalTotals) {
+ guard !tookInEarlier else { return }
+ tookInEarlier = true
+ bytes = bytes.adding(other.bytes)
+ items = items.addingCapped(other.items)
+ apps = apps.addingCapped(other.apps)
+ if other.biggest.known > biggest.known {
+ biggest = other.biggest
+ }
+ }
+
+ static func url(beside history: URL) -> URL {
+ history.deletingLastPathComponent().appending(path: "totals.json")
+ }
+
+ /// The totals kept beside `history`, or none when they cannot be read.
+ public static func read(beside history: URL = RemovalHistory.defaultURL) -> RemovalTotals {
+ stored(at: url(beside: history)) ?? RemovalTotals()
+ }
+
+ /// Changes the totals at `url`. A file that opens and is not the totals is kept aside under another name, and
+ /// counting starts again; one that cannot be opened is left as it is. False when nothing was written.
+ @discardableResult
+ static func change(at url: URL, _ change: (inout RemovalTotals) -> Void) -> Bool {
+ guard var totals = stored(at: url) ?? startedAgain(at: url) else { return false }
+ change(&totals)
+ guard let data = try? JSONEncoder().encode(totals) else { return false }
+ return (try? data.write(to: url, options: .atomic)) != nil
+ }
+
+ /// The totals at `url`: none yet when there is no file, and nil when the file cannot be read as the totals.
+ private static func stored(at url: URL) -> RemovalTotals? {
+ guard !url.isMissing else { return RemovalTotals() }
+ guard let data = BoundedRead.data(at: url, maximum: maximumBytes) else { return nil }
+ return try? JSONDecoder().decode(RemovalTotals.self, from: data)
+ }
+
+ private static func startedAgain(at url: URL) -> RemovalTotals? {
+ guard BoundedRead.data(at: url, maximum: maximumBytes) != nil, DamagedFile.setAside(url) != nil else { return nil }
+ return RemovalTotals()
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/SizeTotal.swift b/Packages/PeelCore/Sources/PeelCore/Support/SizeTotal.swift
index a9bb4228..98bd572b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/SizeTotal.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/SizeTotal.swift
@@ -1,6 +1,6 @@
/// A sum of sizes, some of which may be unknown. An unknown size is never counted as zero: it marks the
/// total incomplete.
-public struct SizeTotal: Sendable, Hashable, Comparable {
+public struct SizeTotal: Sendable, Hashable, Comparable, Codable {
public let known: Int64
/// False when some size is unknown, so `known` is only the least the total can be.
public let isComplete: Bool
@@ -21,6 +21,10 @@ public struct SizeTotal: Sendable, Hashable, Comparable {
self.init(known: known, isComplete: isComplete)
}
+ public func adding(_ other: SizeTotal) -> SizeTotal {
+ SizeTotal(known: known.addingCapped(other.known), isComplete: isComplete && other.isComplete)
+ }
+
/// How the total reads: a size, the least it can be, or nothing known at all.
public enum Reading: Sendable, Hashable {
case exactly(Int64)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalTotalsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalTotalsTests.swift
new file mode 100644
index 00000000..a8530c95
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalTotalsTests.swift
@@ -0,0 +1,153 @@
+import Foundation
+@testable import PeelCore
+import Testing
+
+struct RemovalTotalsTests {
+ private func record(_ path: String, size: Int64?, batch: UUID) -> RemovalRecord {
+ let url = URL(filePath: path)
+ return RemovalRecord(
+ batch: batch,
+ item: TrashedItem(originalURL: url, trashedURL: URL(filePath: "/Users/x/.Trash").appending(path: url.lastPathComponent), date: .now),
+ size: size,
+ source: "Example",
+ tool: "applications"
+ )
+ }
+
+ @Test func countsWhatEitherProcessRecords() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let app = RemovalLog(url: history)
+ let commandLine = RemovalLog(url: history)
+
+ _ = await app.add([record("/Applications/Example.app", size: 300, batch: UUID())])
+ _ = await commandLine.add([record("/Users/x/Library/Caches/org.example.tool", size: 200, batch: UUID())])
+
+ let totals = RemovalTotals.read(beside: history)
+ #expect(totals.bytes == SizeTotal(known: 500, isComplete: true))
+ #expect(totals.items == 2)
+ #expect(totals.apps == 1)
+ #expect(totals.biggest == SizeTotal(known: 300, isComplete: true))
+ }
+
+ @Test func aRemovalRecordedPartByPartIsOneRemovalForTheBiggest() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let log = RemovalLog(url: history)
+ let pass = UUID()
+
+ _ = await log.add([record("/Users/x/Library/Caches/org.example.one", size: 100, batch: pass)])
+ _ = await log.add([record("/Users/x/Library/Caches/org.example.two", size: 200, batch: pass)])
+ _ = await log.add([record("/Users/x/Library/Caches/org.example.three", size: 250, batch: UUID())])
+
+ let totals = RemovalTotals.read(beside: history)
+ #expect(totals.bytes.known == 550)
+ #expect(totals.biggest == SizeTotal(known: 300, isComplete: true))
+ }
+
+ @Test func anItemNotMeasuredLeavesTheTotalTheLeastItCanBe() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+
+ _ = await RemovalLog(url: history).add([
+ record("/Users/x/Library/Caches/org.example.one", size: 100, batch: UUID()),
+ record("/Users/x/Library/Caches/org.example.two", size: nil, batch: UUID()),
+ ])
+
+ let totals = RemovalTotals.read(beside: history)
+ #expect(totals.bytes == SizeTotal(known: 100, isComplete: false))
+ #expect(totals.items == 2)
+ }
+
+ @Test func countsAppsByTheBundlesThatMoved() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let batch = UUID()
+
+ _ = await RemovalLog(url: history).add([
+ record("/Applications/Example.app", size: 10, batch: batch),
+ record("/Applications/Other.app", size: 10, batch: batch),
+ record("/Users/x/Library/Application Support/Example/Helper.app", size: 10, batch: batch),
+ ])
+
+ #expect(RemovalTotals.read(beside: history).apps == 2)
+ }
+
+ @Test func aRemovalCutShortCountsOnceHistoryTakesItIn() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let process = Process()
+ process.executableURL = URL(filePath: "/usr/bin/true")
+ try process.run()
+ process.waitUntilExit()
+ let moved = TrashedItem(
+ originalURL: URL(filePath: "/Users/x/Library/Caches/org.example.app"),
+ trashedURL: URL(filePath: "/Users/x/.Trash/org.example.app"),
+ date: .now
+ )
+ RemovalJournal(beside: history).note([moved], batch: UUID(), by: RemovalJournal.Writer(pid: process.processIdentifier, started: 1))
+
+ _ = await RemovalLog(url: history).load()
+
+ let totals = RemovalTotals.read(beside: history)
+ #expect(totals.items == 1)
+ #expect(totals.bytes == SizeTotal(known: 0, isComplete: false))
+ }
+
+ @Test func nothingRecordedCountsNothing() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+
+ _ = await RemovalLog(url: history).add([])
+
+ #expect(RemovalTotals.read(beside: history) == RemovalTotals())
+ }
+
+ @Test func takesInTotalsKeptBeforeOnce() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let log = RemovalLog(url: history)
+ _ = await log.add([record("/Users/x/Library/Caches/org.example.tool", size: 200, batch: UUID())])
+ let earlier = RemovalTotals(
+ bytes: SizeTotal(known: 1_000, isComplete: false),
+ items: 7,
+ apps: 2,
+ biggest: SizeTotal(known: 900, isComplete: true)
+ )
+
+ #expect(await log.takeIn(earlier))
+ #expect(await log.takeIn(earlier))
+
+ let totals = RemovalTotals.read(beside: history)
+ #expect(totals.bytes == SizeTotal(known: 1_200, isComplete: false))
+ #expect(totals.items == 8)
+ #expect(totals.apps == 2)
+ #expect(totals.biggest == SizeTotal(known: 900, isComplete: true))
+ }
+
+ @Test func setsAsideTotalsItCannotRead() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let file = history.deletingLastPathComponent().appending(path: "totals.json")
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("not the totals".utf8).write(to: file)
+
+ _ = await RemovalLog(url: history).add([record("/Users/x/Library/Caches/org.example.tool", size: 200, batch: UUID())])
+
+ #expect(RemovalTotals.read(beside: history).items == 1)
+ let kept = try FileManager.default.contentsOfDirectory(atPath: file.deletingLastPathComponent().path(percentEncoded: false))
+ #expect(kept.contains { $0.hasPrefix("totals-damaged-") })
+ }
+
+ @Test func historyIsRecordedWhenTheTotalsCannotBeWritten() async throws {
+ let directory = try TemporaryDirectory()
+ let history = directory.url.appending(path: "Peel/removals.json")
+ let file = history.deletingLastPathComponent().appending(path: "totals.json")
+ try FileManager.default.createDirectory(at: file, withIntermediateDirectories: true)
+
+ let outcome = await RemovalLog(url: history).add([record("/Users/x/Library/Caches/org.example.tool", size: 200, batch: UUID())])
+
+ #expect(outcome.records?.count == 1)
+ #expect(RemovalTotals.read(beside: history) == RemovalTotals())
+ }
+}
diff --git a/Peel/Model/LifetimeStats.swift b/Peel/Model/LifetimeStats.swift
index 958f1542..f5896170 100644
--- a/Peel/Model/LifetimeStats.swift
+++ b/Peel/Model/LifetimeStats.swift
@@ -2,44 +2,46 @@ import Foundation
import Observation
import PeelCore
-/// Running totals of what Peel has removed since it was installed.
-///
-/// They are not worked out from History: that log is capped and drops whole batches once it is full, so a
-/// total taken from it would go down over time. These counters only go up, and they are kept in the app's
-/// user defaults rather than in the log.
+/// What Peel and `peel` have moved to the Trash since Peel was installed, as Home and the menu bar panel show it.
+/// History adds to the totals whichever of the two records (`RemovalTotals`), so they are read, never counted here.
@Observable
final class LifetimeStats {
- private enum Key {
- static let installed = "statsInstalledOn"
+ private static let installedKey = "statsInstalledOn"
+
+ /// Where the app kept its totals before `peel` counted too.
+ private enum Earlier {
static let bytes = "statsBytesFreed"
static let bytesIncomplete = "statsBytesFreedIsIncomplete"
static let items = "statsItemsRemoved"
static let apps = "statsAppsRemoved"
static let biggest = "statsBiggestCleanUp"
static let biggestIncomplete = "statsBiggestCleanUpIsIncomplete"
+ static let all = [bytes, bytesIncomplete, items, apps, biggest, biggestIncomplete]
}
private let defaults: UserDefaults
+ private let history: URL
private(set) var installedOn: Date
- /// Incomplete once a removal held something Peel could not measure: the total is then only the least it can be.
- private(set) var bytesFreed: SizeTotal
- private(set) var itemsRemoved: Int
- private(set) var appsRemoved: Int
- private(set) var biggestCleanUp: SizeTotal
+ private(set) var totals: RemovalTotals
- init(defaults: UserDefaults = .standard, bundle: URL = Bundle.main.bundleURL) {
+ init(
+ defaults: UserDefaults = .standard,
+ bundle: URL = Bundle.main.bundleURL,
+ history: URL = RemovalHistory.defaultURL
+ ) {
self.defaults = defaults
- installedOn = defaults.object(forKey: Key.installed) as? Date ?? Self.arrival(of: bundle)
- // Any process can write these preferences, so a total below zero is read as none, and every sum below
- // is capped rather than allowed to trap.
- bytesFreed = SizeTotal(known: max(0, Int64(defaults.integer(forKey: Key.bytes))), isComplete: !defaults.bool(forKey: Key.bytesIncomplete))
- itemsRemoved = max(0, defaults.integer(forKey: Key.items))
- appsRemoved = max(0, defaults.integer(forKey: Key.apps))
- biggestCleanUp = SizeTotal(known: max(0, Int64(defaults.integer(forKey: Key.biggest))), isComplete: !defaults.bool(forKey: Key.biggestIncomplete))
- defaults.set(installedOn, forKey: Key.installed)
+ self.history = history
+ installedOn = defaults.object(forKey: Self.installedKey) as? Date ?? Self.arrival(of: bundle)
+ totals = RemovalTotals.read(beside: history)
+ defaults.set(installedOn, forKey: Self.installedKey)
}
+ var bytesFreed: SizeTotal { totals.bytes }
+ var itemsRemoved: Int { totals.items }
+ var appsRemoved: Int { totals.apps }
+ var biggestCleanUp: SizeTotal { totals.biggest }
+
/// True once Peel has removed something. Home shows the totals only then, so a new install does not show
/// a row of zeros.
var hasCleaned: Bool { itemsRemoved > 0 }
@@ -48,6 +50,35 @@ final class LifetimeStats {
/// cleanup, showing both would say the same thing twice.
var hasABiggestCleanUp: Bool { biggestCleanUp.known > 0 && biggestCleanUp != bytesFreed }
+ /// Reads the totals again: after a removal, and whenever Peel comes forward, since `peel` adds to them too.
+ func reload() {
+ let read = RemovalTotals.read(beside: history)
+ if read != totals {
+ totals = read
+ }
+ }
+
+ /// Adds the totals the app kept in its preferences to the shared ones, then forgets them there.
+ func takeInEarlierTotals() async {
+ guard defaults.object(forKey: Earlier.items) != nil else { return }
+ // Any process can write these preferences, so a total below zero is read as none.
+ let earlier = RemovalTotals(
+ bytes: SizeTotal(
+ known: max(0, Int64(defaults.integer(forKey: Earlier.bytes))),
+ isComplete: !defaults.bool(forKey: Earlier.bytesIncomplete)
+ ),
+ items: max(0, defaults.integer(forKey: Earlier.items)),
+ apps: max(0, defaults.integer(forKey: Earlier.apps)),
+ biggest: SizeTotal(
+ known: max(0, Int64(defaults.integer(forKey: Earlier.biggest))),
+ isComplete: !defaults.bool(forKey: Earlier.biggestIncomplete)
+ )
+ )
+ guard await RemovalLog(url: history).takeIn(earlier) else { return }
+ Earlier.all.forEach(defaults.removeObject(forKey:))
+ reload()
+ }
+
/// The date `bundle` was installed, which is the date it was added to its folder.
///
/// `creationDate` is only a fallback: a bundle copied out of a disk image keeps the date its developer
@@ -57,24 +88,4 @@ final class LifetimeStats {
let values = try? bundle.resourceValues(forKeys: [.addedToDirectoryDateKey, .creationDateKey])
return values?.addedToDirectoryDate ?? values?.creationDate ?? .now
}
-
- /// Adds a removal to the totals. Apps are counted by the bundles that moved, not by batch: five apps
- /// removed together count as five, and an app reset, which moves settings but no bundle, counts as none. An
- /// item missing from `sizes` was not measured.
- func add(_ result: TrashResult, sizes: [URL: Int64]) {
- guard !result.trashed.isEmpty else { return }
- let freed = SizeTotal(result.trashed.map { sizes[$0.originalURL] })
- bytesFreed = SizeTotal(known: bytesFreed.known.addingCapped(freed.known), isComplete: bytesFreed.isComplete && freed.isComplete)
- itemsRemoved = itemsRemoved.addingCapped(result.trashed.count)
- // A helper app kept under a Library folder is a leftover, not an app the user removed.
- appsRemoved = appsRemoved.addingCapped(result.trashed.count { $0.originalURL.pathExtension.lowercased() == "app" && !$0.originalURL.pathComponents.contains("Library") })
- if freed.known > biggestCleanUp.known { biggestCleanUp = freed }
-
- defaults.set(Int(bytesFreed.known), forKey: Key.bytes)
- defaults.set(!bytesFreed.isComplete, forKey: Key.bytesIncomplete)
- defaults.set(itemsRemoved, forKey: Key.items)
- defaults.set(appsRemoved, forKey: Key.apps)
- defaults.set(Int(biggestCleanUp.known), forKey: Key.biggest)
- defaults.set(!biggestCleanUp.isComplete, forKey: Key.biggestIncomplete)
- }
}
diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swift
index 2e53b5c6..1480795b 100644
--- a/Peel/Model/RemovalHistoryStore.swift
+++ b/Peel/Model/RemovalHistoryStore.swift
@@ -93,7 +93,7 @@ struct RefusalBatch: Identifiable, Hashable {
final class RemovalHistoryStore {
private let log = RemovalLog()
private let refusals = RefusalLog()
- /// Updated here rather than by each tool, so no place that records a removal can forget to count it.
+ /// Read again here once History has counted a removal, rather than by each tool.
var stats: LifetimeStats?
/// The last batch moved, for Undo. `@Environment(\.undoManager)` is nil in an app with no documents,
/// so the Edit menu's own item is replaced by one that asks this (`PeelCommands`).
@@ -174,20 +174,17 @@ final class RemovalHistoryStore {
/// Records a removal from one place in History, as one entry. When Peel wrote the source itself, pass it in
/// English along with a `sourceKey`, so History can show it in the user's language (see
- /// `RemovalRecord.sourceKey`). An item missing from `sizes` is recorded as unknown. Remove Peel leaves out the
- /// lifetime totals: they live in Peel's settings, which it has just cleared, and writing them would make those
- /// settings again.
+ /// `RemovalRecord.sourceKey`). An item missing from `sizes` is recorded as unknown.
func record(
_ result: TrashResult,
tool: Tool,
source: String,
sourceKey: String? = nil,
- sizes: [URL: Int64],
- countsTowardTotals: Bool = true
+ sizes: [URL: Int64]
) async {
var removal = RemovalInProgress()
await record(result, part: RemovalPart(source: source, sourceKey: sourceKey, tool: tool.rawValue), sizes: sizes, in: &removal)
- finish(removal, countsTowardTotals: countsTowardTotals)
+ finish(removal)
}
/// Records in History what one part of `removal` moved, and what it refused.
@@ -214,7 +211,7 @@ final class RemovalHistoryStore {
/// Tells what `removal` moved once every part of it is recorded: the bar's "Moved", VoiceOver, the lifetime
/// totals, and Undo.
- func finish(_ removal: RemovalInProgress, countsTowardTotals: Bool = true) {
+ func finish(_ removal: RemovalInProgress) {
guard !removal.records.isEmpty else { return }
let moved = RemovalBatch(
id: removal.batch,
@@ -224,12 +221,7 @@ final class RemovalHistoryStore {
)
justMoved = moved
AccessibilityNotification.Announcement(moved.movedAnnouncement).post()
- if countsTowardTotals {
- stats?.add(
- TrashResult(trashed: removal.records.map(\.trashedItem)),
- sizes: [URL: Int64](measured: removal.records.map { ($0.originalURL, $0.size) })
- )
- }
+ stats?.reload()
registerUndo(of: removal.records, source: moved.title)
}
diff --git a/Peel/PeelApp.swift b/Peel/PeelApp.swift
index f5c00763..78e6c54f 100644
--- a/Peel/PeelApp.swift
+++ b/Peel/PeelApp.swift
@@ -160,8 +160,9 @@ struct PeelApp: App {
helper.refresh()
// `peel exclusions` may have changed the list while another app was in front.
Task { await exclusions.load() }
- // History may have become readable again meanwhile, or stopped being.
+ // History may have become readable again meanwhile, or stopped being, and `peel` may have moved something.
history.checkReadability()
+ stats.reload()
// Home's checks run again whatever page is showing: permissions change in System Settings, and the
// badge on Home in the sidebar shows a missing one.
Task { await home.refresh(helper: helper) }
@@ -320,6 +321,7 @@ struct PeelApp: App {
hasLaunched = true
history.stats = stats
history.checkReadability()
+ Task { await stats.takeInEarlierTotals() }
// Read beside the rest and behind nothing: until the exclusions are read, nothing moves.
async let exclusionsRead: Void = Marks.interval("Exclusions") { await exclusions.load() }
// The apps and Homebrew don't depend on Home's checks, so they load in parallel with them.
diff --git a/Peel/Views/Settings/SettingsView.swift b/Peel/Views/Settings/SettingsView.swift
index 7ab4b65a..376ead6d 100644
--- a/Peel/Views/Settings/SettingsView.swift
+++ b/Peel/Views/Settings/SettingsView.swift
@@ -349,7 +349,7 @@ private struct GeneralSettingsView: View {
Button("Remove Peel", role: .destructive) {
Task {
await selfUninstall.run(installedApps: library.apps, helper: helper, pausing: background) { result in
- await history.record(result, tool: .applications, source: "Peel", sizes: [:], countsTowardTotals: false)
+ await history.record(result, tool: .applications, source: "Peel", sizes: [:])
}
}
}