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.

Tell what an Undo left behind, and keep Undo true to History

Țugui Dragoș114b96a74328
diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swift
index d0473c11..4a14e701 100644
--- a/Peel/Model/RemovalHistoryStore.swift
+++ b/Peel/Model/RemovalHistoryStore.swift
@@ -115,8 +115,11 @@ nonisolated struct RefusalBatch: Identifiable, Hashable {
final class RemovalHistoryStore {
private let log: RemovalLog
private let refusals: RefusalLog
- /// Where a removal History couldn't record is told, with whatever else the removal left to tell.
+ /// Where a removal History couldn't record is told, with whatever else the removal left to tell, and what an
+ /// Undo left in the Trash.
private let outcome: RemovalOutcome?
+ private let knowsTheExclusions: () -> Bool
+ private let restoring: ([TrashedItem], Bool) async -> [RestoreFailure?]
/// 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,
@@ -168,10 +171,22 @@ final class RemovalHistoryStore {
refusalBatches.first { $0.id == selection }
}
- init(log: RemovalLog = RemovalLog(), refusals: RefusalLog = RefusalLog(), outcome: RemovalOutcome? = nil) {
+ /// `restoring` puts items back, for each the reason it stayed or nil, and `knowsTheExclusions` says whether
+ /// anything may move: both are the app's own unless a test stands in for them.
+ init(
+ log: RemovalLog = RemovalLog(),
+ refusals: RefusalLog = RefusalLog(),
+ outcome: RemovalOutcome? = nil,
+ knowsTheExclusions: @escaping () -> Bool = { ExclusionsStore.shared.exclusions.isKnown },
+ restoring: @escaping ([TrashedItem], Bool) async -> [RestoreFailure?] = { items, canUseHelper in
+ await TrashService(exclusions: ExclusionsStore.shared.exclusions).restore(items, canUseHelper: canUseHelper)
+ }
+ ) {
self.log = log
self.refusals = refusals
self.outcome = outcome
+ self.knowsTheExclusions = knowsTheExclusions
+ self.restoring = restoring
}
func load() async {
@@ -296,7 +311,7 @@ final class RemovalHistoryStore {
/// Why nothing may move to the Trash or back now: the exclusions are not known, or History can't be read or
/// written.
var holdingReason: TrashFailure.Reason? {
- guard ExclusionsStore.shared.exclusions.isKnown else { return .guarded(.exclusionsNotKnown) }
+ guard knowsTheExclusions() else { return .guarded(.exclusionsNotKnown) }
if isUnreadable { return .historyUnreadable }
return cannotBeWritten ? .historyCannotBeWritten : nil
}
@@ -308,7 +323,22 @@ final class RemovalHistoryStore {
func undoLastRemoval() async {
guard let undoable, !isRestoring, mayMove else { return }
self.undoable = nil
- await restore(undoable.records, canUseHelper: canUseHelper)
+ let stayed = await restore(undoable.records, canUseHelper: canUseHelper, tellingThePage: false)
+ guard !stayed.isEmpty else { return }
+ outcome?.reportPutBack(stayed.map {
+ RemovalOutcome.PutBackFailure(url: $0.record.originalURL, failure: $0.failure)
+ })
+ // What stayed for a reason that can pass, such as the helper or something in its place, can be asked again.
+ let again = stayed.filter { $0.failure != .missingFromTrash && $0.failure != .notAllowed }.map(\.record)
+ if !again.isEmpty { self.undoable = (again, undoable.title) }
+ }
+
+ /// Takes the records `ids` names out of what Undo would put back, once they are back or gone from History.
+ private func keepUndoable(without ids: Set<RemovalRecord.ID>) {
+ guard let undoable, !ids.isEmpty else { return }
+ let left = undoable.records.filter { !ids.contains($0.id) }
+ guard left.count != undoable.records.count else { return }
+ self.undoable = left.isEmpty ? nil : (left, undoable.title)
}
/// Shows the log's records, or keeps what is already on screen when the log was left untouched or holds the
@@ -317,6 +347,8 @@ final class RemovalHistoryStore {
problem = outcome.problem
checkReadability()
guard let records = outcome.records else { return }
+ // What left History since it was listed, as by `peel restore`, is no longer Undo's to put back.
+ keepUndoable(without: Set(self.records.map(\.id)).subtracting(records.map(\.id)))
listedChange += 1
let change = listedChange
guard let listed = await Self.listed(records, unless: self.records), change == listedChange else { return }
@@ -354,39 +386,48 @@ final class RemovalHistoryStore {
return (batches, searchKeys)
}
- func restore(_ records: [RemovalRecord], canUseHelper: Bool) async {
+ /// Puts `records` back and answers what stayed, each with why. History's page shows the reasons
+ /// (`tellingThePage`); an Undo, asked from any page, has them told by the app instead.
+ @discardableResult
+ func restore(
+ _ records: [RemovalRecord], canUseHelper: Bool, tellingThePage: Bool = true
+ ) async -> [(record: RemovalRecord, failure: RestoreFailure)] {
// One restore at a time, however often it is asked for: two rounds over the same records would each
// report the items the other put back as already there.
- guard !isRestoring, mayMove else { return }
+ guard !isRestoring, mayMove else { return [] }
isRestoring = true
defer { isRestoring = false }
- let service = TrashService(exclusions: ExclusionsStore.shared.exclusions)
- await QuitGuard.shared.run {
+ return await QuitGuard.shared.run {
var restored: Set<UUID> = []
var problems: [RemovalRecord.ID: RestoreFailure] = [:]
+ var stayed: [(record: RemovalRecord, failure: RestoreFailure)] = []
let ordered = records.inPutBackOrder
- let answers = await service.restore(ordered.map(\.trashedItem), canUseHelper: canUseHelper)
+ let answers = await restoring(ordered.map(\.trashedItem), canUseHelper)
for (record, answer) in zip(ordered, answers) {
if let failure = answer {
problems[record.id] = failure
+ stayed.append((record, failure))
} else {
restored.insert(record.id)
}
}
- failures = problems
+ if tellingThePage { failures = problems }
selectedIDs.subtract(restored)
if !restored.isEmpty {
+ keepUndoable(without: restored)
await apply(await log.remove(restored))
// A move is announced, and so is its undoing: the rows only vanish from the list.
AccessibilityNotification.Announcement(
AttributedString(localized: "Put back ^[\(restored.count) item](inflect: true).")
).post()
}
+ return stayed
}
}
/// Removes `records` from History. The page offers this for items that have left the Trash.
func forget(_ records: [RemovalRecord]) async {
+ keepUndoable(without: Set(records.map(\.id)))
await apply(await log.remove(Set(records.map(\.id))))
selectedIDs.subtract(records.map(\.id))
}
diff --git a/Peel/Model/RemovalOutcome.swift b/Peel/Model/RemovalOutcome.swift
index 1cf73262..ec68a9d3 100644
--- a/Peel/Model/RemovalOutcome.swift
+++ b/Peel/Model/RemovalOutcome.swift
@@ -12,6 +12,11 @@ final class RemovalOutcome {
let result: PrivacyReset.Result
}
+ struct PutBackFailure: Hashable {
+ let url: URL
+ let failure: RestoreFailure
+ }
+
private(set) var failures: [TrashFailure] = []
/// The privacy resets the removal ran that are worth telling the user about.
private(set) var privacy: [Privacy] = []
@@ -29,18 +34,24 @@ final class RemovalOutcome {
private(set) var shellReferences: [ShellReferences.Reference] = []
/// True when History couldn't record the removal, so Put Back has nothing to go on for what moved.
private(set) var historyCouldNotRecord = false
+ /// What an Undo left in the Trash: Undo is asked from any page, so what came of it is told here.
+ private(set) var putBackFailures: [PutBackFailure] = []
private(set) var movedCount = 0
var isEmpty: Bool {
failures.isEmpty && privacy.isEmpty && appsToQuit.isEmpty && driversAwaitingARestart.isEmpty
&& appsStartingFromTheTrash.isEmpty && leftForAnAdministrator == 0 && shellReferences.isEmpty
- && !historyCouldNotRecord
+ && !historyCouldNotRecord && putBackFailures.isEmpty
}
func noteHistoryCouldNotRecord() {
historyCouldNotRecord = true
}
+ func reportPutBack(_ failures: [PutBackFailure]) {
+ putBackFailures = failures
+ }
+
/// Keeps what the removal could not do, what a restart or an emptied Trash finishes, and what stays for an
/// administrator, for the alert. `privacy` is every reset the removal ran, and `PrivacyReset.worthTelling` picks
/// which of them to tell. A removal with nothing to tell changes nothing.
@@ -85,5 +96,6 @@ final class RemovalOutcome {
leftForAnAdministrator = 0
shellReferences = []
historyCouldNotRecord = false
+ putBackFailures = []
}
}
diff --git a/Peel/Views/RemovalFailureAlert.swift b/Peel/Views/RemovalFailureAlert.swift
index f9c3f596..2f5fdb2b 100644
--- a/Peel/Views/RemovalFailureAlert.swift
+++ b/Peel/Views/RemovalFailureAlert.swift
@@ -77,6 +77,9 @@ struct RemovalFailureAlert: ViewModifier {
if outcome.historyCouldNotRecord {
return Text("History couldn’t record this removal.")
}
+ if !outcome.putBackFailures.isEmpty, outcome.failures.isEmpty {
+ return Text("Some items couldn’t be put back.")
+ }
if #available(macOS 27, *), !outcome.appsStartingFromTheTrash.isEmpty, outcome.failures.isEmpty,
outcome.appsToQuit.isEmpty, outcome.privacy.isEmpty {
return outcome.driversAwaitingARestart.isEmpty
@@ -102,7 +105,9 @@ struct RemovalFailureAlert: ViewModifier {
}
static func message(for outcome: RemovalOutcome) -> String {
- var lines = historyLines(outcome) + shortened(quitLines(outcome))
+ var lines = historyLines(outcome)
+ + firstItems(outcome.putBackFailures.map { "\($0.url.abbreviatedPath)\n\($0.failure.explanation)" })
+ + shortened(quitLines(outcome))
+ firstItems(outcome.failures.map { "\($0.url.abbreviatedPath)\n\($0.reason.explanation)" })
lines += shortened(keptLines(outcome)) + driverLines(outcome) + administratorLines(outcome)
+ shellLines(outcome) { Self.listed($0) { String(inflecting: "^[\($0) more line](inflect: true)") } }
@@ -164,7 +169,7 @@ struct RemovalFailureAlert: ViewModifier {
/// Offered for a failure, whose full path the alert shortens, and wherever the alert names only the first entries
/// of a list, so every name it leaves out can still be read.
static func offersDetails(for outcome: RemovalOutcome) -> Bool {
- !outcome.failures.isEmpty || message(for: outcome) != details(for: outcome)
+ !outcome.failures.isEmpty || !outcome.putBackFailures.isEmpty || message(for: outcome) != details(for: outcome)
}
/// Copies every item with its full path, since the alert lists only the first few and its text can't be
@@ -175,7 +180,9 @@ struct RemovalFailureAlert: ViewModifier {
}
static func details(for outcome: RemovalOutcome) -> String {
- var lines = historyLines(outcome) + quitLines(outcome)
+ var lines = historyLines(outcome)
+ + outcome.putBackFailures.map { "\($0.url.path(percentEncoded: false))\n\($0.failure.explanation)" }
+ + quitLines(outcome)
+ outcome.failures.map { "\($0.url.path(percentEncoded: false))\n\($0.reason.explanation)" }
+ keptLines(outcome) + driverLines(outcome) + administratorLines(outcome)
+ shellLines(outcome) { $0.formatted(.list(type: .and)) } + appManagementLines(outcome)
@@ -215,6 +222,7 @@ struct RemovalFailureAlert: ViewModifier {
private static func needsHelper(_ outcome: RemovalOutcome) -> Bool {
outcome.failures.contains { $0.reason == .needsHelper }
+ || outcome.putBackFailures.contains { $0.failure == .needsHelper }
}
}
diff --git a/PeelTests/RemovalOutcomeTests.swift b/PeelTests/RemovalOutcomeTests.swift
index fc211e58..e65978eb 100644
--- a/PeelTests/RemovalOutcomeTests.swift
+++ b/PeelTests/RemovalOutcomeTests.swift
@@ -46,4 +46,47 @@ struct RemovalOutcomeTests {
#expect(RemovalFailureAlert.message(for: outcome).hasPrefix("What moved is in the Trash"))
#expect(RemovalFailureAlert.details(for: outcome).hasPrefix("What moved is in the Trash"))
}
+
+ private func history(in folder: URL, outcome: RemovalOutcome, staying: String? = nil) -> RemovalHistoryStore {
+ RemovalHistoryStore(
+ log: RemovalLog(url: folder.appending(path: "removals.json")),
+ refusals: RefusalLog(url: folder.appending(path: "refusals.json")),
+ outcome: outcome,
+ knowsTheExclusions: { true },
+ restoring: { items, _ in items.map { $0.originalURL.lastPathComponent == staying ? .needsHelper : nil } }
+ )
+ }
+
+ private func moved(_ names: [String]) throws -> TrashResult {
+ try TrashResult(trashed: names.map { name in
+ let item = #"{"originalURL": "file:///Users/me/\#(name)", "trashedURL": "file:///Users/me/.Trash/\#(name)", "date": 0}"#
+ return try JSONDecoder().decode(TrashedItem.self, from: Data(item.utf8))
+ })
+ }
+
+ @Test func anUndoThatLeavesAnItemSaysWhyWhereverThePersonIs() async throws {
+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: folder) }
+ let outcome = RemovalOutcome()
+ let history = history(in: folder, outcome: outcome, staying: "Driver")
+ await history.record(try moved(["Cache", "Driver"]), tool: .plugins, source: "Plug-ins", sizes: [:])
+
+ await history.undoLastRemoval()
+
+ #expect(outcome.putBackFailures.map(\.url.lastPathComponent) == ["Driver"])
+ #expect(outcome.putBackFailures.first?.failure == .needsHelper)
+ #expect(history.undoTitle != nil, "what stayed can be put back once the helper can")
+ }
+
+ @Test func undoGoesOnceItsRemovalIsPutBackFromHistory() async throws {
+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: folder) }
+ let history = history(in: folder, outcome: RemovalOutcome())
+ await history.record(try moved(["Cache"]), tool: .plugins, source: "Plug-ins", sizes: [:])
+ #expect(history.undoTitle != nil)
+
+ await history.restore(history.records, canUseHelper: false)
+
+ #expect(history.undoTitle == nil)
+ }
}