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.

peel history --refused lists refusals one removal at a time

Țugui Dragoș805fc5d3bbc6
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
index e96e4800..3523abb7 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
@@ -103,9 +103,55 @@ struct HistoryCommand: AsyncParsableCommand {
}
}
+ /// One removal's refusals, as `--refused --json` writes them.
+ private struct RefusedRemoval: Encodable {
+ struct Item: Encodable {
+ let path: String
+ let reason: String
+ let detail: String?
+ let why: String
+
+ private enum CodingKeys: String, CodingKey {
+ case path, reason, detail, why
+ }
+
+ /// Written by hand so a refusal with no detail says `"detail": null` rather than leaving the key out.
+ func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(path, forKey: .path)
+ try container.encode(reason, forKey: .reason)
+ try container.encode(detail, forKey: .detail)
+ try container.encode(why, forKey: .why)
+ }
+ }
+
+ let batch: String
+ let date: Date
+ let source: String
+ let tool: String?
+ let items: [Item]
+
+ private enum CodingKeys: String, CodingKey {
+ case batch, date, source, tool, items
+ }
+
+ /// Written by hand so a removal from several tools says `"tool": null` rather than leaving the key out.
+ func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(batch, forKey: .batch)
+ try container.encode(date, forKey: .date)
+ try container.encode(source, forKey: .source)
+ try container.encode(tool, forKey: .tool)
+ try container.encode(items, forKey: .items)
+ }
+ }
+
func validate() throws {
guard limit > 0 else { throw ValidationError("--limit has to be at least 1.") }
guard !clear || refused else { throw ValidationError("--clear only goes with --refused. What moved is forgotten from History in the Peel app.") }
+ guard !clear || !output.json else {
+ throw ValidationError("--clear writes nothing to read, so it doesn't go with --json.")
+ }
}
func run() async throws {
@@ -159,24 +205,42 @@ struct HistoryCommand: AsyncParsableCommand {
static func rows(for records: [RefusalRecord]) -> [[String]] {
[["WHEN", "WHAT", "WHY", "PATH"]] + records.map { record in
- [Output.day(record.date), record.source, record.detail ?? record.reason, Output.path(record.url)]
+ [Output.day(record.date), record.source, why(record), Output.path(record.url)]
}
}
+ /// Why an item stayed, in the words the rest of `peel` uses. A reason a newer Peel wrote reads as recorded.
+ static func why(_ record: RefusalRecord) -> String {
+ TrashFailure.Reason(name: record.reason, detail: record.detail)?.summary ?? record.detail ?? record.reason
+ }
+
private func listRefusals(in log: RefusalLog) async throws {
guard !clear else {
guard await log.clear() else { throw CommandFailure("Peel couldn't forget its refusals.") }
Output.line("Forgot every refusal on record.")
return
}
- let records = Array(await log.load().sorted { $0.date > $1.date }.prefix(limit))
+ let removals = Array(RefusalRecord.grouped(await log.load()).prefix(limit))
if output.json {
- try Output.json(records)
- } else if records.isEmpty {
+ try Output.json(removals.map { removal in
+ RefusedRemoval(
+ batch: removal.id.uuidString,
+ date: removal.date,
+ source: Output.list(removal.parts.map(\.source)),
+ tool: removal.parts.count == 1 ? removal.parts[0].namedTool : nil,
+ items: removal.records.map { record in
+ RefusedRemoval.Item(
+ path: Output.path(record.url), reason: record.reason, detail: record.detail,
+ why: Self.why(record)
+ )
+ }
+ )
+ })
+ } else if removals.isEmpty {
Output.line("Peel hasn't refused anything it was asked to move.")
} else {
- Output.table(Self.rows(for: records))
+ Output.table(Self.rows(for: removals.flatMap(\.records)))
}
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
index a7f14dac..bbe3eed8 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
@@ -47,8 +47,10 @@ public actor RefusalLog {
/// Writes down what one removal refused. The parts of one pass through several tools share its `batch`, so
/// History shows them as one entry.
- public func add(_ failures: [TrashFailure], source: String, sourceKey: String? = nil, tool: String, batch: UUID = UUID()) {
- let date = Date.now
+ public func add(
+ _ failures: [TrashFailure], source: String, sourceKey: String? = nil, tool: String, batch: UUID = UUID(),
+ date: Date = .now
+ ) {
let records = failures.map { RefusalRecord(failure: $0, date: date, source: source, sourceKey: sourceKey, tool: tool, batch: batch) }
guard !records.isEmpty else { return }
FileLock.whileHeld(beside: url) {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
index d7523733..7cc7ad75 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
@@ -77,7 +77,7 @@ struct HistoryCommandTests {
#expect(HistoryCommand.rows(for: Batch.all(in: [here, gone])).count == 2, "one removal is one row")
}
- /// The WHY column shows macOS's own message when macOS refused, and Peel's name for the rule when Peel did.
+ /// The WHY column shows macOS's own message when macOS refused, and Peel's words for the rule when Peel did.
@Test func writesEveryColumnOfARefusal() {
let when = Date(timeIntervalSince1970: 1_790_000_000)
let records = [
@@ -87,8 +87,9 @@ struct HistoryCommandTests {
let rows = HistoryCommand.rows(for: records)
#expect(rows[0] == ["WHEN", "WHAT", "WHY", "PATH"])
- #expect(rows[1] == [Inventory.day(when, timeZone: .current), "Editor", "protected-location", "/Users/me/Library/Mail"])
- #expect(rows[2] == [Inventory.day(when, timeZone: .current), "Editor", "no such file", "/Users/me/x.bin"])
+ let day = Inventory.day(when, timeZone: .current)
+ #expect(rows[1] == [day, "Editor", "protected location", "/Users/me/Library/Mail"])
+ #expect(rows[2] == [day, "Editor", "no such file", "/Users/me/x.bin"])
}
/// What `arguments` print, read the way a person or a script would read it.
@@ -240,6 +241,41 @@ struct HistoryCommandTests {
#expect(Dictionary(uniqueKeysWithValues: records.map { ($0.originalURL.lastPathComponent, $0.size) }) == ["a.txt": 5, "b": nil])
}
+ /// `--limit` counts removals, as the app lists refusals one removal to an entry, and `--json` writes each removal
+ /// with its items: a plain path, the reason's name and words, and every key present, `null` where nothing is known.
+ @Test func listsRefusalsOneRemovalAtATime() async throws {
+ let directory = try TemporaryDirectory()
+ let logs = logs(in: directory)
+ let old = TrashFailure(url: URL(filePath: "/Users/me/old.bin"), reason: .lastCopy)
+ await logs.refusals.add([old], source: "Old", tool: "duplicates", date: .now.addingTimeInterval(-60))
+ await logs.refusals.add(
+ [
+ TrashFailure(url: URL(filePath: "/Users/me/My Files/a.bin"), reason: .protectedLocation),
+ TrashFailure(url: URL(filePath: "/Users/me/b.bin"), reason: .failed("disk full")),
+ ],
+ source: "Editor", tool: "applications"
+ )
+
+ let text = try await printed(["history", "--refused", "--limit", "1"], from: logs)
+ #expect(text.contains("a.bin") && text.contains("b.bin") && !text.contains("old.bin"))
+
+ let removals = try listed(try await printed(["history", "--refused", "--limit", "1", "--json"], from: logs))
+ let removal = try #require(removals.first as? [String: Any])
+ #expect(removals.count == 1)
+ #expect(removal["source"] as? String == "Editor")
+ #expect(removal["tool"] as? String == "applications")
+ #expect(removal["batch"] is String)
+ let items = try #require(removal["items"] as? [[String: Any]])
+ #expect(items.map { $0["path"] as? String } == ["/Users/me/My Files/a.bin", "/Users/me/b.bin"])
+ #expect(items.map { $0["reason"] as? String } == ["protected-location", "failed"])
+ #expect(items.map { $0["why"] as? String } == ["protected location", "disk full"])
+ #expect(items[0]["detail"] is NSNull)
+ }
+
+ @Test func refusesToClearAndWriteJSONTogether() throws {
+ #expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["history", "--refused", "--clear", "--json"]) }
+ }
+
@Test func forgetsTheRefusalsWhenAsked() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)