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.

Count and move an item selected on two pages once

Țugui Dragoș9b6d33947c57
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/CarriedSelection.swift b/Packages/PeelCore/Sources/PeelCore/Removal/CarriedSelection.swift
index 30271713..44ffcfd4 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/CarriedSelection.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/CarriedSelection.swift
@@ -37,6 +37,11 @@ public struct CarriedSelection: Sendable {
public var count: Int { sizes.count }
public var total: SizeTotal { SizeTotal(sizes.values) }
+ /// The same part with only `sizes`, some of its own.
+ func keeping(_ sizes: [URL: Int64?]) -> Part {
+ Part(page: page, title: title, source: source, sourceKey: sourceKey, sizes: sizes)
+ }
+
public var removalPart: RemovalPart {
RemovalPart(source: source, sourceKey: sourceKey, tool: page.tool)
}
@@ -74,6 +79,19 @@ public struct CarriedSelection: Sendable {
/// The pages seen so far, in the order they were first seen.
private var seen: [Page] = []
+ /// A path as written, without a trailing slash, which two tools' URLs for one item share. Not `comparablePath`,
+ /// which reads the disk, while the bar asks for the parts whenever a selection changes.
+ static func writtenPath(of url: URL) -> Substring {
+ let path = url.path(percentEncoded: false)
+ return path.count > 1 && path.hasSuffix("/") ? path.dropLast() : Substring(path)
+ }
+
+ /// The folders above `path`, each the part of it before a slash. Split at the slash byte, since a `Character`
+ /// joins a slash and a combining mark after it.
+ static func folders(above path: Substring) -> some Sequence<Substring> {
+ path.utf8.indices.lazy.filter { $0 != path.startIndex && path.utf8[$0] == UInt8(ascii: "/") }.map { path[..<$0] }
+ }
+
public init() {}
public mutating func saw(_ page: Page) {
@@ -85,14 +103,38 @@ public struct CarriedSelection: Sendable {
}
/// 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] {
+ /// `tools`, which is the sidebar's, and within a tool in the order its pages were seen. Each item is in one of
+ /// them only (`eachItemOnce`), the part of the page `asking`, where Move to Trash is pressed, first.
+ public func parts(from candidates: [Part], order tools: [String], asking page: Page? = nil) -> [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) }
+ let parts = candidates.filter { !$0.sizes.isEmpty && seen.contains($0.page) }.sorted { place($0) < place($1) }
+ return Self.eachItemOnce(in: parts, asking: page)
+ }
+
+ /// Two tools can list the same item, or one inside a folder the other lists, and an item selected on both pages
+ /// would count and move twice. So an item inside a folder another part holds goes with that folder, an item two
+ /// parts hold stays in the asking page's part or else the first, and a part left with nothing goes. One page's
+ /// own selection is left as its tool made it.
+ private static func eachItemOnce(in parts: [Part], asking page: Page?) -> [Part] {
+ guard parts.count > 1 else { return parts }
+ let paths = parts.map { part in part.sizes.keys.map { (url: $0, path: writtenPath(of: $0)) } }
+ var holder: [Substring: Int] = [:]
+ let asking = parts.indices.filter { parts[$0].page == page }
+ for index in asking + parts.indices.filter({ !asking.contains($0) }) {
+ for (_, path) in paths[index] where holder[path] == nil {
+ holder[path] = index
+ }
+ }
+ return parts.indices.compactMap { index in
+ let kept = paths[index].filter { _, path in
+ holder[path] == index && !folders(above: path).contains { holder[$0].map { $0 != index } ?? false }
+ }
+ guard kept.count < parts[index].sizes.count else { return parts[index] }
+ let urls = Set(kept.map(\.url))
+ return kept.isEmpty ? nil : parts[index].keeping(parts[index].sizes.filter { urls.contains($0.key) })
+ }
}
/// Moves each part in turn with `move`, which runs the part's own tool with its own checks and answers nil when
@@ -115,6 +157,19 @@ extension Sequence where Element == CarriedSelection.Part {
public var itemCount: Int { reduce(0) { $0 + $1.count } }
public var total: SizeTotal { SizeTotal(flatMap(\.sizes.values)) }
+ /// The parts holding an item in `moved`, or one inside a folder in it, each with only those items: what their
+ /// tools have to bring up to date, whichever part moved it.
+ public func holding(_ moved: [URL]) -> [CarriedSelection.Part] {
+ let gone = Set(moved.map(CarriedSelection.writtenPath(of:)))
+ return compactMap { part in
+ let sizes = part.sizes.filter { url, _ in
+ let path = CarriedSelection.writtenPath(of: url)
+ return gone.contains(path) || CarriedSelection.folders(above: path).contains(where: gone.contains)
+ }
+ return sizes.isEmpty ? nil : part.keeping(sizes)
+ }
+ }
+
/// The tools the parts come from, each once, in the parts' order.
public var tools: [String] {
var tools: [String] = []
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/RealFolder.swift b/Packages/PeelCore/Sources/PeelCore/Support/RealFolder.swift
index 2b62946c..da98410a 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/RealFolder.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/RealFolder.swift
@@ -1,4 +1,4 @@
-import Foundation
+public import Foundation
internal import PeelPrivileged
extension URL {
@@ -11,7 +11,7 @@ extension URL {
/// True only when nothing is there under this name. A name macOS cannot look up, as in a folder that cannot be
/// searched, is not missing, so one of Peel's files it cannot reach is never read as one that is not there.
- var isMissing: Bool {
+ public var isMissing: Bool {
var info = stat()
return lstat(path(percentEncoded: false), &info) != 0 && errno == ENOENT
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift
index 5ea4fb06..1733478e 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CarriedSelectionTests.swift
@@ -148,6 +148,80 @@ struct CarriedSelectionTests {
#expect(Set(pass.refused.flatMap(\.sizes.keys).map(\.lastPathComponent)) == ["com.apple.akd", "Kept.app"])
}
+ /// Two tools can list the same item, as App Caches and Downloaded Updates both list an updater's folder: it
+ /// counts and moves once, with the first part, and a part left with nothing goes.
+ @Test func anItemTwoPagesSelectedCountsOnce() {
+ var selection = CarriedSelection()
+ selection.saw(Page(tool: "installers", scope: "updateDownload"))
+ selection.saw(Page(tool: "space", scope: "caches"))
+
+ let parts = selection.parts(from: [
+ part("installers", "updateDownload", ["Library/Caches/notes-updater": 300]),
+ part("space", "caches", ["Library/Caches/notes-updater/": 300, "Library/Caches/org.example.app": 50]),
+ ], order: tools)
+
+ #expect(parts.map(\.page.scope) == ["updateDownload", "caches"])
+ #expect(parts.itemCount == 2)
+ #expect(parts.total.known == 350)
+ #expect(parts.last.map { Set($0.sizes.keys.map(\.lastPathComponent)) } == ["org.example.app"])
+ }
+
+ /// A shared item counts with the page Move to Trash is pressed on, when that page holds it.
+ @Test func anItemTwoPagesSelectedCountsWithThePageAsking() {
+ var selection = CarriedSelection()
+ selection.saw(Page(tool: "installers", scope: "updateDownload"))
+ selection.saw(Page(tool: "space", scope: "caches"))
+
+ let parts = selection.parts(from: [
+ part("installers", "updateDownload", ["Library/Caches/notes-updater": 300]),
+ part("space", "caches", ["Library/Caches/notes-updater/": 300]),
+ ], order: tools, asking: Page(tool: "space", scope: "caches"))
+
+ #expect(parts.map(\.page.scope) == ["caches"])
+ }
+
+ /// An item inside a folder another page selected moves with that folder, whichever page comes first.
+ @Test func anItemInsideAFolderAnotherPageSelectedCountsWithTheFolder() {
+ var selection = CarriedSelection()
+ selection.saw(Page(tool: "installers", scope: "updateDownload"))
+ selection.saw(Page(tool: "space", scope: "caches"))
+
+ let parts = selection.parts(from: [
+ part("installers", "updateDownload", ["Library/Caches/org.example.notes/org.sparkle-project.Sparkle": 300]),
+ part("space", "caches", ["Library/Caches/org.example.notes": 900]),
+ ], order: tools)
+
+ #expect(parts.map(\.page.scope) == ["caches"])
+ #expect(parts.total.known == 900)
+ }
+
+ /// One page's own selection is left as its tool made it.
+ @Test func onePagesSelectionIsLeftAsItIs() {
+ var selection = CarriedSelection()
+ selection.saw(Page(tool: "space", scope: "caches"))
+
+ let parts = selection.parts(from: [
+ part("space", "caches", ["Library/Caches/org.example.notes": 900, "Library/Caches/org.example.notes/a": 1]),
+ ], order: tools)
+
+ #expect(parts.itemCount == 2)
+ }
+
+ /// After a pass, every part that holds an item that moved, or one inside a folder that moved, so its tool is
+ /// brought up to date even when another page moved it.
+ @Test func findsThePartsHoldingWhatMoved() {
+ let parts = [
+ part("installers", "updateDownload", ["Library/Caches/notes-updater": 300]),
+ part("installers", "updateDownload2", ["Library/Caches/org.example.notes/org.sparkle-project.Sparkle": 9]),
+ part("developer", "npm", ["_cacache": 300]),
+ ]
+ let moved = ["Library/Caches/notes-updater/", "Library/Caches/org.example.notes"].map {
+ URL(filePath: "/Users/x/\($0)")
+ }
+
+ #expect(parts.holding(moved).map(\.page.scope) == ["updateDownload", "updateDownload2"])
+ }
+
/// 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 {
diff --git a/Peel/Model/DuplicateLibrary.swift b/Peel/Model/DuplicateLibrary.swift
index 941685c8..c43ce1d0 100644
--- a/Peel/Model/DuplicateLibrary.swift
+++ b/Peel/Model/DuplicateLibrary.swift
@@ -294,8 +294,18 @@ extension DuplicateLibrary: CarriesSelection {
return result
}
- /// Nothing to bring up to date: the move took what it moved out of the list.
- func refresh(after parts: [CarriedSelection.Part], apps: AppLibrary) async {}
+ /// Takes out of the list what another page moved. What this page's own move took is out already.
+ func refresh(after parts: [CarriedSelection.Part], apps: AppLibrary) async {
+ let selected = selectedURLs.union(selectedFolders)
+ let gone = Set(parts.flatMap(\.sizes.keys).filter { selected.contains($0) && $0.isMissing })
+ guard let scan, !gone.isEmpty else { return }
+ let remaining = scan.removing(gone)
+ self.scan = remaining
+ unselect(gone)
+ if let selection, !remaining.holds(selection) {
+ self.selection = nil
+ }
+ }
func deselect(_ part: CarriedSelection.Part) {
unselect(part.sizes.keys)
diff --git a/Peel/Model/SelectionCarrier.swift b/Peel/Model/SelectionCarrier.swift
index 84abfdb6..bf019e6a 100644
--- a/Peel/Model/SelectionCarrier.swift
+++ b/Peel/Model/SelectionCarrier.swift
@@ -70,7 +70,9 @@ final class SelectionCarrier {
var carried = carried
carried.saw(page)
let order = Tool.Group.allCases.flatMap(\.tools)
- return carried.parts(from: order.compactMap { tools[$0] }.flatMap(\.carriedParts), order: order.map(\.rawValue))
+ return carried.parts(
+ from: order.compactMap { tools[$0] }.flatMap(\.carriedParts), order: order.map(\.rawValue), asking: page
+ )
}
func appToQuit(among parts: [CarriedSelection.Part]) -> String? {
@@ -108,10 +110,13 @@ final class SelectionCarrier {
for part in pass.refused {
tool(of: part)?.deselect(part)
}
- let moved = pass.moved.map(\.part)
- for name in moved.tools {
+ // A tool whose selection holds what another page moved is brought up to date as well.
+ let held = Tool.Group.allCases.flatMap(\.tools).compactMap { tools[$0] }.flatMap(\.carriedParts)
+ .holding(pass.result.trashed.map(\.originalURL))
+ let changed = pass.moved.map(\.part) + held
+ for name in changed.tools {
guard let tool = Tool(rawValue: name) else { continue }
- await tools[tool]?.refresh(after: moved.filter { $0.page.tool == name }, apps: apps)
+ await tools[tool]?.refresh(after: changed.filter { $0.page.tool == name }, apps: apps)
}
}
}