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
Put Back knows an item by which one it is, not by its name
Țugui Dragoș692c8e43d247
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 6b93e49c..af8c2272 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -94,8 +94,9 @@ Take the most common case, uninstalling an app. Every other page follows the sambefore a removal) until the History page starts it over. What Peel refused to move is recorded too(`refusals.json`), and History lists it under Not Moved, one removal to an entry.8. **Put back.** History's Put Back reads its record as a request, not as a fact: an item returns only from a- real Trash, only to a place the guard allows, and, through the helper, only if the helper's own ledger says- it moved that very item from that very place.+ real Trash, only to a place the guard allows, only when it is the item that went (`TrashedItem.identity`,+ its inode and birth time, read in the Trash as it landed and asked again of the item Put Back holds open),+ and, through the helper, only if the helper's own ledger says it moved that very item from that very place.## What keeps data safediff --git a/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift b/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swiftindex dc71861c..14ce1253 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift@@ -112,9 +112,10 @@ public enum PrivilegedHelper {for url in urls {let path = url.path(percentEncoded: false)if let destination = reply?.moved[path] {- result.trashed.append(TrashedItem(originalURL: url, trashedURL: URL(filePath: destination), date: .now))+ let trashedURL = URL(filePath: destination)+ result.trashed.append(TrashedItem(originalURL: url, trashedURL: trashedURL, date: .now, identity: .init(ofItemAt: trashedURL)))} else if reply == nil, !url.isThere, let link = links[url] ?? nil, let found = TrashService.item(link, in: trash) {- result.trashed.append(TrashedItem(originalURL: url, trashedURL: found, date: .now))+ result.trashed.append(TrashedItem(originalURL: url, trashedURL: found, date: .now, identity: .init(ofItemAt: found)))} else {result.failures.append(TrashFailure(url: url, reason: .failed(reply?.failed[path] ?? Self.unavailable)))}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swiftindex 159fe28e..2a7be54a 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift@@ -7,6 +7,9 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {public let originalURL: URLpublic let trashedURL: URLpublic 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.+ public let identity: TrashedItem.Identity?/// Nil when Peel could not measure the item. It is never read as zero.public let size: Int64?/// What the items belonged to: an app, an orphan group, a file name.@@ -22,6 +25,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {originalURL = item.originalURLtrashedURL = item.trashedURLdate = item.date+ identity = item.identityself.size = sizeself.source = sourceself.sourceKey = sourceKey@@ -36,6 +40,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {originalURL = try container.decode(URL.self, forKey: .originalURL)trashedURL = try container.decode(URL.self, forKey: .trashedURL)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) }source = try container.decode(String.self, forKey: .source)tool = try container.decode(String.self, forKey: .tool)@@ -43,11 +48,11 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {}public var trashedItem: TrashedItem {- TrashedItem(originalURL: originalURL, trashedURL: trashedURL, date: date)+ TrashedItem(originalURL: originalURL, trashedURL: trashedURL, date: date, identity: identity)}public var isStillInTrash: Bool {- trashedURL.isThere+ trashedItem.isInTheTrash}/// False while the disk whose Trash holds the item is not connected. The item may still be there, so thediff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex 797a72fc..cce10699 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -5,6 +5,41 @@ public struct TrashedItem: Sendable, Hashable, Codable {public let originalURL: URLpublic let trashedURL: URLpublic let date: Date+ /// Which item went to the Trash, read there as it landed, so an item that lands in the same place once the Trash+ /// is emptied is never taken for it. Nil in what was recorded before Peel kept it.+ public let identity: Identity?++ /// An item as its volume knows it: its inode and when it was made, which a move within the volume keeps. The+ /// volume's device number is left out, since it follows the order volumes are mounted in.+ public struct Identity: Sendable, Hashable, Codable {+ let inode: UInt64+ let birth: Int64++ init(_ identity: ItemIdentity) {+ inode = identity.inode+ birth = identity.birth+ }++ /// The identity of the item at `url` itself, never of what a link there leads to.+ init?(ofItemAt url: URL) {+ guard let identity = ItemIdentity(ofItemAt: url.path(percentEncoded: false)) else { return nil }+ self.init(identity)+ }+ }++ init(originalURL: URL, trashedURL: URL, date: Date, identity: Identity? = nil) {+ self.originalURL = originalURL+ self.trashedURL = trashedURL+ self.date = date+ self.identity = identity+ }++ /// Whether the item is still where it went in the Trash: something is there and, when Peel knows which item+ /// went, it is that item.+ public var isInTheTrash: Bool {+ guard let identity else { return trashedURL.isThere }+ return Identity(ofItemAt: trashedURL) == identity+ }}public struct TrashFailure: Sendable, Hashable {@@ -227,7 +262,8 @@ public struct TrashService: Sendable {let path = PathPattern.comparablePath(of: url)guard !moved.contains(where: { PathComponents.isPath(path, inside: $0) }) else { continue }do {- let item = TrashedItem(originalURL: url, trashedURL: try moveToTrash(url), date: .now)+ let trashedURL = try moveToTrash(url)+ let item = TrashedItem(originalURL: url, trashedURL: trashedURL, date: .now, identity: .init(ofItemAt: trashedURL))if let removal {journal?.note([item], batch: removal)}@@ -310,7 +346,7 @@ public struct TrashService: Sendable {guard removalGuard.allowsPuttingBack(item.trashedURL, at: item.originalURL), isInATrash(item.trashedURL) else { return .notAllowed }let fileManager = FileManager.default- guard item.trashedURL.isThere else { return .missingFromTrash }+ guard item.isInTheTrash else { return .missingFromTrash }guard !item.originalURL.isThere else { return .alreadyThere }let parent = item.originalURL.deletingLastPathComponent()@@ -326,6 +362,8 @@ public struct TrashService: Sendable {return nil} catch is RefusedOnceHeld {return .notAllowed+ } catch is NotTheItemThatMoved {+ return .missingFromTrash} catch POSIXError.EEXIST {return .alreadyThere} catch {@@ -341,6 +379,9 @@ public struct TrashService: Sendable {/// is asked again about the destination as the kernel names it, and the move never replaces an item there.static func putBack(_ item: TrashedItem, isAllowed: (URL) -> Bool) throws {let trashed = try OpenItem.at(item.trashedURL.path(percentEncoded: false)).get()+ if let identity = item.identity, trashed.identity.map(TrashedItem.Identity.init) != identity {+ throw NotTheItemThatMoved()+ }let folder = try DirectoryHandle.at(item.originalURL.deletingLastPathComponent().path(percentEncoded: false)).get()guard let held = folder.currentPath else { throw POSIXError(.ENOENT) }let name = item.originalURL.lastPathComponent@@ -382,6 +423,10 @@ public struct TrashService: Sendable {/// The guard refused the item once its folder was held open and named by the kernel.struct RefusedOnceHeld: Error {}+ /// What sits where an item went in the Trash is another item: the Trash was emptied, and something of the same+ /// name landed there since.+ struct NotTheItemThatMoved: Error {}+/// A move by name put something other than the checked item in the Trash.struct SomethingElseMoved: Error {let trashedURL: URLdiff --git a/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift b/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swiftindex 881852cc..3d9d23cf 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift@@ -73,8 +73,9 @@ public final class DirectoryHandle: Sendable {/// three, and the birth time tells apart an item that reuses a freed inode number.public struct ItemIdentity: Codable, Hashable, Sendable {let device: Int64- let inode: UInt64- let birth: Int64+ public let inode: UInt64+ /// When the item was made, in nanoseconds since 1970.+ public let birth: Int64init(_ info: stat) {device = Int64(info.st_dev)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swiftindex 5706fe8b..fc92f556 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHistoryTests.swift@@ -98,6 +98,34 @@ struct RemovalHistoryTests {#expect(try decoder.decode([RemovalRecord].self, from: stored).first?.date == Date(timeIntervalSince1970: 5.25))}+ /// Which item went to the Trash is kept in the log, so Put Back knows it after Peel quits; a record written before+ /// Peel kept it reads as it always did, by name.+ @Test func whichItemMovedIsKeptInTheLog() async throws {+ let directory = try TemporaryDirectory()+ let trashed = try directory.file("home/.Trash/report.pdf")+ let item = TrashedItem(+ originalURL: directory.url.appending(path: "home/Documents/report.pdf"),+ trashedURL: trashed,+ date: .now,+ identity: TrashedItem.Identity(ofItemAt: trashed)+ )+ let log = RemovalLog(url: directory.url.appending(path: "Peel/removals.json"))+ _ = await log.add([RemovalRecord(batch: UUID(), item: item, size: 16, source: "Editor", tool: "applications")])++ let read = try #require(await RemovalLog(url: log.url).load().records?.first)++ #expect(read.identity != nil)+ #expect(read.identity == item.identity)+ #expect(read.isStillInTrash)++ let older = try JSONDecoder().decode(RemovalRecord.self, from: Data("""+ {"id":"\(UUID())","batch":"\(UUID())","originalURL":"file:///Users/x/Documents/report.pdf",+ "trashedURL":"\(trashed.absoluteString)","date":788918400,"size":16,"source":"Editor","tool":"applications"}+ """.utf8))+ #expect(older.identity == nil)+ #expect(older.isStillInTrash, "a record without an identity is judged by name, as before")+ }+/// A time read from a log is written back as it was read, since every change writes the whole log again: a/// time that lost a millisecond each time could move behind a part that moved after it.@Test func aTimeReadBackIsWrittenAsItWas() throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swiftindex ee6fa152..e3961ba1 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift@@ -221,6 +221,47 @@ struct TrashServiceTests {#expect(await service.restore(planted) == .notAllowed)}+ /// Once the Trash is emptied, another item of the same name can land where an old record's item was. It is not+ /// that item: History no longer counts the old record as in the Trash, and Put Back leaves the new one where it is.+ @Test func anItemLandingLaterWhereAnotherWasIsNotTakenForIt() async throws {+ let directory = try TemporaryDirectory()+ let first = try directory.file("home/Projects/One/node_modules/left-pad/index.js")+ .deletingLastPathComponent().deletingLastPathComponent()+ let second = try directory.file("home/Projects/Two/node_modules/is-odd/index.js")+ .deletingLastPathComponent().deletingLastPathComponent()+ let service = try service(in: directory)+ let moved = try #require(await service.trash([first]).trashed.first)+ let record = RemovalRecord(batch: UUID(), item: moved, size: 10, source: "One", tool: "projects")++ // The Trash is emptied, and the next project's folder of the same name lands in the same place.+ try FileManager.default.moveItem(at: moved.trashedURL, to: directory.url.appending(path: "emptied"))+ let movedLater = try #require(await service.trash([second]).trashed.first)+ #expect(movedLater.trashedURL == moved.trashedURL, "the second folder did not land where the first had")++ #expect(!record.isStillInTrash)+ #expect(await service.restore(record.trashedItem) == .missingFromTrash)+ #expect(!FileManager.default.fileExists(atPath: first.path(percentEncoded: false)), "the other project's folder was put back here")+ #expect(FileManager.default.fileExists(atPath: movedLater.trashedURL.path(percentEncoded: false)))+ }++ /// Put Back asks again, of the item it holds open, whether it is the one that moved: another item could take its+ /// place between the look and the move.+ @Test func putBackLeavesAnotherItemInThePlaceItHolds() throws {+ let directory = try TemporaryDirectory()+ let original = directory.url.appending(path: "home/Projects/One/node_modules")+ try FileManager.default.createDirectory(at: original.deletingLastPathComponent(), withIntermediateDirectories: true)+ let first = try directory.directory("home/.Trash/node_modules")+ let identity = try #require(TrashedItem.Identity(ofItemAt: first))+ try FileManager.default.moveItem(at: first, to: directory.url.appending(path: "emptied"))+ try directory.directory("home/.Trash/node_modules")+ let item = TrashedItem(originalURL: original, trashedURL: first, date: .now, identity: identity)++ #expect(throws: TrashService.NotTheItemThatMoved.self) {+ try TrashService.putBack(item) { _ in true }+ }+ #expect(!FileManager.default.fileExists(atPath: original.path(percentEncoded: false)))+ }+/// Records come from a file any process can rewrite, so Put Back checks the folder an item really sits in./// A folder that is only called `.Trash` can be a link into Messages, or sit inside iCloud Drive.@Test func putsNothingBackFromAFolderThatIsOnlyCalledTrash() async throws {diff --git a/SAFETY.md b/SAFETY.mdindex 5271bb4f..dec5f797 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -130,7 +130,9 @@ back. The `peel` command says so and moves nothing either.The record is also a file any process running as you can rewrite, so Put Back reads it as a request, not asa fact. It only takes something that really sits in a Trash of yours (`~/.Trash`, or `.Trashes/<uid>` at theroot of another disk), asked of the folder itself with every link resolved: a folder that is merely called-`.Trash`, a link into Messages, or iCloud Drive's own Trash, is refused.+`.Trash`, a link into Messages, or iCloud Drive's own Trash, is refused. And it takes only the very item that+went: History keeps which item it was (its inode and when it was made), so once the Trash is emptied, another+item that lands in the same place, another project's `node_modules`, say, is never put back in its stead.## What is selected for you