Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Find a removed item's disk by its volume, not its name
Țugui Dragoș0b789ee2f1c6
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swiftindex 8645940d..3477fda4 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift@@ -10,6 +10,7 @@ extension RemovalPart {/// One removal, as History shows it: everything that went in one go, grouped and dated as the app does.struct Batch {let group: RemovalGroup+ let disks: MountedDisksvar id: UUID { group.id }var records: [RemovalRecord] { group.records }@@ -20,19 +21,23 @@ struct Batch {/// The tool the removal moved from, or nil for one that moved from several or was interrupted.var tool: String? { parts.count == 1 ? parts[0].namedTool : nil }var size: SizeTotal { group.size }- /// 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) }-- static func all(in records: [RemovalRecord]) -> [Batch] {- RemovalRecord.grouped(records).map(Batch.init)+ /// The records whose items are still in the Trash of a disk that is connected. An item emptied from the Trash+ /// can't be put back.+ var restorable: [RemovalRecord] { records.filter { $0.isOnAConnectedDisk(disks) && $0.isStillInTrash } }+ /// The records on a disk that isn't connected: their items may still be in its Trash.+ var waiting: [RemovalRecord] { records.filter { !$0.isOnAConnectedDisk(disks) } }++ /// Each record where its disk is mounted now.+ static func all(in records: [RemovalRecord], disks: MountedDisks = .now()) -> [Batch] {+ RemovalRecord.grouped(records.map { $0.located(on: disks) }).map { Batch(group: $0, disks: disks) }}/// The first eight characters of the batch ID, which `peel history` shows and `peel restore` accepts.var shortID: String { String(id.uuidString.prefix(8)).lowercased() }var state: String {+ if !waiting.isEmpty { return "on a disk that isn't connected" }if records.allSatisfy(\.isStillInTrash) { return "in the Trash" }- if records.contains(where: { !$0.isOnAConnectedDisk }) { return "on a disk that isn't connected" }if records.contains(where: { $0.standing == .notKnown }) { return "can't look in the Trash" }return restorable.isEmpty ? "gone from the Trash" : "partly gone from the Trash"}@@ -332,7 +337,7 @@ struct RestoreCommand: AsyncParsableCommand {}let going = inTheTrash.filter { record in !refused.contains { $0.record.id == record.id } }// An item in the Trash of a disk that isn't connected is still there, once the disk is.- let waiting = batch.records.filter { !$0.isStillInTrash && !$0.isOnAConnectedDisk }+ let waiting = batch.waitinglet items = Output.count(waiting.count, "item is", "items are")let elsewhere = waiting.isEmpty? nildiff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swiftindex 9ecc285f..ed22260c 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift@@ -6,7 +6,9 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {/// Everything removed in one go shares a batch, so History can show it as one entry.public let batch: UUIDpublic let originalURL: URL- public let trashedURL: URL+ public private(set) var trashedURL: URL+ /// The disk the item moved on, when it isn't the startup disk. Nil in a record written before Peel kept it.+ public let disk: TrashedDisk?public let date: Date/// Which item went to the Trash, so one that lands in the same place later is never taken for it. Nil in a record/// written before Peel kept it.@@ -37,6 +39,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {self.batch = batchoriginalURL = item.originalURLtrashedURL = item.trashedURL+ disk = TrashedDisk(of: item.trashedURL)date = item.dateidentity = item.identityself.size = size@@ -54,6 +57,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {batch = try container.decode(UUID.self, forKey: .batch)originalURL = try container.decode(URL.self, forKey: .originalURL)trashedURL = try container.decode(URL.self, forKey: .trashedURL)+ disk = try? container.decodeIfPresent(TrashedDisk.self, forKey: .disk)date = try container.decode(Date.self, forKey: .date)identity = try container.decodeIfPresent(TrashedItem.Identity.self, forKey: .identity)size = try container.decodeIfPresent(Int64.self, forKey: .size).map { max(0, $0) }@@ -80,12 +84,70 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {}/// False while the disk whose Trash holds the item is not connected. The item may still be there, so the- /// record is not treated as missing.- public var isOnAConnectedDisk: Bool {+ /// record is not treated as missing. A disk is known by its volume, which stays with it when it is renamed, while+ /// its name and place can be another disk's; a record written before Peel kept it goes by the name in its path.+ public func isOnAConnectedDisk(_ disks: MountedDisks) -> Bool {+ if let disk { return disks.place(of: disk.volume) != nil }let components = trashedURL.pathComponentsguard components.count > 2, components[1] == "Volumes" else { return true }return URL(filePath: "/Volumes/" + components[2]).isThere}++ /// The record with its place in the Trash where its disk is mounted now.+ public func located(on disks: MountedDisks) -> RemovalRecord {+ guard let disk, let place = disks.place(of: disk.volume) else { return self }+ var located = self+ located.trashedURL = URL(filePath: place == "/" ? "/" + disk.path : place + "/" + disk.path)+ return located+ }+}++/// The disk an item moved on: its volume's UUID, and where the item was on that disk.+public struct TrashedDisk: Sendable, Codable, Hashable {+ public let volume: String+ /// The item's path from the top of the disk, without the place the disk was mounted at.+ public let path: String++ /// The disk `url` is on, or nil for the startup disk, which is always there, or when macOS doesn't say. The home's+ /// Trash is on the home's disk, which is there while anyone uses it, so nothing is asked for what is in the home.+ init?(of url: URL) {+ let home = URL.homeDirectory.path(percentEncoded: false)+ guard !PathComponents.isPath(url.path(percentEncoded: false), inside: home) else { return nil }+ let keys: Set<URLResourceKey> = [.volumeURLKey, .volumeUUIDStringKey, .volumeIsRootFileSystemKey]+ guard let values = try? url.resourceValues(forKeys: keys), values.volumeIsRootFileSystem != true,+ let volume = values.volumeUUIDString, let mount = values.volume+ else { return nil }+ // The kernel's spelling, as the mount point is spelled: `resolvingSymlinksInPath` drops `/private`.+ let place = MountedDisks.path(of: mount)+ guard let item = PathPattern.located(url.path(percentEncoded: false)),+ PathComponents.isPath(item, inside: place)+ else { return nil }+ self.volume = volume+ path = String(item.dropFirst(place.count).drop { $0 == "/" })+ }+}++/// The disks mounted now, each by its volume's UUID, read once for whatever asks about many records.+public struct MountedDisks: Sendable {+ private let places: [String: String]++ public static func now() -> MountedDisks {+ let key = URLResourceKey.volumeUUIDStringKey+ let volumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: [key], options: []) ?? []+ let places = volumes.compactMap { url in+ (try? url.resourceValues(forKeys: [key]).volumeUUIDString).flatMap(\.self).map { ($0, path(of: url)) }+ }+ return MountedDisks(places: Dictionary(places, uniquingKeysWith: { first, _ in first }))+ }++ func place(of volume: String) -> String? {+ places[volume]+ }++ static func path(of url: URL) -> String {+ let path = url.path(percentEncoded: false)+ return path.count > 1 && path.hasSuffix("/") ? String(path.dropLast()) : path+ }}extension [URL: Int64] {diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalStanding.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalStanding.swiftindex a5158536..7d12896b 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalStanding.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalStanding.swift@@ -22,18 +22,22 @@ public struct RemovalStanding: Sendable {/// The records among `records` that have left the Trash, looked at again.@concurrentpublic static func stillGone(_ records: [RemovalRecord]) async -> [RemovalRecord] {- records.filter { $0.standing == .gone && $0.isOnAConnectedDisk }+ let disks = MountedDisks.now()+ return records.filter { $0.isOnAConnectedDisk(disks) && $0.located(on: disks).standing == .gone }}- init(_ records: [RemovalRecord]) {+ init(_ records: [RemovalRecord], disks: MountedDisks = .now()) {var restorableRecords: [RemovalRecord] = []for record in records {- let place = record.standing+ // Another disk can have this one's name and place, so a disk that isn't connected is asked about first.+ guard record.isOnAConnectedDisk(disks) else {+ away.insert(record.id)+ continue+ }+ let place = record.located(on: disks).standingif place == .inTheTrash {inTrash.insert(record.id)restorableRecords.append(record)- } else if !record.isOnAConnectedDisk {- away.insert(record.id)} else if place == .notKnown {notKnown.insert(record.id)} else {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swiftindex ac46ac38..0d16f1a8 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift@@ -212,9 +212,9 @@ struct RemovalHistoryTests {tool: "applications")#expect(present.isStillInTrash)- #expect(present.isOnAConnectedDisk)+ #expect(present.isOnAConnectedDisk(.now()))#expect(!record("Gone.app").isStillInTrash)- #expect(record("Gone.app").isOnAConnectedDisk)+ #expect(record("Gone.app").isOnAConnectedDisk(.now()))}/// An item in the Trash of a disk that is not connected may still be there, so its record is kept.@@ -231,7 +231,7 @@ struct RemovalHistoryTests {tool: "projects")#expect(!away.isStillInTrash)- #expect(!away.isOnAConnectedDisk)+ #expect(!away.isOnAConnectedDisk(.now()))}private static func record(batch: UUID, date: Date = .now, name: String = "Item") -> RemovalRecord {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swiftindex 02e3402b..8f0c2a66 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift@@ -39,6 +39,29 @@ struct RemovalStandingTests {#expect(standing.missing(among: records).map(\.id) == [gone.id])}+ @Test func knowsAnItemsDiskByItsVolumeRatherThanItsName() throws {+ let directory = try TemporaryDirectory()+ let place = directory.url.appending(path: "Disk", directoryHint: .isDirectory)+ var disk: ScratchVolume? = try ScratchVolume(fileSystem: "MS-DOS FAT32", mountedAt: place)+ let trashed = place.appending(path: ".Trashes/\(getuid())/report.txt")+ let trash = trashed.deletingLastPathComponent()+ try FileManager.default.createDirectory(at: trash, withIntermediateDirectories: true)+ try Data("report".utf8).write(to: trashed)+ let moved = record(trashed, size: 6)++ try disk?.remount(at: directory.url.appending(path: "Renamed", directoryHint: .isDirectory))+ let elsewhere = RemovalStanding([moved])+ disk = nil+ let other = try ScratchVolume(fileSystem: "MS-DOS FAT32", mountedAt: place)+ try FileManager.default.createDirectory(at: trash, withIntermediateDirectories: true)+ try Data("other".utf8).write(to: trashed)+ let sameName = RemovalStanding([moved])++ #expect(elsewhere.inTrash == [moved.id])+ #expect(sameName.away == [moved.id] && sameName.inTrash.isEmpty)+ withExtendedLifetime(other) {}+ }+@Test func countsAndListsOnlyWhatIsSelectedAndCanBePutBack() throws {let directory = try TemporaryDirectory()let first = record(try directory.file(".Trash/first.txt"), size: 1)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ScratchVolume.swift b/Packages/PeelCore/Tests/PeelCoreTests/ScratchVolume.swiftindex 1cc81a8b..b8ae1c19 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ScratchVolume.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ScratchVolume.swift@@ -3,7 +3,7 @@ import Foundation/// A small disk of its own for a test, formatted with a file system the startup disk does not use, made with `hdiutil`/// and mounted at a folder the test chooses, out of Finder's sight. It is detached when the test lets go of it.final class ScratchVolume {- let url: URL+ private(set) var url: URLprivate let image: TemporaryDirectory/// `fileSystem` is a name `hdiutil create -fs` takes, such as `ExFAT` or `MS-DOS FAT32`.@@ -20,6 +20,15 @@ final class ScratchVolume {try? Self.hdiutil("detach", "-quiet", "-force", url.path)}+ /// The same disk, detached and mounted again at `place`, as a disk renamed or plugged in again lands elsewhere.+ func remount(at place: URL) throws {+ try Self.hdiutil("detach", "-quiet", "-force", url.path)+ try FileManager.default.createDirectory(at: place, withIntermediateDirectories: true)+ let file = image.url.appending(path: "disk.dmg")+ try Self.hdiutil("attach", "-quiet", "-nobrowse", "-noautoopen", "-noverify", "-mountpoint", place.path, file.path)+ url = place+ }+private static func hdiutil(_ arguments: String...) throws {let process = try Process.run(URL(filePath: "/usr/bin/hdiutil"), arguments: arguments)process.waitUntilExit()diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swiftindex 6cdbb5e8..7ccc8260 100644--- a/Peel/Model/RemovalHistoryStore.swift+++ b/Peel/Model/RemovalHistoryStore.swift@@ -411,7 +411,8 @@ final class RemovalHistoryStore {var problems: [RemovalRecord.ID: RestoreFailure] = [:]var stayed: [(record: RemovalRecord, failure: RestoreFailure)] = []let ordered = records.inPutBackOrder- let answers = await restoring(ordered.map(\.trashedItem), canUseHelper)+ let disks = MountedDisks.now()+ let answers = await restoring(ordered.map { $0.located(on: disks).trashedItem }, canUseHelper)for (record, answer) in zip(ordered, answers) {if let failure = answer {problems[record.id] = failure