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
Nothing moves from under a program that still has files open in it
Țugui Dragoș35257630a0a5
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 668bb1d3..c1bbf215 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -30907,6 +30907,112 @@}}},+ "Files in it are still open in %@, so Peel left it where it is." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Soubory v ní jsou stále otevřené (%@), proto ji Peel nechal na místě."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Dateien darin sind noch in %@ geöffnet, daher hat Peel es an seinem Ort belassen."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Contiene archivos que siguen abiertos en %@, así que Peel lo ha dejado donde está."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Des fichiers qu’il contient sont encore ouverts par %@ : Peel l’a donc laissé en place."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Contiene file ancora aperti in %@, quindi Peel l’ha lasciato dov’è."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "中のファイルが%@でまだ開かれているため、Peelはそのままにしました。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "이 항목 안의 파일이 아직 %@에서 열려 있어서 Peel이 그대로 두었습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Bestanden erin zijn nog geopend in %@, dus Peel heeft het laten staan waar het is."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Pliki wewnątrz są nadal otwarte przez: %@, więc Peel zostawił to na miejscu."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Há arquivos dentro dele que ainda estão abertos em %@, por isso o Peel o deixou onde está."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Unele fișiere din acest articol sunt încă deschise în %@, așa că Peel l‑a lăsat unde se află."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Файлы в этом объекте все еще открыты в %@, поэтому Peel оставил его на месте."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Filer i det är fortfarande öppna i %@, så Peel lät det ligga kvar där det är."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "İçindeki dosyalar hâlâ %@ tarafından açık tutuluyor, bu yüzden Peel onu yerinde bıraktı."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Файли цього елемента досі відкриті в %@, тож Peel залишила його на місці."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "其中有文件仍在“%@”中打开,因此Peel将它留在了原处。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "其中有檔案仍在「%@」中打開,因此Peel將它留在原處。"+ }+ }+ }+ },"Files named with an app’s identifier that no installed app claims will appear here." : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swiftindex 989ef5e0..8a206456 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift@@ -335,6 +335,8 @@ extension TrashFailure.Reason {case .movedWithoutATrace: "in the Trash where macOS didn't say, so only Finder can put it back"case .somethingElseMoved(let name): "something else was at that path; it is in the Trash as \(Output.plain(name))"case .historyUnreadable: "History can't be read"+ case .heldOpen(let processes):+ "files in it are still open in \(processes.map(Output.plain).joined(separator: ", "))"case .failed(let message): Output.plain(message)}}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swiftnew file mode 100644index 00000000..906ccfe5--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift@@ -0,0 +1,55 @@+import Darwin+import Foundation+internal import PeelPrivileged++/// The files other processes hold open, read from every process this account may look at (`proc_pidinfo(2)`): an+/// app's agent, a tool's daemon, a server. Another account's processes, and macOS's own that run as root, stay unseen.+struct OpenFiles {+ private let files: [(names: [String], process: String)]++ /// Each regular file held open for reading or writing. A watch (`O_EVTONLY`, as Finder keeps on what it shows)+ /// and a folder are no hold on what is inside.+ init(excluding excluded: pid_t? = getpid()) {+ var pids = [pid_t](repeating: 0, count: 8_192)+ let count = Int(proc_listallpids(&pids, Int32(pids.count * MemoryLayout<pid_t>.size)))+ var files: [(names: [String], process: String)] = []+ for pid in pids.prefix(max(count, 0)) where pid > 0 && pid != excluded {+ let paths = Self.paths(openBy: pid)+ guard !paths.isEmpty else { continue }+ let process = Self.name(of: pid)+ files += paths.map { (PathComponents.of($0), process) }+ }+ self.files = files+ }++ func holders(of url: URL) -> [String] {+ let names = PathComponents.of(PathPattern.canonical(url).path(percentEncoded: false))+ return Set(files.filter { $0.names.starts(with: names) }.map(\.process)).sorted()+ }++ private static func paths(openBy pid: pid_t) -> [String] {+ let size = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, nil, 0)+ guard size > 0 else { return [] }+ var descriptors = [proc_fdinfo](repeating: proc_fdinfo(), count: Int(size) / MemoryLayout<proc_fdinfo>.size)+ let filled = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &descriptors, size)+ guard filled > 0 else { return [] }+ return descriptors.prefix(Int(filled) / MemoryLayout<proc_fdinfo>.size).compactMap { descriptor in+ guard descriptor.proc_fdtype == PROX_FDTYPE_VNODE else { return nil }+ var info = vnode_fdinfowithpath()+ let expected = Int32(MemoryLayout<vnode_fdinfowithpath>.size)+ guard proc_pidfdinfo(pid, descriptor.proc_fd, PROC_PIDFDVNODEPATHINFO, &info, expected) == expected,+ info.pfi.fi_openflags & UInt32(O_EVTONLY) == 0,+ mode_t(info.pvip.vip_vi.vi_stat.vst_mode) & S_IFMT == S_IFREG+ else { return nil }+ return withUnsafeBytes(of: info.pvip.vip_path) { bytes in+ String(decoding: bytes.prefix { $0 != 0 }, as: UTF8.self)+ }+ }+ }++ private static func name(of pid: pid_t) -> String {+ var buffer = [CChar](repeating: 0, count: 2 * Int(MAXCOMLEN) + 1)+ guard proc_name(pid, &buffer, UInt32(buffer.count)) > 0 else { return "process \(pid)" }+ return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex 73970186..1763cd82 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -75,6 +75,8 @@ public struct TrashFailure: Sendable, Hashable {case somethingElseMoved(named: String)/// History cannot be read, so nothing moves: what moved could not be listed for Put Back.case historyUnreadable+ /// These processes hold a file open in it, and moving it would pull it from under them.+ case heldOpen(by: [String])case failed(String)}@@ -101,6 +103,7 @@ extension TrashFailure.Reason {case .movedWithoutATrace: "moved-without-a-trace"case .somethingElseMoved: "something-else-moved"case .historyUnreadable: "history-unreadable"+ case .heldOpen: "held-open"case .failed: "failed"}}@@ -109,6 +112,7 @@ extension TrashFailure.Reason {switch self {case .failed(let message): messagecase .somethingElseMoved(let name): name+ case .heldOpen(let processes): processes.joined(separator: "\n")default: nil}}@@ -125,6 +129,7 @@ extension TrashFailure.Reason {case "moved-without-a-trace": self = .movedWithoutATracecase "something-else-moved": self = .somethingElseMoved(named: detail ?? "")case "history-unreadable": self = .historyUnreadable+ case "held-open": self = .heldOpen(by: (detail ?? "").split(separator: "\n").map(String.init))case "failed": self = .failed(detail ?? "")default: return nil}@@ -264,6 +269,7 @@ public struct TrashService: Sendable {// The guard reads the disk, so it is asked once for each item.let allowed = urls.filter(removalGuard.allowsRemoval(of:))let isAllowed = Set(allowed)+ let openFiles = OpenFiles()// Read before the move, while the files are still there to say which jobs they declare.let jobs = LaunchdCleanup.jobs(for: allowed, environment: environment)@@ -278,6 +284,11 @@ public struct TrashService: Sendable {// An item inside a folder that just moved went with it: it is neither moved again nor a failure.let path = PathPattern.comparablePath(of: url)guard !moved.contains(where: { PathComponents.isPath(path, inside: $0) }) else { continue }+ let holders = openFiles.holders(of: url)+ guard holders.isEmpty else {+ result.failures.append(TrashFailure(url: url, reason: .heldOpen(by: holders)))+ continue+ }do {let trashedURL = try moveToTrash(url)let item = TrashedItem(originalURL: url, trashedURL: trashedURL, date: .now, identity: .init(ofItemAt: trashedURL))@@ -310,9 +321,17 @@ public struct TrashService: Sendable {// An item inside another folder of this request goes with that folder. Sent on its own, the helper would// find it gone and report a failure.let paths = permitted.map(PathPattern.comparablePath)- let allowed = permitted.filter { url in+ let openFiles = OpenFiles()+ var allowed: [URL] = []+ for url in permitted {let path = PathPattern.comparablePath(of: url)- return !paths.contains { PathComponents.isPath(path, inside: $0) }+ guard !paths.contains(where: { PathComponents.isPath(path, inside: $0) }) else { continue }+ let holders = openFiles.holders(of: url)+ guard holders.isEmpty else {+ result.failures.append(TrashFailure(url: url, reason: .heldOpen(by: holders)))+ continue+ }+ allowed.append(url)}let jobs = LaunchdCleanup.jobs(for: allowed, environment: environment)// A command-line tool's link leads into its app until the app has moved, and the helper takes such a linkdiff --git a/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swiftnew file mode 100644index 00000000..741001d1--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/OpenFilesTests.swift@@ -0,0 +1,38 @@+import Darwin+import Foundation+@testable import PeelCore+import Testing++struct OpenFilesTests {+ @Test func seesAFileHeldOpenInsideAFolder() throws {+ let directory = try TemporaryDirectory()+ let file = try directory.file("Cache/inner/store.db")+ let handle = try FileHandle(forReadingFrom: file)+ defer { try? handle.close() }++ let folder = directory.url.appending(path: "Cache", directoryHint: .isDirectory)+ #expect(!OpenFiles(excluding: nil).holders(of: folder).isEmpty)+ #expect(!OpenFiles(excluding: nil).holders(of: file).isEmpty)+ #expect(OpenFiles(excluding: nil).holders(of: directory.url.appending(path: "Other")).isEmpty)+ }++ @Test func aWatchOrAnOpenFolderHoldsNothing() throws {+ let directory = try TemporaryDirectory()+ let file = try directory.file("Cache/store.db")+ let folder = file.deletingLastPathComponent()+ let watch = open(file.path(percentEncoded: false), O_EVTONLY)+ let opened = open(folder.path(percentEncoded: false), O_RDONLY)+ defer { close(watch); close(opened) }+ #expect(watch >= 0 && opened >= 0)++ #expect(OpenFiles(excluding: nil).holders(of: folder).isEmpty)+ }++ @Test func leavesOutItsOwnProcess() throws {+ let directory = try TemporaryDirectory()+ let handle = try FileHandle(forReadingFrom: try directory.file("Cache/store.db"))+ defer { try? handle.close() }++ #expect(OpenFiles().holders(of: directory.url.appending(path: "Cache")).isEmpty)+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swiftindex 2450b5f6..028c5838 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift@@ -150,7 +150,8 @@ struct RefusalLogTests {private static let everyReason: [TrashFailure.Reason] = [.protectedLocation, .changedSinceScan, .claimedSinceScan, .lastCopy, .notPermitted, .needsHelper,- .movedWithoutATrace, .somethingElseMoved(named: "x 2"), .historyUnreadable, .failed("x"),+ .movedWithoutATrace, .somethingElseMoved(named: "x 2"), .historyUnreadable,+ .heldOpen(by: ["Figma Agent", "java"]), .failed("x"),]/// A record stores its reason as a word, not a sentence, so a later version of Peel can still read it.@@ -159,7 +160,7 @@ struct RefusalLogTests {#expect(Set(reasons.map(\.name)).count == reasons.count)#expect(reasons.allSatisfy { !$0.name.contains(" ") })- #expect(reasons.filter { $0.detail != nil }.count == 2)+ #expect(reasons.filter { $0.detail != nil }.count == 3)}/// History words a refusal from the reason it stored, so every word leads back to its reason, and a word adiff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swiftindex 16192baf..7871299e 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift@@ -600,6 +600,30 @@ struct TrashServiceTests {#expect(FileManager.default.fileExists(atPath: home.appending(path: "Library/Caches").path(percentEncoded: false)))}+ @Test func leavesAFolderAnotherProcessHoldsAFileOpenIn() async throws {+ let directory = try TemporaryDirectory()+ let service = try service(in: directory)+ let file = try directory.file("home/Library/Caches/org.example.agent/store.db")+ let folder = file.deletingLastPathComponent()+ let holder = Process()+ holder.executableURL = URL(filePath: "/bin/sleep")+ holder.arguments = ["30"]+ holder.standardInput = try FileHandle(forReadingFrom: file)+ try holder.run()+ defer { holder.terminate() }++ let held = await service.trash([folder])++ #expect(held.trashed.isEmpty)+ #expect(held.failures.map(\.reason) == [.heldOpen(by: ["sleep"])])+ #expect(FileManager.default.fileExists(atPath: folder.path(percentEncoded: false)))++ holder.terminate()+ holder.waitUntilExit()+ let free = await service.trash([folder])+ #expect(free.trashed.map(\.originalURL) == [folder])+ }+/// `/var`, `/tmp`, and `/etc` are symbolic links into `/private`. A guard that knew only one spelling could/// be bypassed by writing the other.@Test func refusesTheSystemsRootsHoweverTheyAreSpelled() throws {diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swiftindex 7b24c407..27421563 100644--- a/Peel/Views/Presentation.swift+++ b/Peel/Views/Presentation.swift@@ -116,6 +116,8 @@ extension TrashFailure.Reason {case .movedWithoutATrace: String(localized: "It is in the Trash, but macOS didn’t say where, so it can only be put back from Finder.")case .somethingElseMoved(let name): String(localized: "Something else was at that path by the time it moved. It is in the Trash as \(name), and Finder can put it back.")case .historyUnreadable: String(localized: "Peel couldn’t read History, and it moves nothing it can’t put back.")+ case .heldOpen(let processes):+ String(localized: "Files in it are still open in \(processes.formatted(.list(type: .and))), so Peel left it where it is.")case .failed(let message): FixedSentence.translated(message)}}diff --git a/SAFETY.md b/SAFETY.mdindex efd6e3d4..efa76e35 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -116,6 +116,11 @@ 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.+Right before anything moves, Peel looks at the files other programs of yours hold open, and leaves where it is any+file or folder with one of them inside, naming the program: moving a database or a cache from under an agent, a+daemon, or a server that is using it would break it. Programs that run as another account or as root, macOS's own+among them, cannot be seen this way, which is why Space also leaves macOS's own caches unselected.+A move to the Trash, or back from it, never replaces what is already at the new name. Most disks refuse that bythemselves; on one that cannot, such as exFAT, Peel first takes the name with an empty placeholder, which only afree name allows, and the move then replaces the placeholder.