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.

Put an item back on its disk wherever that disk is mounted now

Țugui Dragoș64767f487ffb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 071cc920..68f0fb5b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -398,8 +398,8 @@ its changes the way [Keep a Changelog](https://keepachangelog.com/) suggests.
- Put Back says why an item stays: excluded since the move, a protected place, not in the Trash where Peel put it, a
locked item or folder, App Management, or a folder that isn't there anymore, each with its step. `peel restore`
says the same, and leaves out of its plan what only the helper can put back.
-- An item on a disk with the same name as another, or one renamed, is found by its volume, not its name, for removals
- from this version on.
+- An item on a disk with the same name as another, or one renamed, is found by its volume, not its name, and goes back
+ on that disk wherever it is mounted now, for removals from this version on.
- An uninstall's Dock icons go back at once, each beside the icons it sat between.
- History is read again when Peel comes forward, never says Nothing Removed Yet while it can't be read, and keeps
fewer removals rather than growing past what it reads back.
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
index 2c732b87..6d308847 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
@@ -5,7 +5,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {
public let id: UUID
/// Everything removed in one go shares a batch, so History can show it as one entry.
public let batch: UUID
- public let originalURL: URL
+ public private(set) var originalURL: 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?
@@ -40,7 +40,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {
self.batch = batch
originalURL = item.originalURL
trashedURL = item.trashedURL
- self.disk = disk ?? TrashedDisk(of: item.trashedURL)
+ self.disk = disk ?? TrashedDisk(of: item)
date = item.date
identity = item.identity
self.size = size
@@ -94,11 +94,15 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {
return URL(filePath: "/Volumes/" + components[2]).isThere
}
- /// The record with its place in the Trash where its disk is mounted now.
+ /// The record with both its places where its disk is mounted now: another disk can have taken the name it had.
public func located(on disks: MountedDisks) -> RemovalRecord {
guard let disk, let place = disks.place(of: disk.volume) else { return self }
+ let onTheDisk = { (path: String) in URL(filePath: place == "/" ? "/" + path : place + "/" + path) }
var located = self
- located.trashedURL = URL(filePath: place == "/" ? "/" + disk.path : place + "/" + disk.path)
+ located.trashedURL = onTheDisk(disk.path)
+ if let originalPath = disk.originalPath {
+ located.originalURL = onTheDisk(originalPath)
+ }
return located
}
}
@@ -108,10 +112,14 @@ 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) {
+ /// Where the item came from, from the top of the disk. Nil in a record written before Peel kept it.
+ public let originalPath: String?
+
+ /// The disk `item` went to the Trash 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 item: TrashedItem) {
+ let url = item.trashedURL
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]
@@ -120,11 +128,16 @@ public struct TrashedDisk: Sendable, Codable, Hashable {
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 }
+ let onTheDisk = { (url: URL) -> String? in
+ guard let located = PathPattern.located(url.path(percentEncoded: false)),
+ PathComponents.isPath(located, inside: place)
+ else { return nil }
+ return String(located.dropFirst(place.count).drop { $0 == "/" })
+ }
+ guard let path = onTheDisk(url) else { return nil }
self.volume = volume
- path = String(item.dropFirst(place.count).drop { $0 == "/" })
+ self.path = path
+ originalPath = onTheDisk(item.originalURL)
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift
index 0fce5152..28e1019c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalJournal.swift
@@ -127,7 +127,7 @@ struct RemovalJournal: Sendable {
let entry = { item in
Entry(
writer: writer, batch: recorded?.batch ?? batch, item: item, part: recorded?.part,
- disk: TrashedDisk(of: item.trashedURL)
+ disk: TrashedDisk(of: item)
)
}
let lines = items
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalStanding.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalStanding.swift
index 6d5a19f3..2e19c490 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalStanding.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalStanding.swift
@@ -12,7 +12,7 @@ public struct RemovalStanding: Sendable {
public private(set) var restorableSize = SizeTotal([])
/// How many records have left the Trash.
public private(set) var missingCount = 0
- private var places: [RemovalRecord.ID: URL] = [:]
+ private var locatedRecords: [RemovalRecord.ID: RemovalRecord] = [:]
/// Reads the disk off the main actor.
@concurrent
@@ -36,10 +36,10 @@ public struct RemovalStanding: Sendable {
continue
}
let located = record.located(on: disks)
+ locatedRecords[record.id] = located
let place = located.standing
if place == .inTheTrash {
inTrash.insert(record.id)
- places[record.id] = located.trashedURL
restorableRecords.append(record)
} else if place == .notKnown {
notKnown.insert(record.id)
@@ -51,9 +51,9 @@ public struct RemovalStanding: Sendable {
restorableSize = restorableRecords.totalSize
}
- /// Where `record`'s item is in the Trash now: its disk may be mounted at another place than when it moved.
- public func place(of record: RemovalRecord) -> URL {
- places[record.id] ?? record.trashedURL
+ /// `record` with its places as they are now: its disk may be mounted at another place than when it moved.
+ public func located(_ record: RemovalRecord) -> RemovalRecord {
+ locatedRecords[record.id] ?? record
}
/// The records among `records` that have left the Trash.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift
index 3cb53518..30fc2acb 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalStandingTests.swift
@@ -52,7 +52,8 @@ struct RemovalStandingTests {
try disk?.remount(at: directory.url.appending(path: "Renamed", directoryHint: .isDirectory))
let elsewhere = RemovalStanding([moved])
let renamed = directory.url.appending(path: "Renamed/.Trashes/\(getuid())/report.txt")
- #expect(PathPattern.comparablePath(of: elsewhere.place(of: moved)) == PathPattern.comparablePath(of: renamed))
+ let located = elsewhere.located(moved).trashedURL
+ #expect(PathPattern.comparablePath(of: located) == PathPattern.comparablePath(of: renamed))
disk = nil
let other = try ScratchVolume(fileSystem: "MS-DOS FAT32", mountedAt: place)
try FileManager.default.createDirectory(at: trash, withIntermediateDirectories: true)
@@ -64,6 +65,55 @@ struct RemovalStandingTests {
withExtendedLifetime(other) {}
}
+ @Test func anItemGoesBackOnItsDiskWhereverThatDiskIsMountedNow() async throws {
+ let directory = try TemporaryDirectory()
+ let place = directory.url.appending(path: "Disk", directoryHint: .isDirectory)
+ let disk = try ScratchVolume(fileSystem: "MS-DOS FAT32", mountedAt: place)
+ let file = place.appending(path: "folder/report.txt")
+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("report".utf8).write(to: file)
+ let trash = place.appending(path: ".Trashes/\(getuid())", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: trash, withIntermediateDirectories: true)
+ let environment = SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ )
+ let service = TrashService(environment: environment) { url in
+ let destination = trash.appending(path: url.lastPathComponent)
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+ let item = try #require(await service.trash([file]).trashed.first)
+ let moved = RemovalRecord(batch: UUID(), item: item, size: 6, source: "Example", tool: "duplicates")
+
+ let renamed = directory.url.appending(path: "Renamed", directoryHint: .isDirectory)
+ try disk.remount(at: renamed)
+ let other = try ScratchVolume(fileSystem: "MS-DOS FAT32", mountedAt: place)
+ let located = moved.located(on: .now())
+
+ #expect(await service.restore(located.trashedItem) == nil)
+ #expect(renamed.appending(path: "folder/report.txt").isThere)
+ #expect(!place.appending(path: "folder/report.txt").isThere)
+ withExtendedLifetime(other) {}
+ }
+
+ @Test func aRecordThatDoesNotSayWhereItCameFromOnItsDiskKeepsThePlaceItNames() throws {
+ let directory = try TemporaryDirectory()
+ let disk = try ScratchVolume(fileSystem: "MS-DOS FAT32", mountedAt: directory.url.appending(path: "Disk"))
+ let volume = try #require(try disk.url.resourceValues(forKeys: [.volumeUUIDStringKey]).volumeUUIDString)
+ let written = try JSONDecoder().decode(
+ TrashedDisk.self, from: Data(#"{"volume": "\#(volume)", "path": ".Trashes/501/report.txt"}"#.utf8)
+ )
+ let original = URL(filePath: "/Volumes/Old/report.txt")
+ let trashed = URL(filePath: "/Volumes/Old/.Trashes/501/report.txt")
+ let item = TrashedItem(originalURL: original, trashedURL: trashed, date: .now)
+ let moved = RemovalRecord(
+ batch: UUID(), item: item, size: 6, source: "Example", tool: "duplicates", disk: written
+ )
+
+ #expect(moved.located(on: .now()).originalURL == original)
+ }
+
@Test func countsAndListsOnlyWhatIsSelectedAndCanBePutBack() throws {
let directory = try TemporaryDirectory()
let first = record(try directory.file(".Trash/first.txt"), size: 1)
diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swift
index f19e51e0..25edb467 100644
--- a/Peel/Model/RemovalHistoryStore.swift
+++ b/Peel/Model/RemovalHistoryStore.swift
@@ -526,9 +526,9 @@ final class RemovalHistoryStore {
var restored: Set<UUID> = []
var problems: [RemovalRecord.ID: RestoreFailure] = [:]
var stayed: [(record: RemovalRecord, failure: RestoreFailure)] = []
- let ordered = records.inPutBackOrder
let disks = await MountedDisks.read()
- let answers = await restoring(ordered.map { $0.located(on: disks).trashedItem }, canUseHelper)
+ let ordered = records.map { $0.located(on: disks) }.inPutBackOrder
+ let answers = await restoring(ordered.map(\.trashedItem), canUseHelper)
for (record, answer) in zip(ordered, answers) {
if let failure = answer {
problems[record.id] = failure
diff --git a/Peel/Views/History/HistoryDetailView.swift b/Peel/Views/History/HistoryDetailView.swift
index d8b9e0da..7b749e59 100644
--- a/Peel/Views/History/HistoryDetailView.swift
+++ b/Peel/Views/History/HistoryDetailView.swift
@@ -113,9 +113,8 @@ struct HistoryDetailView: View {
ForEach(batch.records) { record in
HistoryRecordRow(
history: history,
- record: record,
+ record: standing.located(record),
place: place(of: record, in: standing),
- trashedURL: standing.place(of: record),
failure: history.failures[record.id],
isSelected: history.isSelected(record),
isFirst: record.id == batch.records.first?.id
@@ -240,10 +239,9 @@ private enum RecordNote {
/// only the row it affects, not the whole batch (see `RowSelection`).
private struct HistoryRecordRow: View {
let history: RemovalHistoryStore
+ /// The record with its places as they are now, which are not where they were when its disk is mounted elsewhere.
let record: RemovalRecord
let place: RecordPlace
- /// Where the item is now, which is not where it went when its disk is mounted at another place.
- let trashedURL: URL
/// Why the last Put Back left this item in the Trash, said under it.
let failure: RestoreFailure?
let isSelected: Bool
@@ -269,7 +267,7 @@ private struct HistoryRecordRow: View {
.contextMenu {
if place == .inTrash {
Button("Show in Finder", systemImage: "folder") {
- NSWorkspace.shared.activateFileViewerSelecting([trashedURL])
+ NSWorkspace.shared.activateFileViewerSelecting([record.trashedURL])
}
}
Button("Copy Path", systemImage: "doc.on.doc") {