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 rules for carrying a selection from one tool's page to another

Țugui Dragoș8e6713f48ad4
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/CarriedSelection.swift b/Packages/PeelCore/Sources/PeelCore/Removal/CarriedSelection.swift
new file mode 100644
index 00000000..4c9c8ff6
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/CarriedSelection.swift
@@ -0,0 +1,109 @@
+public import Foundation
+
+/// What is selected on the pages of the storage tools, and what of it moves when Move to Trash is pressed on any
+/// of them: each page the person has seen, one part to a page. A tool can select for the person on pages they
+/// never opened (Developer selects the caches it recommends in every tool it lists), and what was never seen must
+/// never be moved from another page, so a page counts only once it has been on screen.
+public struct CarriedSelection: Sendable {
+ /// One page of a tool: `tool` names the tool, and `scope` the page within it, such as a developer tool, a
+ /// project, or a kind of installer. It is empty for a tool that is one page.
+ public struct Page: Sendable, Hashable {
+ public let tool: String
+ public let scope: String
+
+ public init(tool: String, scope: String) {
+ self.tool = tool
+ self.scope = scope
+ }
+ }
+
+ /// What one page has selected: its items with the sizes the page measured, nil where it could not, and the
+ /// source History names them by.
+ public struct Part: Sendable, Hashable, Identifiable {
+ public let page: Page
+ public let source: String
+ public let sourceKey: String?
+ public let sizes: [URL: Int64?]
+
+ public init(page: Page, source: String, sourceKey: String?, sizes: [URL: Int64?]) {
+ self.page = page
+ self.source = source
+ self.sourceKey = sourceKey
+ self.sizes = sizes
+ }
+
+ public var id: Page { page }
+ public var count: Int { sizes.count }
+ public var total: SizeTotal { SizeTotal(sizes.values) }
+
+ /// What moved of this part, as History records of `batch`: each under the part's source and tool, with the
+ /// size its page measured, and none where the page could not measure it.
+ public func records(of result: TrashResult, batch: UUID) -> [RemovalRecord] {
+ result.trashed.map { item in
+ RemovalRecord(
+ batch: batch,
+ item: item,
+ size: sizes[item.originalURL] ?? nil,
+ source: source,
+ sourceKey: sourceKey,
+ tool: page.tool
+ )
+ }
+ }
+ }
+
+ /// What a pass did with each part: moved, with what came of it, or kept whole by its tool.
+ public struct Pass: Sendable {
+ public var moved: [(part: Part, result: TrashResult)] = []
+ public var kept: [Part] = []
+ }
+
+ /// The pages seen so far, in the order they were first seen.
+ private var seen: [Page] = []
+
+ public init() {}
+
+ public mutating func saw(_ page: Page) {
+ if !seen.contains(page) { seen.append(page) }
+ }
+
+ /// The parts that move: those of `candidates` whose page was seen and has something selected, in the order of
+ /// `tools`, which is the sidebar's, and within a tool in the order its pages were seen.
+ public func parts(from candidates: [Part], order tools: [String]) -> [Part] {
+ func place(_ part: Part) -> (Int, Int) {
+ (tools.firstIndex(of: part.page.tool) ?? tools.count, seen.firstIndex(of: part.page) ?? seen.count)
+ }
+ return candidates
+ .filter { !$0.sizes.isEmpty && seen.contains($0.page) }
+ .sorted { place($0) < place($1) }
+ }
+
+ /// Moves each part in turn with `move`, which runs the part's own tool with its own checks and answers nil when
+ /// the tool kept the whole part (an app it waits for was opened, for example). Every part is tried, whatever
+ /// came of the ones before.
+ public static func pass(_ parts: [Part], move: (Part) async -> TrashResult?) async -> Pass {
+ var pass = Pass()
+ for part in parts {
+ if let result = await move(part) {
+ pass.moved.append((part, result))
+ } else {
+ pass.kept.append(part)
+ }
+ }
+ return pass
+ }
+}
+
+extension Sequence where Element == CarriedSelection.Part {
+ public var itemCount: Int { reduce(0) { $0 + $1.count } }
+ public var total: SizeTotal { SizeTotal(flatMap(\.sizes.values)) }
+
+ /// The tools the parts come from, each once, in the parts' order.
+ public var tools: [String] {
+ var tools: [String] = []
+ for part in self where !tools.contains(part.page.tool) {
+ tools.append(part.page.tool)
+ }
+ return tools
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
index b3768079..14f58d97 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
@@ -44,8 +44,9 @@ public actor RefusalLog {
FileLock.whileHeld(beside: url) { current() ?? [] }
}
- public func add(_ failures: [TrashFailure], source: String, sourceKey: String? = nil, tool: String) {
- let batch = UUID()
+ /// 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
let records = failures.map { RefusalRecord(failure: $0, date: date, source: source, sourceKey: sourceKey, tool: tool, batch: batch) }
guard !records.isEmpty else { return }
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift
new file mode 100644
index 00000000..0b3be8eb
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift
@@ -0,0 +1,118 @@
+import Foundation
+@testable import PeelCore
+import Testing
+
+/// What moves when Move to Trash is pressed on any page of the storage tools: what is selected on every page the
+/// person has seen, one part to a page, in one batch.
+struct CarriedSelectionTests {
+ private typealias Page = CarriedSelection.Page
+ private typealias Part = CarriedSelection.Part
+
+ private let tools = ["orphans", "developer", "projects", "installers", "duplicates", "space", "fileSearch"]
+
+ private func part(_ tool: String, _ scope: String, _ sizes: [String: Int64?], source: String? = nil) -> Part {
+ Part(
+ page: Page(tool: tool, scope: scope),
+ source: source ?? scope,
+ sourceKey: nil,
+ sizes: Dictionary(uniqueKeysWithValues: sizes.map { (URL(filePath: "/Users/x/\($0.key)"), $0.value) })
+ )
+ }
+
+ /// A tool can select for the person on pages they never opened, so only a page they have seen is carried.
+ @Test func aPageNeverSeenIsNotCarried() {
+ var selection = CarriedSelection()
+ selection.saw(Page(tool: "developer", scope: "Xcode"))
+
+ let parts = selection.parts(from: [
+ part("developer", "Xcode", ["DerivedData": 900]),
+ part("developer", "npm", ["_cacache": 300]),
+ ], order: tools)
+
+ #expect(parts.map(\.page.scope) == ["Xcode"])
+ }
+
+ /// The parts move in the sidebar's order of the tools, and within a tool in the order its pages were seen.
+ @Test func partsFollowTheToolsThenTheOrderSeen() {
+ var selection = CarriedSelection()
+ for page in [Page(tool: "projects", scope: "Peel"), Page(tool: "developer", scope: "npm"), Page(tool: "developer", scope: "Xcode")] {
+ selection.saw(page)
+ }
+ selection.saw(Page(tool: "developer", scope: "npm"))
+
+ let parts = selection.parts(from: [
+ part("developer", "Xcode", ["DerivedData": 900]),
+ part("projects", "Peel", ["node_modules": 300]),
+ part("developer", "npm", ["_cacache": 300]),
+ ], order: tools)
+
+ #expect(parts.map(\.page) == [
+ Page(tool: "developer", scope: "npm"),
+ Page(tool: "developer", scope: "Xcode"),
+ Page(tool: "projects", scope: "Peel"),
+ ])
+ }
+
+ /// A page with nothing selected carries nothing.
+ @Test func aPageWithNothingSelectedIsLeftOut() {
+ var selection = CarriedSelection()
+ selection.saw(Page(tool: "duplicates", scope: ""))
+
+ #expect(selection.parts(from: [part("duplicates", "", [:])], order: tools).isEmpty)
+ }
+
+ /// The whole is every part's items together, and it says "Over" when one of their sizes is not known.
+ @Test func theWholeCountsEveryPart() {
+ let parts = [
+ part("developer", "Xcode", ["DerivedData": 900, "ModuleCache": 100]),
+ part("developer", "npm", ["_cacache": nil]),
+ part("space", "logs", ["a.log": 50]),
+ ]
+
+ #expect(parts.itemCount == 4)
+ #expect(parts.total == SizeTotal(known: 1_050, isComplete: false))
+ #expect(parts.tools == ["developer", "space"])
+ }
+
+ /// Every part is tried in turn, whatever came of the ones before: a part whose tool kept it (an app it waits
+ /// for was opened) stays whole, and the others still move.
+ @Test func aPartKeptByItsToolDoesNotStopTheOthers() async {
+ let parts = [
+ part("developer", "Xcode", ["DerivedData": 900], source: "Xcode"),
+ part("projects", "Peel", ["node_modules": 300], source: "Peel"),
+ ]
+ var tried: [String] = []
+ let pass = await CarriedSelection.pass(parts) { part in
+ tried.append(part.page.scope)
+ guard part.page.tool != "developer" else { return nil }
+ return TrashResult(trashed: part.sizes.keys.map { TrashedItem(originalURL: $0, trashedURL: $0, date: .now) })
+ }
+
+ #expect(tried == ["Xcode", "Peel"])
+ #expect(pass.kept.map(\.page.scope) == ["Xcode"])
+ #expect(pass.moved.map(\.part.page.scope) == ["Peel"])
+ }
+
+ /// What a pass moved is one History batch, each record under its own part's source and tool, with the size
+ /// its page measured, and none for an item whose size was not known.
+ @Test func whatMovedIsOneBatchWithEachPartsName() async {
+ let parts = [
+ part("developer", "Xcode", ["DerivedData": 900], source: "Xcode"),
+ part("duplicates", "", ["copy.bin": nil], source: "Duplicates"),
+ ]
+ let batch = UUID()
+ var records: [RemovalRecord] = []
+ _ = await CarriedSelection.pass(parts) { part in
+ let result = TrashResult(trashed: part.sizes.keys.map { TrashedItem(originalURL: $0, trashedURL: $0, date: .now) })
+ records += part.records(of: result, batch: batch)
+ return result
+ }
+
+ #expect(records.allSatisfy { $0.batch == batch })
+ #expect(Set(records.map(\.tool)) == ["developer", "duplicates"])
+ #expect(records.first { $0.tool == "developer" }?.source == "Xcode")
+ #expect(records.first { $0.tool == "developer" }?.size == 900)
+ #expect(records.first { $0.tool == "duplicates" }?.size == nil)
+ #expect(RemovalRecord.grouped(records).first?.parts.map(\.source) == ["Xcode", "Duplicates"])
+ }
+}