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.

Watch the Trash also sees apps thrown away from other disks

Țugui Dragoșcb9bb97cc1cd
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index ea4626a9..59c10a1d 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -169,9 +169,10 @@ macOS asks the user to approve it once. It talks to the app over XPC.
languages. The key is the English, so changing a sentence means translating it again; the tests fail until
every language has it. PeelCore never translates: it returns plain English, and the app turns known
sentences into the reader's language (`FixedSentence`).
-- **Watching the Trash.** `TrashMonitor` notices an app the user moves to the Trash. `TrashService` tells it
- about Peel's own moves (`OwnTrashMoves`), by where each item landed, so Peel never offers to clean up after
- itself.
+- **Watching the Trash.** `TrashMonitor` notices an app the user moves to the Trash: the home's, and the Trash of
+ each other disk Peel lists apps on (`VolumeTrashes`), where an app thrown away from that disk lands. `TrashService`
+ tells it about Peel's own moves (`OwnTrashMoves`), by where each item landed, so Peel never offers to clean up
+ after itself.
## The `peel` tool
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/OwnTrashMoves.swift b/Packages/PeelCore/Sources/PeelCore/Removal/OwnTrashMoves.swift
index 6939bccc..e785460b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/OwnTrashMoves.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/OwnTrashMoves.swift
@@ -1,4 +1,5 @@
public import Foundation
+internal import PeelPrivileged
import Synchronization
/// Peel's own moves to the Trash, so a watch on the Trash can tell them from the user's. `TrashService`, which
@@ -57,8 +58,9 @@ public final class OwnTrashMoves: Sendable {
guard state.underWay == 0 else { return nil }
let folder = PathPattern.comparablePath(of: trash)
let arrived = names.subtracting(known).sorted().filter { state.landed[folder + "/" + $0] == nil }
- // What landed before the listing began has been seen by it, or has left the Trash since.
- state.landed = state.landed.filter { $0.value > look }
+ // What landed in this Trash before the listing began has been seen by it, or has left since. Another
+ // Trash keeps what landed there until it is listed itself.
+ state.landed = state.landed.filter { $0.value > look || !PathComponents.isPath($0.key, inside: folder) }
return arrived
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/VolumeTrashes.swift b/Packages/PeelCore/Sources/PeelCore/Removal/VolumeTrashes.swift
new file mode 100644
index 00000000..015acdde
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/VolumeTrashes.swift
@@ -0,0 +1,22 @@
+import Darwin
+public import Foundation
+
+/// The Trash an app thrown away from a disk other than the home's lands in: macOS keeps one for each account at the
+/// top of each volume, `.Trashes/<uid>`, and makes it the first time something there goes to the Trash.
+public enum VolumeTrashes {
+ /// The Trash of each volume that holds one of `apps`, other than the home's, whose apps land in `~/.Trash`.
+ public static func folders(forAppsAt apps: [URL], home: URL = .homeDirectory) -> [URL] {
+ let homeVolume = volume(of: home)
+ var folders: [URL] = []
+ for app in apps {
+ guard let volume = volume(of: app), volume != homeVolume else { continue }
+ let trash = volume.appending(path: ".Trashes/\(getuid())", directoryHint: .isDirectory)
+ if !folders.contains(trash) { folders.append(trash) }
+ }
+ return folders
+ }
+
+ private static func volume(of url: URL) -> URL? {
+ (try? url.resourceValues(forKeys: [.volumeURLKey]))?.volume?.standardizedFileURL
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OwnTrashMovesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OwnTrashMovesTests.swift
index 2ce282fb..cf502a51 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/OwnTrashMovesTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/OwnTrashMovesTests.swift
@@ -60,6 +60,18 @@ struct OwnTrashMovesTests {
#expect(moves.arrivals(["Foo.app"], known: [], in: trash, since: moves.look()) == ["Foo.app"])
}
+ /// Each Trash is looked at on its own, so a look at one keeps what landed in another until that one is seen.
+ @Test func aLookAtOneTrashKeepsWhatLandedInAnother() {
+ let moves = OwnTrashMoves()
+ let volume = URL(filePath: "/Volumes/Disk/.Trashes/501", directoryHint: .isDirectory)
+ moves.began()
+ moves.ended(landedAt: [volume.appending(path: "Foo.app")])
+
+ #expect(moves.arrivals([], known: [], in: trash, since: moves.look()) == [])
+ let arrived = moves.arrivals(["Foo.app"], known: [], in: volume, since: moves.look())
+ #expect(arrived == [], "Peel's own app was told")
+ }
+
/// A listing that began before Peel's move landed may not show what it landed, so what landed after the
/// look began is kept for the next one.
@Test func keepsWhatLandedAfterTheLookBegan() {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/VolumeTrashesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/VolumeTrashesTests.swift
new file mode 100644
index 00000000..b953a63c
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/VolumeTrashesTests.swift
@@ -0,0 +1,21 @@
+import Darwin
+import Foundation
+@testable import PeelCore
+import Testing
+
+struct VolumeTrashesTests {
+ /// An app thrown away from another disk lands in that disk's own Trash, so that is where the watch looks. An
+ /// app on the home's disk lands in the home's Trash, which is watched already.
+ @Test func watchesTheTrashOfEachOtherDiskAnAppIsOn() throws {
+ let directory = try TemporaryDirectory()
+ let disk = try ScratchVolume(fileSystem: "APFS", mountedAt: directory.url.appending(path: "Disk"))
+ let app = disk.url.appending(path: "Applications/Example.app", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: app, withIntermediateDirectories: true)
+ let calculator = URL(filePath: "/System/Applications/Calculator.app", directoryHint: .isDirectory)
+
+ let folders = VolumeTrashes.folders(forAppsAt: [app, calculator, app], home: .homeDirectory)
+
+ let trash = disk.url.appending(path: ".Trashes/\(getuid())", directoryHint: .isDirectory)
+ #expect(folders.map(PathPattern.comparablePath) == [PathPattern.comparablePath(of: trash)])
+ }
+}
diff --git a/Peel/Model/TrashMonitor.swift b/Peel/Model/TrashMonitor.swift
index 47cdb86c..9525fada 100644
--- a/Peel/Model/TrashMonitor.swift
+++ b/Peel/Model/TrashMonitor.swift
@@ -3,6 +3,8 @@ import Foundation
import Observation
import PeelCore
+/// Watches the Trash for apps the user moves there: the home's Trash, and the Trash of each other disk Peel lists
+/// apps on, where an app thrown away from that disk lands.
@Observable
final class TrashMonitor {
enum Status {
@@ -11,54 +13,175 @@ final class TrashMonitor {
case needsFullDiskAccess
}
+ /// The home Trash's watch, the one macOS keeps behind Full Disk Access.
private(set) var status = Status.off
var onApplicationTrashed: ((URL) -> Void)?
+ @ObservationIgnored private var home: TrashWatch?
+ @ObservationIgnored private var volumeTrashes: [URL] = []
+ /// A disk's Trash is watched from the first time Peel lists an app on the disk until the disk goes away, so an
+ /// app thrown away from it is seen even when it was the last one there.
+ @ObservationIgnored private var volumes: [URL: TrashWatch] = [:]
+
+ func start() {
+ guard home == nil else { return }
+ let trash = URL.homeDirectory.appending(path: ".Trash", directoryHint: .isDirectory)
+ let watch = TrashWatch(trash: trash, waitsForTheTrash: false) { [weak self] in self?.onApplicationTrashed?($0) }
+ switch watch.start() {
+ case .watching:
+ home = watch
+ status = .watching
+ case .refused:
+ status = .needsFullDiskAccess
+ return
+ case .unavailable:
+ status = .off
+ return
+ }
+ watch.onRestart = { [weak self] result in
+ guard result != .watching else { return }
+ self?.stop()
+ self?.status = result == .refused ? .needsFullDiskAccess : .off
+ }
+ // The setting is about apps the user moves to the Trash, so Peel's own moves are told apart, and every
+ // Trash is looked at again once one ends.
+ OwnTrashMoves.shared.whenSettled { [weak self] in
+ Task { @MainActor in
+ self?.home?.changed()
+ self?.volumes.values.forEach { $0.changed() }
+ }
+ }
+ startVolumes()
+ }
+
+ func stop() {
+ home?.stop()
+ home = nil
+ volumes.values.forEach { $0.stop() }
+ volumes = [:]
+ status = .off
+ }
+
+ /// Follows the apps Peel lists: each disk other than the home's that holds one has a Trash of its own.
+ func follow(appsAt apps: [URL]) {
+ volumeTrashes = VolumeTrashes.folders(forAppsAt: apps)
+ guard home != nil else { return }
+ startVolumes()
+ }
+
+ private func startVolumes() {
+ for trash in volumeTrashes {
+ if let watch = volumes[trash], watch.isActive {
+ // A Trash can appear inside `.Trashes`, which cannot be opened, so no event says when it does.
+ // The list of apps changing, as it does when one leaves its folder, is when to look again.
+ watch.lookForTheTrash()
+ } else {
+ let watch = TrashWatch(trash: trash, waitsForTheTrash: true) { [weak self] in
+ self?.onApplicationTrashed?($0)
+ }
+ _ = watch.start()
+ volumes[trash] = watch
+ }
+ }
+ }
+}
+
+/// One Trash folder, watched for apps arriving. A disk's Trash appears only once something there first goes to
+/// the Trash, so until then the top of the disk is watched, where `.Trashes` appears.
+@MainActor
+private final class TrashWatch {
+ enum Start {
+ case watching
+ /// macOS refused to let Peel look, which for the home's Trash means Full Disk Access is missing.
+ case refused
+ case unavailable
+ }
+
+ let trash: URL
+ private let waitsForTheTrash: Bool
+ private let onArrived: (URL) -> Void
+ /// Told what came of starting again after the folder watched went away.
+ var onRestart: ((Start) -> Void)?
private var source: (any DispatchSourceFileSystemObject)?
- private var knownApplications: Set<String> = []
+ private var isWaitingForTheTrash = false
+ private var known: Set<String> = []
/// One listing at a time, and one more when events arrived while it ran: the Trash can hold thousands of
/// items, and the event comes in on the main queue.
private var isListing = false
private var needsAnotherLook = false
- private var trashURL: URL {
- .homeDirectory.appending(path: ".Trash", directoryHint: .isDirectory)
+ var isActive: Bool { source != nil }
+
+ init(trash: URL, waitsForTheTrash: Bool, onArrived: @escaping (URL) -> Void) {
+ self.trash = trash
+ self.waitsForTheTrash = waitsForTheTrash
+ self.onArrived = onArrived
}
- func start() {
- guard source == nil else { return }
- let descriptor = open(trashURL.path(percentEncoded: false), O_EVTONLY)
+ /// `appeared` is true for a Trash that appeared while it was waited for: whatever is in it came with it.
+ func start(appeared: Bool = false) -> Start {
+ guard source == nil else { return .watching }
+ let descriptor = open(trash.path(percentEncoded: false), O_EVTONLY)
let failure = errno
- guard descriptor >= 0, let applications = applicationsInTrash() else {
+ if descriptor < 0, failure == ENOENT, waitsForTheTrash {
+ return waitForTheTrash()
+ }
+ guard descriptor >= 0, let applications = Self.names(in: trash) else {
if descriptor >= 0 { close(descriptor) }
// Only a refusal from macOS means Full Disk Access is missing. No Trash yet, or no descriptors left,
// leaves the watch off instead.
- status = descriptor >= 0 || [EPERM, EACCES].contains(failure) ? .needsFullDiskAccess : .off
- return
+ return descriptor >= 0 || [EPERM, EACCES].contains(failure) ? .refused : .unavailable
}
- knownApplications = applications
- // The setting is about apps the user moves to the Trash, so Peel's own moves are told apart, and the
- // Trash is looked at again once one ends.
- OwnTrashMoves.shared.whenSettled { [weak self] in
- Task { @MainActor in self?.trashChanged() }
+ known = appeared ? [] : applications
+ watch(descriptor)
+ if appeared {
+ changed()
}
+ return .watching
+ }
+
+ func stop() {
+ source?.cancel()
+ source = nil
+ isWaitingForTheTrash = false
+ }
+
+ /// Looks again for a Trash that was waited for.
+ func lookForTheTrash() {
+ guard isWaitingForTheTrash else { return }
+ stop()
+ _ = start(appeared: true)
+ }
- // Watches for delete and rename too: a Trash folder that is removed and made again is another folder,
- // and the descriptor would keep following the old one, so no event would arrive while the status
- // still read `watching`.
+ private func waitForTheTrash() -> Start {
+ let volume = trash.deletingLastPathComponent().deletingLastPathComponent()
+ let descriptor = open(volume.path(percentEncoded: false), O_EVTONLY)
+ guard descriptor >= 0 else { return .unavailable }
+ watch(descriptor)
+ isWaitingForTheTrash = true
+ return .watching
+ }
+
+ // Watches for delete and rename too: a folder that is removed and made again is another folder, and the
+ // descriptor would keep following the old one. A disk that goes away revokes it.
+ private func watch(_ descriptor: Int32) {
let source = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: descriptor,
- eventMask: [.write, .delete, .rename],
+ eventMask: [.write, .delete, .rename, .revoke],
queue: .main
)
source.setEventHandler { [weak self] in
MainActor.assumeIsolated {
- guard let self else { return }
- if self.source?.data.contains(.write) == true {
- self.trashChanged()
- }
- if self.source?.data.isDisjoint(with: [.delete, .rename]) == false {
- self.restart()
+ guard let self, let events = self.source?.data else { return }
+ if events.contains(.revoke) {
+ self.stop()
+ } else if self.isWaitingForTheTrash {
+ self.lookForTheTrash()
+ } else if !events.isDisjoint(with: [.delete, .rename]) {
+ self.stop()
+ self.onRestart?(self.start())
+ } else if events.contains(.write) {
+ self.changed()
}
}
}
@@ -67,58 +190,41 @@ final class TrashMonitor {
}
source.resume()
self.source = source
- status = .watching
- }
-
- /// The folder it was watching is gone, so the watch starts again on whatever is there now.
- private func restart() {
- stop()
- start()
- }
-
- func stop() {
- source?.cancel()
- source = nil
- status = .off
}
- private func trashChanged() {
- // The end of one of Peel's own moves asks too, and it may come after the watch was turned off.
- guard status == .watching else { return }
+ func changed() {
+ // The end of one of Peel's own moves asks too, and it may come after the watch ended.
+ guard source != nil, !isWaitingForTheTrash else { return }
guard !isListing else {
needsAnotherLook = true
return
}
isListing = true
- Task { [trashURL] in
+ Task { [trash, known] in
defer {
isListing = false
if needsAnotherLook {
needsAnotherLook = false
- trashChanged()
+ changed()
}
}
let look = OwnTrashMoves.shared.look()
guard
- let applications = await Self.applications(in: trashURL),
+ let applications = await Self.applications(in: trash),
// Nil while Peel is moving something itself: the end of that move looks again.
- let arrived = OwnTrashMoves.shared.arrivals(applications, known: knownApplications, in: trashURL, since: look)
+ let arrived = OwnTrashMoves.shared.arrivals(applications, known: known, in: trash, since: look)
else { return }
- knownApplications = applications
- // What Peel put there, from this process or from `peel` in Terminal, is no app the person threw away.
+ self.known = applications
+ // What Peel put there, from this process or from `peel` in Terminal, is no app the user threw away.
let placedByPeel = arrived.isEmpty ? [] : await RemovalLog().placesInTheTrash()
for name in arrived {
- let url = trashURL.appending(path: name, directoryHint: .isDirectory)
+ let url = trash.appending(path: name, directoryHint: .isDirectory)
guard !placedByPeel.contains(PathPattern.comparablePath(of: url)) else { continue }
- onApplicationTrashed?(url)
+ onArrived(url)
}
}
}
- private func applicationsInTrash() -> Set<String>? {
- Self.names(in: trashURL)
- }
-
/// Lists the apps in the Trash off the main actor, for events. The first listing, which decides whether
/// the watch can start at all, runs directly in `start()`.
@concurrent
diff --git a/Peel/PeelApp.swift b/Peel/PeelApp.swift
index 4e0924b6..97c1cb68 100644
--- a/Peel/PeelApp.swift
+++ b/Peel/PeelApp.swift
@@ -95,6 +95,13 @@ struct PeelApp: App {
))
}
+ /// Tells the Trash watch where the listed apps are, so it watches the Trash of each other disk they are on.
+ private func followAppsForTheTrash() async {
+ for await _ in Observations({ library.revision }) {
+ trashMonitor.follow(appsAt: library.apps.map(\.url))
+ }
+ }
+
/// Keeps the app list current as apps are installed and removed while Peel is open, and as folders are added to
/// or removed from the ones it looks in.
private func followFolders() async {
@@ -341,7 +348,10 @@ struct PeelApp: App {
// Started once, and not as a child of this view's task, so the work goes on in the menu bar
// after the window closes.
Navigator.shared.openWindow = openWindow
- background.start([followFolders, askWhenDue, followFindings, followActivations, watchFreeSpace])
+ background.start([
+ followFolders, followAppsForTheTrash, askWhenDue, followFindings, followActivations,
+ watchFreeSpace,
+ ])
textEditing.start()
}
}