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
Moving to the Trash and back works on exFAT disks
Țugui Dragoș826d88b60cde
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex bda854e3..d966fecf 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -102,11 +102,12 @@ Take the most common case, uninstalling an app. Every other page follows the samA handful of ideas carry most of the weight. Each is enforced in one place and tested there.-- **The Trash, never deletion.** Nothing in Peel deletes anything of the user's; the one file it deletes outright is- its own list of refusals, when `peel history --refused --clear` is asked to forget it. Three actions can't be- undone by History, and each says so where it is confirmed: Homebrew's own uninstall and clean up, and resetting- an app's privacy permissions. Forgetting a preference domain happens only once its file is in the Trash, so- putting the file back undoes it. Every `brew` call runs without Homebrew's automatic cleanup+- **The Trash, never deletion.** Nothing in Peel deletes anything of the user's; what it deletes outright is its own:+ its list of refusals, when `peel history --refused --clear` is asked to forget it, and the empty placeholder+ `TrashMover` makes to hold a name on a disk that cannot rename without replacing (exFAT), when the move it was made+ for fails. Three actions can't be undone by History, and each says so where it is confirmed: Homebrew's own uninstall+ and clean up, and resetting an app's privacy permissions. Forgetting a preference domain happens only once its file is+ in the Trash, so putting the file back undoes it. Every `brew` call runs without Homebrew's automatic cleanup(`HOMEBREW_NO_INSTALL_CLEANUP`), so an upgrade never deletes on its own.- **One guard.** `RemovalGuard` decides, for the app and the `peel` tool alike, whether an item may move. Itslist of what nothing can bring back lives in `ProtectedData`, in PeelPrivileged, so the helper applies thediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b5aabb46..77fc4974 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -11,13 +11,14 @@ from happening, and they are not up for negotiation.**Nothing of the user's is ever deleted for good.** Every removal goes to the Trash through `TrashService` and isrecorded, so History can put it back; in the app it runs inside `QuitGuard.shared.run` from its first move until Historyhas it, and so does a Put Back, so that quitting waits for them. No code path in Peel deletes anything of the user's,-and a change that adds one won't be accepted; the one file Peel deletes outright is its own list of refusals, when-`peel history --refused --clear` is asked to forget it. Three things Peel starts can't be undone by History, and each-says so where the user confirms it: Homebrew's own uninstall and clean up, and resetting an app's privacy permissions.-`defaults delete` for an app's preferences runs only once their file is in the Trash, and a reset exports the domain-first, so putting the file back undoes it; putting saved settings back clears a domain only once it has been saved as a-copy of its own, and asks first. Every `brew` call runs with `HOMEBREW_NO_INSTALL_CLEANUP`, so an upgrade never cleans-up on its own.+and a change that adds one won't be accepted. What Peel deletes outright is its own: its list of refusals, when+`peel history --refused --clear` is asked to forget it, and the empty placeholder `TrashMover` makes to hold a name on a+disk that cannot rename without replacing (exFAT), when the move it was made for fails. Three things Peel starts can't+be undone by History, and each says so where the user confirms it: Homebrew's own uninstall and clean up, and resetting+an app's privacy permissions. `defaults delete` for an app's preferences runs only once their file is in the Trash, and+a reset exports the domain first, so putting the file back undoes it; putting saved settings back clears a domain only+once it has been saved as a copy of its own, and asks first. Every `brew` call runs with `HOMEBREW_NO_INSTALL_CLEANUP`,+so an upgrade never cleans up on its own.## What you needdiff --git a/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift b/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swiftindex d9e21143..d57499e4 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift@@ -6,6 +6,10 @@ public enum TrashMover {/// is taken, it adds " 2", " 3", and so on, as Finder does. It never copies across volumes and never/// resolves a path a second time.public static func move(_ item: OpenItem, into trash: DirectoryHandle) -> Result<String, POSIXError> {+ move(item, into: trash, exclusively: renameExclusively)+ }++ static func move(_ item: OpenItem, into trash: DirectoryHandle, exclusively: ExclusiveRename) -> Result<String, POSIXError> {let base = (item.name as NSString).deletingPathExtensionlet pathExtension = (item.name as NSString).pathExtension@@ -16,7 +20,7 @@ public enum TrashMover {} else {candidate = pathExtension.isEmpty ? "\(base) \(attempt)" : "\(base) \(attempt).\(pathExtension)"}- switch rename(item, to: candidate, in: trash) {+ switch rename(item, to: candidate, in: trash, exclusively: exclusively) {case .success:return .success((trash.path as NSString).appendingPathComponent(candidate))case .failure(let error):@@ -28,6 +32,74 @@ public enum TrashMover {/// Renames `item` to `name` in `directory` through both descriptors, refusing to replace anything there.public static func rename(_ item: OpenItem, to name: String, in directory: DirectoryHandle) -> Result<Void, POSIXError> {+ rename(item, to: name, in: directory, exclusively: renameExclusively)+ }++ /// A rename that refuses to replace what is at the new name. A test stands in for a file system without one.+ typealias ExclusiveRename = (OpenItem, String, DirectoryHandle) -> Result<Void, POSIXError>++ /// A file system that cannot refuse to replace by itself answers `ENOTSUP` (rename(2)), as exFAT does for a free+ /// name. There the name is first taken with an empty placeholder of the item's kind, which only a free name+ /// allows, and a plain rename then replaces the placeholder.+ static func rename(_ item: OpenItem, to name: String, in directory: DirectoryHandle, exclusively: ExclusiveRename) -> Result<Void, POSIXError> {+ switch exclusively(item, name, directory) {+ case .failure(let error) where error.code == .ENOTSUP:+ return renameOntoPlaceholder(item, to: name, in: directory)+ case let result:+ return result+ }+ }++ private static func renameOntoPlaceholder(_ item: OpenItem, to name: String, in directory: DirectoryHandle) -> Result<Void, POSIXError> {+ var info = stat()+ guard item.name.withCString({ fstatat(item.parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0 else { return .failure(.last) }+ let isFolder = info.st_mode & S_IFMT == S_IFDIR+ let placeholder: ItemIdentity+ switch makePlaceholder(named: name, in: directory, isFolder: isFolder) {+ case .success(let made): placeholder = made+ case .failure(let error): return .failure(error)+ }+ let moved = item.name.withCString { from in+ name.withCString { to in renameat(item.parent.descriptor, from, directory.descriptor, to) }+ }+ guard moved == 0 else {+ let error = POSIXError.last+ removePlaceholder(placeholder, named: name, in: directory, isFolder: isFolder)+ return .failure(error)+ }+ return .success(())+ }++ /// Makes an empty folder, or an empty file for anything else, at `name`, failing with `EEXIST` when it is taken.+ private static func makePlaceholder(named name: String, in directory: DirectoryHandle, isFolder: Bool) -> Result<ItemIdentity, POSIXError> {+ var info = stat()+ if isFolder {+ guard name.withCString({ mkdirat(directory.descriptor, $0, 0o700) }) == 0 else { return .failure(.last) }+ guard name.withCString({ fstatat(directory.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0 else {+ let error = POSIXError.last+ _ = name.withCString { unlinkat(directory.descriptor, $0, AT_REMOVEDIR) }+ return .failure(error)+ }+ } else {+ let file = name.withCString { openat(directory.descriptor, $0, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, 0o600) }+ guard file >= 0 else { return .failure(.last) }+ defer { close(file) }+ guard fstat(file, &info) == 0 else { return .failure(.last) }+ }+ return .success(ItemIdentity(info))+ }++ /// Takes away the placeholder a failed rename left, only while it is still the one made for it.+ private static func removePlaceholder(_ placeholder: ItemIdentity, named name: String, in directory: DirectoryHandle, isFolder: Bool) {+ var info = stat()+ guard+ name.withCString({ fstatat(directory.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0,+ ItemIdentity(info) == placeholder+ else { return }+ _ = name.withCString { unlinkat(directory.descriptor, $0, isFolder ? AT_REMOVEDIR : 0) }+ }++ private static func renameExclusively(_ item: OpenItem, to name: String, in directory: DirectoryHandle) -> Result<Void, POSIXError> {let moved = item.name.withCString { from inname.withCString { to inrenameatx_np(item.parent.descriptor, from, directory.descriptor, to, UInt32(RENAME_EXCL))diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashMoverTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashMoverTests.swiftnew file mode 100644index 00000000..bb978f1d--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashMoverTests.swift@@ -0,0 +1,102 @@+import Darwin+import Foundation+@testable import PeelCore+@testable import PeelPrivileged+import Testing++/// Moves into the Trash, and back out of it, never replace what is already at the new name. exFAT cannot refuse to+/// replace by itself: `RENAME_EXCL` answers `ENOTSUP` there for a free name and `EEXIST` for a taken one, and these+/// tests stand in for it.+struct TrashMoverTests {+ private func likeExFAT(_ item: OpenItem, _ name: String, _ directory: DirectoryHandle) -> Result<Void, POSIXError> {+ var info = stat()+ let isTaken = name.withCString { fstatat(directory.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) } == 0+ return .failure(POSIXError(isTaken ? .EEXIST : .ENOTSUP))+ }++ private func contents(of url: URL) throws -> [String] {+ try FileManager.default.contentsOfDirectory(atPath: url.path(percentEncoded: false)).sorted()+ }++ @Test func aFileMovesWhereTheDiskCannotRefuseToReplace() throws {+ let directory = try TemporaryDirectory()+ let file = try directory.file("folder/notes.txt", contents: Data("mine".utf8))+ let trash = try directory.directory("Trash")+ let item = try OpenItem.at(file.path(percentEncoded: false)).get()++ let landed = try TrashMover.move(item, into: try DirectoryHandle.at(trash.path(percentEncoded: false)).get(), exclusively: likeExFAT).get()++ #expect(URL(filePath: landed).lastPathComponent == "notes.txt")+ #expect(try String(contentsOfFile: landed, encoding: .utf8) == "mine")+ #expect(!file.isThere)+ #expect(try contents(of: trash) == ["notes.txt"])+ }++ @Test func whatIsAlreadyThereIsNeverReplaced() throws {+ let directory = try TemporaryDirectory()+ let file = try directory.file("folder/notes.txt", contents: Data("mine".utf8))+ let earlier = try directory.file("Trash/notes.txt", contents: Data("in the Trash already".utf8))+ let item = try OpenItem.at(file.path(percentEncoded: false)).get()++ let trash = try DirectoryHandle.at(earlier.deletingLastPathComponent().path(percentEncoded: false)).get()+ let landed = try TrashMover.move(item, into: trash, exclusively: likeExFAT).get()++ #expect(URL(filePath: landed).lastPathComponent == "notes 2.txt")+ #expect(try String(contentsOf: earlier, encoding: .utf8) == "in the Trash already")+ #expect(try String(contentsOfFile: landed, encoding: .utf8) == "mine")+ }++ @Test func aFolderMovesWithEverythingInIt() throws {+ let directory = try TemporaryDirectory()+ try directory.file("folder/Project/one.txt", contents: Data("1".utf8))+ try directory.file("folder/Project/deeper/two.txt", contents: Data("2".utf8))+ let trash = try directory.directory("Trash")+ let item = try OpenItem.at(directory.url.appending(path: "folder/Project").path(percentEncoded: false)).get()++ let landed = URL(filePath: try TrashMover.move(item, into: try DirectoryHandle.at(trash.path(percentEncoded: false)).get(), exclusively: likeExFAT).get())++ #expect(try String(contentsOf: landed.appending(path: "one.txt"), encoding: .utf8) == "1")+ #expect(try String(contentsOf: landed.appending(path: "deeper/two.txt"), encoding: .utf8) == "2")+ #expect(try contents(of: trash) == ["Project"])+ }++ /// A move that fails once the new name is taken for it gives the name back, so neither the Trash nor the place an+ /// item was being put back to is left holding an empty stand-in.+ @Test func aMoveThatFailsLeavesNothingBehind() throws {+ let directory = try TemporaryDirectory()+ let file = try directory.file("locked/notes.txt")+ let folder = try directory.directory("Project/inside")+ let trash = try directory.directory("Trash")+ let item = try OpenItem.at(file.path(percentEncoded: false)).get()+ let folderItem = try OpenItem.at(folder.path(percentEncoded: false)).get()+ try directory.setPermissions(0o555, of: "locked")+ try directory.setPermissions(0o555, of: "Project")+ defer {+ try? directory.setPermissions(0o755, of: "locked")+ try? directory.setPermissions(0o755, of: "Project")+ }++ let bin = try DirectoryHandle.at(trash.path(percentEncoded: false)).get()+ #expect(throws: POSIXError.self) { try TrashMover.move(item, into: bin, exclusively: likeExFAT).get() }+ #expect(throws: POSIXError.self) { try TrashMover.move(folderItem, into: bin, exclusively: likeExFAT).get() }+ #expect(try contents(of: trash).isEmpty)+ #expect(file.isThere && folder.isThere)+ }++ @Test func putBackNeverReplacesWhatCameBackInTheMeantime() throws {+ let directory = try TemporaryDirectory()+ let trashed = try directory.file("Trash/notes.txt", contents: Data("from the Trash".utf8))+ let place = try directory.directory("folder")+ let item = try OpenItem.at(trashed.path(percentEncoded: false)).get()+ let folder = try DirectoryHandle.at(place.path(percentEncoded: false)).get()++ try TrashMover.rename(item, to: "notes.txt", in: folder, exclusively: likeExFAT).get()+ #expect(try String(contentsOf: place.appending(path: "notes.txt"), encoding: .utf8) == "from the Trash")++ let another = try directory.file("Trash/other.txt", contents: Data("another".utf8))+ let second = try OpenItem.at(another.path(percentEncoded: false)).get()+ #expect(throws: POSIXError(.EEXIST)) { try TrashMover.rename(second, to: "notes.txt", in: folder, exclusively: likeExFAT).get() }+ #expect(try String(contentsOf: place.appending(path: "notes.txt"), encoding: .utf8) == "from the Trash")+ #expect(another.isThere)+ }+}diff --git a/SAFETY.md b/SAFETY.mdindex 50741eb6..ec35a8b4 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -116,8 +116,12 @@ and each item is written down the moment it moves, so one cut short by a crash oHistory, as an interrupted removal, the next time Peel or `peel` opens it. The space is freed when *you* emptythe Trash: Peel never does that for you.-The one file Peel deletes outright is its own list of refusals, and only when `peel history --refused --clear` is-asked to forget it.+A move to the Trash, or back from it, never replaces what is already at the new name. Most disks refuse that by+themselves; on one that cannot, such as exFAT, Peel first takes the name with an empty placeholder, which only a+free name allows, and the move then replaces the placeholder.++What Peel deletes outright is only its own: its list of refusals, when `peel history --refused --clear` is asked to+forget it, and such a placeholder, when the move it was made for fails.Three things Peel starts can't be undone by History, and Peel says so before you confirm each of them: Homebrew'sown uninstall and Clean Up, which delete what they remove, and resetting an app's privacy permissions, which is off