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.

History names a removal by every part it moved from

Țugui Dragoșa9fdefe5a1b3
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
index 4dc137ac..063de972 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
@@ -8,8 +8,11 @@ struct Batch {
let records: [RemovalRecord]
var date: Date { records.map(\.date).max() ?? .distantPast }
- var source: String { records.first?.source ?? "" }
- var tool: String { records.first?.tool ?? "" }
+ /// Where the removal moved from: one part, or one for each tool whose selection it moved.
+ var parts: [RemovalPart] { RemovalPart.of(records.map { ($0.date, $0.part) }) }
+ var source: String { Output.list(parts.map(\.source)) }
+ /// The tool the removal moved from, or nil for one that moved from several.
+ var tool: String? { parts.count == 1 ? parts[0].tool : nil }
var size: SizeTotal { records.totalSize }
/// The records whose items are still in the Trash. An item emptied from the Trash can't be put back.
var restorable: [RemovalRecord] { records.filter(\.isStillInTrash) }
@@ -49,14 +52,38 @@ struct HistoryCommand: AsyncParsableCommand {
@OptionGroup var output: OutputOptions
private struct Record: Encodable {
+ struct Part: Encodable {
+ let source: String
+ let tool: String
+ }
+
let batch: String
let date: Date
let source: String
- let tool: String
+ let tool: String?
+ let parts: [Part]
let size: MeasuredSize
let itemCount: Int
let restorableCount: Int
let files: [FileRecord]
+
+ private enum CodingKeys: String, CodingKey {
+ case batch, date, source, tool, parts, size, itemCount, restorableCount, files
+ }
+
+ /// 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(parts, forKey: .parts)
+ try container.encode(size, forKey: .size)
+ try container.encode(itemCount, forKey: .itemCount)
+ try container.encode(restorableCount, forKey: .restorableCount)
+ try container.encode(files, forKey: .files)
+ }
}
func validate() throws {
@@ -83,6 +110,7 @@ struct HistoryCommand: AsyncParsableCommand {
date: batch.date,
source: batch.source,
tool: batch.tool,
+ parts: batch.parts.map { Record.Part(source: $0.source, tool: $0.tool) },
size: MeasuredSize(batch.size),
itemCount: batch.records.count,
restorableCount: batch.restorable.count,
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
index 81446fc3..f8e29d30 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
@@ -154,6 +154,16 @@ enum Output {
PathPattern.comparablePath(of: url)
}
+ /// Names joined as an English list: "A", "A and B", "A, B, and C".
+ static func list(_ names: [String]) -> String {
+ switch names.count {
+ case 0: ""
+ case 1: names[0]
+ case 2: "\(names[0]) and \(names[1])"
+ default: names.dropLast().joined(separator: ", ") + ", and " + names[names.count - 1]
+ }
+ }
+
static func number(_ value: Int) -> String {
value.formatted(.number.locale(locale))
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift
index 96ec0eb2..854a7e05 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift
@@ -5,9 +5,7 @@ public import Foundation
/// rule can be tested.
public struct RemovalGroup: Sendable, Hashable, Identifiable {
public let id: UUID
- public let source: String
- public let sourceKey: String?
- public let tool: String
+ public let parts: [RemovalPart]
/// When the batch was moved: the earliest of its records' dates, since each item is stamped as it moves.
public let date: Date
public let records: [RemovalRecord]
@@ -25,9 +23,7 @@ extension RemovalRecord {
}
return RemovalGroup(
id: batch,
- source: sorted.first?.source ?? "",
- sourceKey: sorted.first?.sourceKey,
- tool: sorted.first?.tool ?? "",
+ parts: RemovalPart.of(sorted.map { ($0.date, $0.part) }),
date: sorted.map(\.date).min() ?? .now,
records: sorted
)
@@ -39,9 +35,7 @@ extension RemovalRecord {
/// What Peel was asked to move in one removal and did not, as History shows it.
public struct RefusalGroup: Sendable, Hashable, Identifiable {
public let id: UUID
- public let source: String
- public let sourceKey: String?
- public let tool: String
+ public let parts: [RemovalPart]
public let date: Date
public let records: [RefusalRecord]
}
@@ -54,9 +48,7 @@ extension RefusalRecord {
let sorted = records.sorted { $0.url.path(percentEncoded: false) < $1.url.path(percentEncoded: false) }
return RefusalGroup(
id: batch,
- source: sorted.first?.source ?? "",
- sourceKey: sorted.first?.sourceKey,
- tool: sorted.first?.tool ?? "",
+ parts: RemovalPart.of(sorted.map { ($0.date, $0.part) }),
date: sorted.map(\.date).min() ?? .now,
records: sorted
)
@@ -64,3 +56,39 @@ extension RefusalRecord {
.sorted { $0.date != $1.date ? $0.date > $1.date : $0.id.uuidString < $1.id.uuidString }
}
}
+
+/// Where some of a removal's records came from: the tool, and the source it names, such as an app or a group of
+/// orphaned files. A removal from one page has one part, and one that moved what was selected in several tools
+/// has one for each, in the order they moved.
+public struct RemovalPart: Sendable, Hashable {
+ public let source: String
+ /// The key of a source Peel names itself, so History can show it in the user's language.
+ public let sourceKey: String?
+ public let tool: String
+
+ public init(source: String, sourceKey: String?, tool: String) {
+ self.source = source
+ self.sourceKey = sourceKey
+ self.tool = tool
+ }
+
+ /// The parts of one removal, each once, in the order its first record moved. Two parts that moved at the same
+ /// moment keep one order, by tool and then by source.
+ public static func of(_ records: some Sequence<(date: Date, part: RemovalPart)>) -> [RemovalPart] {
+ var first: [RemovalPart: Date] = [:]
+ for (date, part) in records {
+ first[part] = min(first[part] ?? date, date)
+ }
+ return first
+ .sorted { $0.value != $1.value ? $0.value < $1.value : ($0.key.tool, $0.key.source) < ($1.key.tool, $1.key.source) }
+ .map(\.key)
+ }
+}
+
+extension RemovalRecord {
+ public var part: RemovalPart { RemovalPart(source: source, sourceKey: sourceKey, tool: tool) }
+}
+
+extension RefusalRecord {
+ public var part: RemovalPart { RemovalPart(source: source, sourceKey: sourceKey, tool: tool) }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
index 12b85152..c5fb34fc 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
@@ -104,6 +104,39 @@ struct HistoryCommandTests {
try #require(try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [Any])
}
+ /// A removal of what was selected in several tools is named by each of their sources, in the order they
+ /// moved, in the table and in `--json`, where it names no one tool and lists each part.
+ @Test func namesEveryPartOfARemovalFromSeveralTools() async throws {
+ let directory = try TemporaryDirectory()
+ let logs = logs(in: directory)
+ let batch = UUID()
+ let now = Date.now
+ let parts = [("Xcode", "developer", "DerivedData"), ("Peel", "projects", "node_modules"), ("Duplicates", "duplicates", "copy.bin")]
+ let records = parts.enumerated().map { index, part in
+ RemovalRecord(
+ batch: batch,
+ item: TrashedItem(
+ originalURL: directory.url.appending(path: "home/\(part.2)"),
+ trashedURL: directory.url.appending(path: "home/.Trash/\(part.2)"),
+ date: now.addingTimeInterval(Double(index))
+ ),
+ size: 10,
+ source: part.0,
+ tool: part.1
+ )
+ }
+ _ = await logs.removals.add(records)
+
+ #expect(HistoryCommand.rows(for: Batch.all(in: records))[1][2] == "Xcode, Peel, and Duplicates")
+ #expect(HistoryCommand.rows(for: Batch.all(in: Array(records.prefix(2))))[1][2] == "Xcode and Peel")
+
+ let removal = try #require(try listed(try await printed(["history", "--json"], from: logs)).first as? [String: Any])
+ #expect(removal["tool"] is NSNull)
+ let listedParts = try #require(removal["parts"] as? [[String: Any]])
+ #expect(listedParts.compactMap { $0["source"] as? String } == ["Xcode", "Peel", "Duplicates"])
+ #expect(listedParts.compactMap { $0["tool"] as? String } == ["developer", "projects", "duplicates"])
+ }
+
/// With nothing recorded, the command prints a sentence rather than an empty table, and `--json` prints an
/// empty list.
@Test func saysSoWhenThereIsNothingToList() async throws {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
index 1be38269..0ac289eb 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
@@ -144,6 +144,25 @@ struct RefusalLogTests {
#expect(records.first { $0.source == "Editor" }?.sourceKey == nil)
}
+ /// What one removal of several tools' selections refused is one entry with a part for each tool, in the order
+ /// they were refused.
+ @Test func aRemovalFromSeveralToolsHasARefusalPartForEach() throws {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ let batch = UUID()
+ let stored = """
+ [{"id":"\(UUID())","batch":"\(batch)","url":"file:///Users/me/b","reason":"last-copy","date":"2026-09-20T10:00:02Z","source":"Duplicates","sourceKey":"tool","tool":"duplicates"},
+ {"id":"\(UUID())","batch":"\(batch)","url":"file:///Users/me/a","reason":"not-permitted","date":"2026-09-20T10:00:00Z","source":"Xcode","tool":"developer"}]
+ """
+ let groups = RefusalRecord.grouped(try decoder.decode([RefusalRecord].self, from: Data(stored.utf8)))
+
+ #expect(groups.count == 1)
+ #expect(groups.first?.parts == [
+ RemovalPart(source: "Xcode", sourceKey: nil, tool: "developer"),
+ RemovalPart(source: "Duplicates", sourceKey: "tool", tool: "duplicates"),
+ ])
+ }
+
/// History lists what was refused one removal to an entry, newest first. A record kept without a batch is an
/// entry of its own.
@Test func historyShowsEachRemovalsRefusalsAsOneEntry() throws {
@@ -157,12 +176,12 @@ struct RefusalLogTests {
"""
let groups = RefusalRecord.grouped(try decoder.decode([RefusalRecord].self, from: Data(stored.utf8)))
- #expect(groups.map(\.source) == ["Duplicates", "Editor"])
+ #expect(groups.map { $0.parts.map(\.source) } == [["Duplicates"], ["Editor"]])
#expect(groups.first?.id == batch)
- #expect(groups.first?.sourceKey == "tool")
+ #expect(groups.first?.parts.first?.sourceKey == "tool")
#expect(groups.first?.records.map(\.url.lastPathComponent) == ["a", "b"])
#expect(groups.first?.date == ISO8601DateFormatter().date(from: "2026-09-20T10:00:00Z"))
#expect(groups.last?.records.count == 1)
- #expect(groups.last?.sourceKey == nil)
+ #expect(groups.last?.parts == [RemovalPart(source: "Editor", sourceKey: nil, tool: "applications")])
}
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalGroupingTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalGroupingTests.swift
index ccee0a7d..d42c0b0e 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalGroupingTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalGroupingTests.swift
@@ -25,7 +25,7 @@ struct RemovalGroupingTests {
let keyed = RemovalRecord(batch: UUID(), item: item, size: 1, source: "Duplicates", sourceKey: "tool", tool: "duplicates")
let copy = try JSONDecoder().decode(RemovalRecord.self, from: JSONEncoder().encode(keyed))
#expect(copy.sourceKey == "tool")
- #expect(RemovalRecord.grouped([copy]).first?.sourceKey == "tool")
+ #expect(RemovalRecord.grouped([copy]).first?.parts.first?.sourceKey == "tool")
var old = try JSONSerialization.jsonObject(with: JSONEncoder().encode(keyed)) as! [String: Any]
old.removeValue(forKey: "sourceKey")
@@ -51,8 +51,27 @@ struct RemovalGroupingTests {
// The batch's own time is the first record written, not the last.
#expect(groups.last?.date == now.addingTimeInterval(-60))
#expect(groups.last?.size == SizeTotal(known: 110, isComplete: true))
- #expect(groups.first?.source == "Caches")
- #expect(groups.first?.tool == "space")
+ #expect(groups.first?.parts == [RemovalPart(source: "Caches", sourceKey: nil, tool: "space")])
+ }
+
+ /// A removal that moved what was selected in several tools has a part for each, in the order they moved, so
+ /// History names it by all of them rather than by its largest item. A removal from one page has one part.
+ @Test func aRemovalFromSeveralToolsHasAPartForEach() {
+ let now = Date(timeIntervalSince1970: 1_800_000_000)
+ let batch = UUID()
+ let groups = RemovalRecord.grouped([
+ record(batch, "copy.bin", size: 2_000, at: now.addingTimeInterval(2), source: "Duplicates", tool: "duplicates"),
+ record(batch, "DerivedData", size: 900, at: now, source: "Xcode", tool: "developer"),
+ record(batch, "node_modules", size: 300, at: now.addingTimeInterval(1), source: "Peel", tool: "projects"),
+ record(batch, "ModuleCache", size: 50, at: now.addingTimeInterval(0.5), source: "Xcode", tool: "developer"),
+ ])
+
+ #expect(groups.count == 1)
+ #expect(groups.first?.parts.map(\.source) == ["Xcode", "Peel", "Duplicates"])
+ #expect(groups.first?.parts.map(\.tool) == ["developer", "projects", "duplicates"])
+
+ let single = RemovalRecord.grouped([record(UUID(), "one.bin", size: 5, at: now, source: "Caches", tool: "space")])
+ #expect(single.first?.parts == [RemovalPart(source: "Caches", sourceKey: nil, tool: "space")])
}
/// An item whose size is not known comes first, since what could not be measured is most likely the biggest,
diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swift
index 262f5c6c..d0f86a23 100644
--- a/Peel/Model/RemovalHistoryStore.swift
+++ b/Peel/Model/RemovalHistoryStore.swift
@@ -5,23 +5,36 @@ import PeelCore
struct RemovalBatch: Identifiable, Hashable {
let id: UUID
- let source: String
- let sourceKey: String?
- let tool: Tool?
+ /// Every tool the batch moved from, in the order they moved: one, or several for a batch that moved what was
+ /// selected in more than one tool.
+ let tools: [Tool]
let date: Date
let records: [RemovalRecord]
- /// The title the row shows. A source Peel stored with a key is shown in the user's language, any other
- /// source as stored.
+ /// The title the row shows: each part's source, in the order they moved. A source Peel stored with a key is
+ /// shown in the user's language, any other source as stored.
let title: String
- init(id: UUID, source: String, sourceKey: String?, tool: Tool?, date: Date, records: [RemovalRecord]) {
+ init(id: UUID, parts: [RemovalPart], date: Date, records: [RemovalRecord]) {
self.id = id
- self.source = source
- self.sourceKey = sourceKey
- self.tool = tool
+ tools = Self.tools(of: parts)
self.date = date
self.records = records
- title = Self.title(source: source, key: sourceKey, tool: tool)
+ title = Self.title(of: parts)
+ }
+
+ /// The one tool the batch moved from, or nil for a batch from several.
+ var tool: Tool? { tools.count == 1 ? tools[0] : nil }
+
+ static func tools(of parts: [RemovalPart]) -> [Tool] {
+ var tools: [Tool] = []
+ for tool in parts.compactMap({ Tool(rawValue: $0.tool) }) where !tools.contains(tool) {
+ tools.append(tool)
+ }
+ return tools
+ }
+
+ static func title(of parts: [RemovalPart]) -> String {
+ parts.map { title(source: $0.source, key: $0.sourceKey, tool: Tool(rawValue: $0.tool)) }.formatted(.list(type: .and))
}
static func title(source: String, key: String?, tool: Tool?) -> String {
@@ -51,18 +64,16 @@ struct RemovalBatch: Identifiable, Hashable {
/// What Peel was asked to move in one removal and did not.
struct RefusalBatch: Identifiable, Hashable {
let id: UUID
- let tool: Tool?
let date: Date
let records: [RefusalRecord]
- /// The source in the user's language, as `RemovalBatch.title` gives it.
+ /// The sources in the user's language, as `RemovalBatch.title(of:)` gives them.
let title: String
init(_ group: RefusalGroup) {
id = group.id
- tool = Tool(rawValue: group.tool)
date = group.date
records = group.records
- title = RemovalBatch.title(source: group.source, key: group.sourceKey, tool: tool)
+ title = RemovalBatch.title(of: group.parts)
}
}
@@ -101,14 +112,7 @@ final class RemovalHistoryStore {
/// Groups `records` into batches. The rule lives in `RemovalRecord.grouped`, where it is tested.
private static func batches(of records: [RemovalRecord]) -> [RemovalBatch] {
RemovalRecord.grouped(records).map { group in
- RemovalBatch(
- id: group.id,
- source: group.source,
- sourceKey: group.sourceKey,
- tool: Tool(rawValue: group.tool),
- date: group.date,
- records: group.records
- )
+ RemovalBatch(id: group.id, parts: group.parts, date: group.date, records: group.records)
}
}
@@ -147,7 +151,12 @@ final class RemovalHistoryStore {
let new = result.trashed.map {
RemovalRecord(batch: batch, item: $0, size: sizes[$0.originalURL], source: source, sourceKey: sourceKey, tool: tool.rawValue)
}
- let moved = RemovalBatch(id: batch, source: source, sourceKey: sourceKey, tool: tool, date: .now, records: new)
+ let moved = RemovalBatch(
+ id: batch,
+ parts: [RemovalPart(source: source, sourceKey: sourceKey, tool: tool.rawValue)],
+ date: .now,
+ records: new
+ )
justMoved = moved
AccessibilityNotification.Announcement(moved.movedAnnouncement).post()
// History first: it is the way back for what just moved, and nothing that follows may keep it unwritten.
diff --git a/Peel/Views/History/HistoryDetailView.swift b/Peel/Views/History/HistoryDetailView.swift
index 6ae5f961..77554f60 100644
--- a/Peel/Views/History/HistoryDetailView.swift
+++ b/Peel/Views/History/HistoryDetailView.swift
@@ -157,7 +157,7 @@ struct HistoryDetailView: View {
.font(.callout)
.foregroundStyle(.secondary)
FlowLayout {
- if let tool = batch.tool {
+ ForEach(batch.tools, id: \.self) { tool in
Badge(title: Text(tool.title), systemImage: tool.systemImage)
}
Badge(title: Text("^[\(batch.records.count) item](inflect: true)"), systemImage: "doc.on.doc")