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
Start again a launch job that Put Back brings back
Țugui Dragoș5e26c8130d62
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swiftindex 44b0d904..fd8bcf74 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift@@ -19,6 +19,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {/// A key for a source Peel names itself (a tool, a Space area, a kind of installer, or a count of apps), so/// History can show it in the user's language. `source` then holds the English name, which `peel` prints.public let sourceKey: String?+ public let stoppedJob: String?public init(id: UUID = UUID(),@@ -39,6 +40,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {self.source = sourceself.sourceKey = sourceKeyself.tool = tool+ stoppedJob = item.stoppedJob}/// Reads a negative size as zero, since any process of the user can rewrite the History file.@@ -54,10 +56,13 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {source = try container.decode(String.self, forKey: .source)tool = try container.decode(String.self, forKey: .tool)sourceKey = try container.decodeIfPresent(String.self, forKey: .sourceKey)+ stoppedJob = try container.decodeIfPresent(String.self, forKey: .stoppedJob)}public var trashedItem: TrashedItem {- TrashedItem(originalURL: originalURL, trashedURL: trashedURL, date: date, identity: identity)+ TrashedItem(+ originalURL: originalURL, trashedURL: trashedURL, date: date, identity: identity, stoppedJob: stoppedJob+ )}public var isStillInTrash: Bool {diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swiftindex c53cf90f..b27a3dd7 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift@@ -9,17 +9,30 @@ enum LaunchdCleanup {let plist: URL}- /// Stops jobs whose configuration has gone, so launchd doesn't keep them running or restart them.+ /// Stops jobs whose configuration has gone, so launchd doesn't keep them running or restart them, and answers+ /// those it stopped: a job launchd did not have is not one.@concurrent- static func stop(_ jobs: [Job], canUseHelper: Bool) async {+ static func stop(_ jobs: [Job], canUseHelper: Bool) async -> [Job] {+ var stopped: [Job] = []for job in jobs {if job.isDaemon {guard canUseHelper, PrivilegedHelper.status == .enabled else { continue }- _ = await PrivilegedHelper.runDaemonCommand(.bootout, label: job.label)- } else {- _ = await Launchctl.run(["bootout", "gui/\(getuid())/\(job.label)"])+ if await PrivilegedHelper.runDaemonCommand(.bootout, label: job.label) == nil { stopped.append(job) }+ } else if await Launchctl.run(["bootout", "gui/\(getuid())/\(job.label)"]).status == 0 {+ stopped.append(job)}}+ return stopped+ }++ @concurrent+ static func start(_ job: Job, canUseHelper: Bool) async {+ if job.isDaemon {+ guard canUseHelper, PrivilegedHelper.status == .enabled else { return }+ _ = await PrivilegedHelper.runDaemonCommand(.bootstrap, label: job.label)+ } else {+ _ = await Launchctl.run(["bootstrap", "gui/\(getuid())", job.plist.path(percentEncoded: false)])+ }}/// The jobs these plists declare. launchd knows a job by the `Label` inside its file, and the file name doesdiff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex c1db6918..1a0af0ee 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -8,6 +8,8 @@ public struct TrashedItem: Sendable, Hashable, Codable {/// 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?+ /// The launchd job Peel stopped once this file moved, by its label, which putting the file back starts again.+ public internal(set) var stoppedJob: String?/// 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.@@ -27,11 +29,12 @@ public struct TrashedItem: Sendable, Hashable, Codable {}}- init(originalURL: URL, trashedURL: URL, date: Date, identity: Identity? = nil) {+ init(originalURL: URL, trashedURL: URL, date: Date, identity: Identity? = nil, stoppedJob: String? = nil) {self.originalURL = originalURLself.trashedURL = trashedURLself.date = dateself.identity = identity+ self.stoppedJob = stoppedJob}/// Where the item stands now, as the disk says.@@ -171,10 +174,21 @@ public struct TrashResult: Sendable {self.trashed = trashedself.failures = failures}++ /// Marks each item whose move stopped the job it declares.+ mutating func note(_ stopped: [LaunchdCleanup.Job]) {+ for job in stopped {+ for index in trashed.indices where trashed[index].originalURL == job.plist {+ trashed[index].stoppedJob = job.label+ }+ }+ }}public struct TrashService: Sendable {- typealias StopJobs = @Sendable ([LaunchdCleanup.Job], _ canUseHelper: Bool) async -> Void+ /// Answers the jobs it stopped.+ typealias StopJobs = @Sendable ([LaunchdCleanup.Job], _ canUseHelper: Bool) async -> [LaunchdCleanup.Job]+ typealias StartJob = @Sendable (LaunchdCleanup.Job, _ canUseHelper: Bool) async -> Voidtypealias ForgetDomains = @Sendable ([URL], _ owner: String?) async -> Voidtypealias MoveThroughHelper = @Sendable ([URL]) async -> TrashResulttypealias PutBackDockTiles = @Sendable (URL) async -> Void@@ -182,6 +196,7 @@ public struct TrashService: Sendable {let environment: SearchEnvironmentprivate let removalGuard: RemovalGuardprivate let stopJobs: StopJobs+ private let startJob: StartJobprivate let forgetDomains: ForgetDomainsprivate let moveThroughHelper: MoveThroughHelperprivate let putBackDockTiles: PutBackDockTiles@@ -196,6 +211,7 @@ public struct TrashService: Sendable {environment: environment,removalGuard: removalGuard,stopJobs: LaunchdCleanup.stop,+ startJob: LaunchdCleanup.start,forgetDomains: { await PreferenceCleanup.forgetDomains(for: $0, ownedBy: $1) },moveThroughHelper: Self.moveThroughTheHelper,putBackDockTiles: { await DockTiles().putBack($0) },@@ -205,12 +221,13 @@ public struct TrashService: Sendable {)}- /// For tests. Unless a test passes its own, it stops no launchd job, forgets no preference domain, acts as if- /// there were no helper, changes no Dock, and writes no journal.+ /// For tests. Unless a test passes its own, it stops and starts no launchd job, forgets no preference domain, acts+ /// as if there were no helper, changes no Dock, and writes no journal.init(environment: SearchEnvironment,exclusions: Exclusions = .none,- stopJobs: @escaping StopJobs = { _, _ in },+ stopJobs: @escaping StopJobs = { _, _ in [] },+ startJob: @escaping StartJob = { _, _ in },forgetDomains: @escaping ForgetDomains = { _, _ in },moveThroughHelper: @escaping MoveThroughHelper = Self.asIfThereWereNoHelper,putBackDockTiles: @escaping PutBackDockTiles = { _ in },@@ -222,6 +239,7 @@ public struct TrashService: Sendable {environment: environment,removalGuard: RemovalGuard(environment: environment, exclusions: exclusions),stopJobs: stopJobs,+ startJob: startJob,forgetDomains: forgetDomains,moveThroughHelper: moveThroughHelper,putBackDockTiles: putBackDockTiles,@@ -235,6 +253,7 @@ public struct TrashService: Sendable {environment: SearchEnvironment,removalGuard: RemovalGuard,stopJobs: @escaping StopJobs,+ startJob: @escaping StartJob,forgetDomains: @escaping ForgetDomains,moveThroughHelper: @escaping MoveThroughHelper,putBackDockTiles: @escaping PutBackDockTiles,@@ -245,6 +264,7 @@ public struct TrashService: Sendable {self.environment = environmentself.removalGuard = removalGuardself.stopJobs = stopJobs+ self.startJob = startJobself.forgetDomains = forgetDomainsself.moveThroughHelper = moveThroughHelperself.putBackDockTiles = putBackDockTiles@@ -360,7 +380,7 @@ public struct TrashService: Sendable {}}ownMoves.ended(landedAt: result.trashed.map(\.trashedURL))- await finish(result, stopping: jobs, canUseHelper: false, owner: owner)+ result.note(await finish(result, stopping: jobs, canUseHelper: false, owner: owner))return result}@@ -449,22 +469,23 @@ public struct TrashService: Sendable {ownMoves.ended(landedAt: helperResult.trashed.map(\.trashedURL))result.trashed += helperResult.trashedresult.failures += helperResult.failures- await finish(helperResult, stopping: jobs, canUseHelper: true, owner: nil)+ result.note(await finish(helperResult, stopping: jobs, canUseHelper: true, owner: nil))return result}- /// Stops the jobs and forgets the preference domains of what really moved. It runs after the move: a job- /// stopped before a move that fails would stay stopped with its file in place, and cfprefsd would forget- /// settings that are still on disk.+ /// Stops the jobs and forgets the preference domains of what really moved, and answers the jobs it stopped. It+ /// runs after the move: a job stopped before a move that fails would stay stopped with its file in place, and+ /// cfprefsd would forget settings that are still on disk.private func finish(_ result: TrashResult,stopping jobs: [LaunchdCleanup.Job],canUseHelper: Bool,owner: String?- ) async {+ ) async -> [LaunchdCleanup.Job] {let moved = result.trashed.map(\.originalURL)- await stopJobs(jobs.filter { moved.contains($0.plist) }, canUseHelper)+ let stopped = await stopJobs(jobs.filter { moved.contains($0.plist) }, canUseHelper)await forgetDomains(moved, owner)+ return stopped}/// Moves `urls` through the helper. When the helper is not enabled, nothing moves and every item fails with@@ -485,6 +506,13 @@ public struct TrashService: Sendable {let failure = await moveBack(item, canUseHelper: canUseHelper)if failure == nil {await putBackDockTiles(item.originalURL)+ // The label comes from History, which any process of the user can rewrite, so the job starts only as the+ // file now back in place declares it.+ if let label = item.stoppedJob,+ let job = LaunchdCleanup.jobs(for: [item.originalURL], environment: environment).first,+ job.label == label {+ await startJob(job, canUseHelper)+ }}return failure}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swiftindex e20861b3..6ef1d977 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift@@ -41,8 +41,9 @@ struct TrashServiceTests {private actor Stopped {private(set) var labels: [String] = []- func record(_ jobs: [LaunchdCleanup.Job]) {+ func record(_ jobs: [LaunchdCleanup.Job]) -> [LaunchdCleanup.Job] {labels += jobs.map(\.label)+ return jobs}}@@ -161,6 +162,7 @@ struct TrashServiceTests {#expect(result.trashed.map(\.originalURL) == [moved])#expect(await stopped.labels == ["com.example.moved"])+ #expect(result.trashed.map(\.stoppedJob) == ["com.example.moved"])}/// An item that needs the helper but was not selected stays in place, and its job keeps running.@@ -176,9 +178,63 @@ struct TrashServiceTests {#expect(result.trashed.map(\.originalURL) == [selected])#expect(await stopped.labels == ["com.example.selected"])+ #expect(result.trashed.map(\.stoppedJob) == ["com.example.selected"])#expect(FileManager.default.fileExists(atPath: unselected.path(percentEncoded: false)))}+ @Test func puttingBackTheFileOfAJobPeelStoppedStartsItAgain() async throws {+ let directory = try TemporaryDirectory()+ let trash = try directory.directory("home/.Trash")+ let running = try launchdPlist("home/Library/LaunchAgents/org.example.running.plist", in: directory)+ let idle = try launchdPlist("home/Library/LaunchAgents/org.example.idle.plist", in: directory)+ let started = Mutex<[String]>([])+ let service = TrashService(+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ ),+ stopJobs: { jobs, _ in jobs.filter { $0.label == "org.example.running" } },+ startJob: { job, _ in started.withLock { $0.append(job.label) } },+ moveToTrash: { url in+ let destination = trash.appending(path: url.lastPathComponent)+ try FileManager.default.moveItem(at: url, to: destination)+ return destination+ }+ )++ let result = await service.trash([running, idle])+ #expect(started.withLock { $0 }.isEmpty)+ for item in result.trashed {+ let record = RemovalRecord(batch: UUID(), item: item, size: nil, source: "Example", tool: "test")+ let read = try JSONDecoder().decode(RemovalRecord.self, from: JSONEncoder().encode(record))+ #expect(await service.restore(read.trashedItem) == nil)+ }++ #expect(started.withLock { $0 } == ["org.example.running"], "the job Peel stopped was not started again")+ #expect(running.isThere && idle.isThere)+ }++ @Test func aJobIsStartedAgainOnlyAsTheFilePutBackDeclaresIt() async throws {+ let directory = try TemporaryDirectory()+ let trash = try directory.directory("home/.Trash")+ let plist = try launchdPlist("home/Library/LaunchAgents/org.example.agent.plist", in: directory)+ let trashed = trash.appending(path: plist.lastPathComponent)+ try FileManager.default.moveItem(at: plist, to: trashed)+ let started = Mutex<[String]>([])+ let service = TrashService(+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home"),+ rootDirectory: directory.url.appending(path: "root")+ ),+ startJob: { job, _ in started.withLock { $0.append(job.label) } },+ moveToTrash: { $0 }+ )++ let edited = TrashedItem(originalURL: plist, trashedURL: trashed, date: .now, stoppedJob: "org.example.other")+ #expect(await service.restore(edited) == nil)+ #expect(started.withLock { $0 }.isEmpty, "a label History named, and the file does not declare, was started")+ }+/// The guard and the exclusions decide before any job is stopped. What they keep is never moved, so its job/// is never stopped either.@Test func leavesTheJobOfAnExcludedItemRunning() async throws {diff --git a/SAFETY.md b/SAFETY.mdindex b9addfc5..c2137afb 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -85,9 +85,9 @@ behalf, and never for the global domain under any of its names.The other two follow what really moved too. launchd is told to stop the jobs whose files went(`launchctl bootout`), or it would keep them running and start them again; putting a file back from History-lets launchd load its job again at the next login, or at the next restart for a daemon. And an uninstalled-app's icon is taken out of the Dock, unless you deselect it, which restarts the Dock; putting the app back-puts its icon back where it was.+starts again the job Peel stopped, as the file back in place declares it (a daemon through the helper), and a job+that was not running stays as it was. And an uninstalled app's icon is taken out of the Dock, unless you deselect+it, which restarts the Dock; putting the app back puts its icon back where it was.**The check is not a string comparison.** A disk is case-insensitive unless you went out of your way, so`~/Library/mobile documents` is the same folder as `~/Library/Mobile Documents`; `/var` and `/private/var`@@ -188,7 +188,7 @@ Some of what Peel does is not a move to the Trash. Each is here with how it is u| What Peel changes | How it is undone || --- | --- || A preference domain is forgotten (`defaults delete`) once its file is in the Trash | Putting the file back from History, as described above |-| A launch job is stopped (`launchctl bootout`) once its file is in the Trash | Putting the file back from History; launchd loads the job again at the next login, or at the next restart for a daemon |+| A launch job is stopped (`launchctl bootout`) once its file is in the Trash | Putting the file back from History, which starts the job again (`launchctl bootstrap`, a daemon through the helper) || An uninstalled app's icon is taken out of the Dock, which restarts the Dock | Putting the app back from History puts its icon back where it was || An app's privacy permissions are reset, only when you choose it | Can't be undone: the app asks again for each permission || Homebrew uninstalls a package or cleans up its downloads | Can't be undone: Homebrew deletes what it removes |