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.

Put an edited agent's old file back by moving the edit aside first

Țugui Dragoșbe86884a7cff
diff --git a/GUIDE.md b/GUIDE.md
index e6c728e1..ab48817e 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -290,9 +290,10 @@ and how many items the others hold.
is gone, or whose command looks unusual, says so. Remove takes out a job a deleted app left loaded,
and an item whose app is in the Trash says that macOS starts it from there each time you log in, until you empty
the Trash. A job an app gave launchd itself, such as an update's installer, says so. Edit… beside an agent's file in
- your own `~/Library/LaunchAgents` opens the file as text: Save moves the file as it was to the Trash, where History
- can put it back, writes yours in its place, and loads the job again if it was loaded. Apps set to open at login are
- in System Settings > General > Login Items & Extensions, not here.
+ your own `~/Library/LaunchAgents` opens the file as text: Save moves the file as it was to the Trash, writes yours
+ in its place, and loads the job again if it was loaded, and putting the old file back from History moves your edit
+ to the Trash first. Apps set to open at login are in System Settings > General > Login Items & Extensions, not
+ here.
- **Extensions:** app extensions and system extensions, the app each one came with and whether it is still installed,
the choice made for each one, or that macOS decides when nobody chose, which keeps a Finder extension off, and where
it is turned on or off: System Settings for most, Safari > Settings > Extensions for a Safari extension, which Safari
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 7769d09d..1e729922 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -200193,6 +200193,112 @@
}
}
},
+ "The edit in its place couldn’t move to the Trash first, so nothing changed." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Úpravu, která je teď na jeho místě, se nejdřív nepodařilo přesunout do koše, takže se nic nezměnilo."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Die bearbeitete Fassung, die an seiner Stelle liegt, konnte nicht zuerst in den Papierkorb gelegt werden, daher wurde nichts geändert."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "No se ha podido trasladar primero a la papelera la versión editada que ocupa su lugar, así que no ha cambiado nada."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Impossible de placer d’abord dans la corbeille la version modifiée qui se trouve à sa place : rien n’a donc changé."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Non è stato possibile spostare prima nel Cestino la versione modificata che si trova al suo posto, quindi non è cambiato nulla."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "その場所にある編集版を先にゴミ箱に入れられなかったため、何も変更されていません。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "현재 그 자리에 있는 편집본을 먼저 휴지통으로 이동할 수 없어 아무것도 변경되지 않았습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "De versie die nu op de plek ervan staat, kon niet eerst naar de prullenmand worden verplaatst, dus er is niets gewijzigd."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nie udało się najpierw przenieść do Kosza wersji, która jest teraz na miejscu tej rzeczy, więc nic się nie zmieniło."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Não foi possível mover primeiro para o Lixo a edição que agora está no lugar do item, então nada mudou."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Versiunea editată aflată în locul său nu a putut fi mutată mai întâi în Coș, așa că nu s‑a schimbat nimic."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Отредактированную версию, которая сейчас находится на его месте, не удалось сначала переместить в Корзину, поэтому ничего не изменилось."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Versionen som nu ligger på dess plats kunde inte flyttas till papperskorgen först, så ingenting ändrades."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Yerinde duran düzenlenmiş hâli önce Çöp Sepeti’ne taşınamadı, bu yüzden hiçbir şey değişmedi."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Не вдалося спершу перемістити в Смітник відредагований варіант, який на його місці, тому нічого не змінено."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未能先将位于原位置的编辑后的版本移到废纸篓,因此没有任何更改。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "目前位於原處的編輯版本無法先丟到「垃圾桶」,因此沒有任何變更。"
+ }
+ }
+ }
+ },
"The extra section at the end goes away." : {
"localizations" : {
"cs" : {
@@ -233919,6 +234025,112 @@
}
}
},
+ "Your edit of it stands in its place, so Put Back moves that edit to the Trash first, where History keeps it." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Na jeho místě je teď vaše úprava, takže ji tlačítko Vrátit zpět nejdřív přesune do koše, kde ji Historie uchová."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "An seiner Stelle liegt deine bearbeitete Fassung, daher legt „Zurücklegen“ diese zuerst in den Papierkorb, und der Verlauf behält sie."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tu versión editada ocupa su lugar, así que “Restaurar” traslada primero esa versión editada a la papelera, donde Historial la conserva."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Votre version modifiée de cet élément se trouve à sa place : « Remettre » commence donc par placer cette version modifiée dans la corbeille, où l’Historique la conserve."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Al suo posto c’è la tua versione modificata dell’elemento, quindi “Ripristina” sposta prima quella nel Cestino, dove la Cronologia la conserva."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "その場所には編集版があるため、“戻す”は先にその編集版をゴミ箱に入れます。その編集版も履歴に残ります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "현재 그 자리에 이 항목의 편집본이 있으므로, ‘되돌려 놓기’는 먼저 그 편집본을 휴지통으로 이동하며, 이동한 편집본은 기록에 보관됩니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Op de plek ervan staat nu een andere versie, dus 'Zet terug' verplaatst die eerst naar de prullenmand, waar Geschiedenis die bewaart."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Na miejscu tej rzeczy jest teraz inna jej wersja, więc przycisk Przywróć najpierw przeniesie tę wersję do Kosza, gdzie Historia ją zachowa."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "A sua edição do item está agora no lugar dele, então o comando Colocar de Volta primeiro move essa edição para o Lixo, onde o Histórico a mantém."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "În locul său se află acum versiunea editată de dvs., așa că butonul Puneți înapoi o mută mai întâi pe aceasta în Coș, unde Istoricul o păstrează."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Сейчас на его месте находится отредактированная Вами версия, поэтому кнопка «Восстановить» сначала переместит ее в Корзину, где ее сохранит История."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "En annan version av det ligger nu på dess plats, så ”Lägg tillbaka” flyttar först den versionen till papperskorgen, där Historik behåller den."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Yerinde, sizin düzenlediğiniz hâli duruyor, bu yüzden Yerine Koy, önce o düzenlenmiş hâli Çöp Sepeti’ne taşır; Geçmiş onu da orada tutar."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "На його місці стоїть ваш відредагований варіант, тому «Повернути назад» спершу переміщує цей варіант у Смітник, де його зберігає Історія."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "位于原位置的是你编辑后的版本,因此“放回原处”会先将那个编辑后的版本移到废纸篓,“历史记录”会保留它。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "它的原處現在是你的編輯版本,因此「還原」會先將該編輯版本丟到「垃圾桶」,並由「歷史記錄」保留。"
+ }
+ }
+ }
+ },
"Your exclusions couldn’t be saved" : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
index ec860cff..ef1e01a5 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
@@ -401,6 +401,9 @@ struct RestoreCommand: AsyncParsableCommand {
for (record, failure) in refused {
Output.note("\(Output.plain(Output.path(record.originalURL))) stays: \(failure.summary)")
}
+ for record in going where record.trashedItem.editStandsInItsPlace {
+ Output.note("\(Output.plain(Output.path(record.originalURL))): the edit in its place goes to the Trash first, and History keeps it.")
+ }
guard !going.isEmpty else {
Output.line("Nothing of that removal can be put back from here.")
@@ -425,14 +428,23 @@ struct RestoreCommand: AsyncParsableCommand {
let ordered = going.inPutBackOrder
// `peel` never uses the helper: items that need administrator access are left for the Peel app.
let answers = await service.restore(ordered.map(\.trashedItem), canUseHelper: false)
- for (record, answer) in zip(ordered, answers) {
+ for (record, answer) in zip(ordered, answers.failures) {
if let failure = answer {
failures.append((record, failure))
} else {
restored.insert(record.id)
}
}
- return (restored, failures, await log.remove(restored).records != nil)
+ // An edit that made room goes into History under the same part, so it can come back too.
+ var aside: [RemovalRecord] = []
+ for (record, edit) in zip(ordered, answers.movedAside) {
+ guard let edit else { continue }
+ let size = await FileSize.reclaimableSize(of: edit.trashedURL)
+ let sizes = size.map { [edit.originalURL: $0] } ?? [:]
+ aside += record.part.records(of: TrashResult(trashed: [edit]), sizes: sizes, batch: UUID())
+ }
+ let kept = aside.isEmpty ? true : await log.add(aside).records != nil
+ return (restored, failures, await log.remove(restored).records != nil && kept)
}
Output.line("Put \(Output.count(restored.count, "item", "items")) back.")
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
index 1b8d492a..e5536704 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
@@ -277,6 +277,7 @@ extension RestoreFailure {
"macOS lets your terminal app put back another developer's app only with App Management; allow it in System Settings > Privacy & Security > App Management, or put it back with the Peel app"
case .notPermitted: "macOS didn't allow it"
case .failed(let message): Output.plain(message)
+ case .editStays(let reason): "the edit in its place couldn't move to the Trash first (\(reason.summary))"
}
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/LaunchAgentFile.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/LaunchAgentFile.swift
index 14c5c78e..c50d9d3d 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/LaunchAgentFile.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/LaunchAgentFile.swift
@@ -146,7 +146,7 @@ public struct LaunchAgentFile: Sendable {
}
},
start: { item throws(BackgroundItemActions.Failure) in try await BackgroundItemActions.start(item) },
- putBack: { await trash.restore([$0]).first ?? nil }
+ putBack: { await trash.restore([$0]).failures.first ?? nil }
)
}
@@ -175,26 +175,27 @@ public struct LaunchAgentFile: Sendable {
let problem = moved.result.failures.first.map { Problem.notMoved($0.reason) } ?? .changed
return .unchanged(problem, moved: moved.result)
}
+ var result = moved.result
switch makeFile(url, Data(text.utf8), mode) {
case .written:
- break
+ result.trashed[0].replacedBy = TrashedItem.Identity(ofItemAt: url)
case .notMade(let error):
guard await putBack(old) != nil else { return .unchanged(.notWritten(error), moved: TrashResult()) }
return .oldFileInTheTrash(.notWritten(error), moved: moved.result)
case .incomplete(let error):
return .oldFileInTheTrash(.incomplete(error), moved: moved.result)
}
- guard item.state != .notLoaded, item.state != .unknown else { return .saved(moved: moved.result, reload: nil) }
+ guard item.state != .notLoaded, item.state != .unknown else { return .saved(moved: result, reload: nil) }
if let stillRunning = moved.stillRunning {
- return .saved(moved: moved.result, reload: .notStopped(stillRunning))
+ return .saved(moved: result, reload: .notStopped(stillRunning))
}
var stopped = item
stopped.state = .notLoaded
do throws(BackgroundItemActions.Failure) {
try await start(stopped)
- return .saved(moved: moved.result, reload: nil)
+ return .saved(moved: result, reload: nil)
} catch {
- return .saved(moved: moved.result, reload: .notStarted(error))
+ return .saved(moved: result, reload: .notStarted(error))
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
index 6d308847..d779c5aa 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
@@ -22,6 +22,8 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {
/// 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?
+ /// The file an edit wrote in the item's place, which a Put Back moves to the Trash first.
+ public let replacedBy: TrashedItem.Identity?
/// True when the item shared most of its storage with another copy, so moving it freed only its own part.
public let sharedStorage: Bool?
@@ -48,6 +50,7 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {
self.sourceKey = sourceKey
self.tool = tool
stoppedJob = item.stoppedJob
+ replacedBy = item.replacedBy
self.sharedStorage = sharedStorage
}
@@ -66,12 +69,14 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {
tool = try container.decode(String.self, forKey: .tool)
sourceKey = try container.decodeIfPresent(String.self, forKey: .sourceKey)
stoppedJob = try container.decodeIfPresent(String.self, forKey: .stoppedJob)
+ replacedBy = try container.decodeIfPresent(TrashedItem.Identity.self, forKey: .replacedBy)
sharedStorage = try container.decodeIfPresent(Bool.self, forKey: .sharedStorage)
}
public var trashedItem: TrashedItem {
TrashedItem(
- originalURL: originalURL, trashedURL: trashedURL, date: date, identity: identity, stoppedJob: stoppedJob
+ originalURL: originalURL, trashedURL: trashedURL, date: date, identity: identity, stoppedJob: stoppedJob,
+ replacedBy: replacedBy
)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
index c20590f9..00d0071b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
@@ -11,6 +11,8 @@ public struct TrashedItem: Sendable, Hashable, Codable {
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?
+ /// The file an edit of this one wrote in its place, which a Put Back moves to the Trash before this goes back.
+ public internal(set) var replacedBy: 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.
@@ -30,12 +32,22 @@ public struct TrashedItem: Sendable, Hashable, Codable {
}
}
- init(originalURL: URL, trashedURL: URL, date: Date, identity: Identity? = nil, stoppedJob: String? = nil) {
+ init(
+ originalURL: URL, trashedURL: URL, date: Date, identity: Identity? = nil, stoppedJob: String? = nil,
+ replacedBy: Identity? = nil
+ ) {
self.originalURL = originalURL
self.trashedURL = trashedURL
self.date = date
self.identity = identity
self.stoppedJob = stoppedJob
+ self.replacedBy = replacedBy
+ }
+
+ /// True while the file an edit of this one wrote stands in its place, never a link taken for it.
+ public var editStandsInItsPlace: Bool {
+ guard let replacedBy else { return false }
+ return Identity(ofItemAt: originalURL) == replacedBy
}
/// Where the item stands now, as the disk says.
@@ -242,13 +254,15 @@ public enum RestoreFailure: Sendable, Hashable {
/// macOS's privacy protection refused it.
case notPermitted
case failed(String)
+ /// The file an edit of it wrote in its place couldn't move to the Trash first, for this reason.
+ case editStays(TrashFailure.Reason)
/// True when asking again can't help: the item left the Trash, or Peel puts nothing back from or to there.
public var isFinal: Bool {
switch self {
case .missingFromTrash, .notAllowed, .notAllowedByTheHelper, .notInATrash: true
case .alreadyThere, .needsHelper, .locked, .folderLocked, .folderGone, .needsAppManagement, .notPermitted,
- .failed:
+ .failed, .editStays:
false
}
}
@@ -788,44 +802,75 @@ public struct TrashService: Sendable {
TrashResult(failures: urls.map { TrashFailure(url: $0, reason: .needsHelper) })
}
- /// Puts `items` back in the order given, each as `restore(_:canUseHelper:)` does, and answers for each why it
- /// stayed, or nil. The Dock tiles an uninstall took out for them go back then, all at once. Launch Services
- /// leaves out an app in the Trash and isn't told it moved back, so the apps among them are registered again, but
- /// only once every item is back: a registered app starts its extensions, which would make their containers again
- /// before the ones in the Trash went back.
+ /// What putting items back did.
+ public struct Restored: Sendable {
+ /// Why each item stayed, in the order given, or nil for one that went back.
+ public internal(set) var failures: [RestoreFailure?] = []
+ /// For each item, the file an edit of it wrote in its place, which moved to the Trash to make room, or nil.
+ /// Each is written down like any removal, so it can be put back too.
+ public internal(set) var movedAside: [TrashedItem?] = []
+ }
+
+ /// Puts `items` back in the order given, each as `restore(_:canUseHelper:)` does. The Dock tiles an uninstall took
+ /// out for them go back then, all at once. Launch Services leaves out an app in the Trash and isn't told it moved
+ /// back, so the apps among them are registered again, but only once every item is back: a registered app starts
+ /// its extensions, which would make their containers again before the ones in the Trash went back.
@concurrent
- public func restore(_ items: [TrashedItem], canUseHelper: Bool = false) async -> [RestoreFailure?] {
- var answers: [RestoreFailure?] = []
+ public func restore(_ items: [TrashedItem], canUseHelper: Bool = false) async -> Restored {
+ var restored = Restored()
for item in items {
- answers.append(await restore(item, canUseHelper: canUseHelper))
+ let answer = await putBack(item, canUseHelper: canUseHelper)
+ restored.failures.append(answer.failure)
+ restored.movedAside.append(answer.movedAside)
}
- let back = zip(items, answers).filter { $0.1 == nil }.map(\.0.originalURL)
+ let back = zip(items, restored.failures).filter { $0.1 == nil }.map(\.0.originalURL)
if !back.isEmpty {
await putBackDockTiles(back)
}
- for (item, answer) in zip(items, answers)
+ for (item, answer) in zip(items, restored.failures)
where answer == nil && AppBundleLayout.isAnApp(item.originalURL) {
await registerApp(item.originalURL)
}
- return answers
+ return restored
}
/// Moves an item from the Trash back where it came from, through the helper when the folder needs
/// administrator rights.
@concurrent
func restore(_ item: TrashedItem, canUseHelper: Bool = false) async -> RestoreFailure? {
- let failure = await moveBack(item, canUseHelper: canUseHelper)
- if failure == nil {
- journal?.forget([item])
- // 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)
+ await putBack(item, canUseHelper: canUseHelper).failure
+ }
+
+ /// Puts `item` back, first moving to the Trash the file an edit of it wrote in its place, which comes back as the
+ /// item moved aside. Should `item` not go back after all, the edit goes back to its place.
+ private func putBack(
+ _ item: TrashedItem, canUseHelper: Bool
+ ) async -> (failure: RestoreFailure?, movedAside: TrashedItem?) {
+ var movedAside: TrashedItem?
+ if item.editStandsInItsPlace {
+ if let refusal = refusal(ofPuttingBack: item, canUseHelper: canUseHelper) { return (refusal, nil) }
+ let moved = await trash([item.originalURL])
+ guard var edit = moved.trashed.first else {
+ return (.editStays(moved.failures.first?.reason ?? .changedSinceScan), nil)
}
+ edit.replacedBy = item.identity
+ movedAside = edit
+ }
+ let failure = await moveBack(item, canUseHelper: canUseHelper)
+ guard failure == nil else {
+ guard let movedAside else { return (failure, nil) }
+ let editBack = await putBack(movedAside, canUseHelper: canUseHelper)
+ return (failure, editBack.failure == nil ? nil : movedAside)
}
- return failure
+ journal?.forget([item])
+ // 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 (nil, movedAside)
}
/// Why `item` cannot go back as things stand, or nil when it can. A way back only the helper can take stays when
@@ -838,7 +883,11 @@ public struct TrashService: Sendable {
return .notAllowed(refusal)
}
guard item.isInTheTrash else { return .missingFromTrash }
- guard !item.originalURL.isThere else { return .alreadyThere }
+ if item.originalURL.isThere {
+ guard item.editStandsInItsPlace else { return .alreadyThere }
+ if FileAccess.isLockedInFinder(item.originalURL) { return .editStays(.locked) }
+ if let refusal = refusal(of: item.originalURL) { return .editStays(refusal) }
+ }
if FileAccess.isLockedInFinder(item.trashedURL) { return .locked }
let folder = URL(filePath: Self.folder(puttingBack: item))
let privacy = FileAccess.isProtectedByPrivacy(folder)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/EditPutBackTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/EditPutBackTests.swift
new file mode 100644
index 00000000..12a8e9ec
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/EditPutBackTests.swift
@@ -0,0 +1,171 @@
+import Darwin
+import Foundation
+@testable import PeelCore
+import Synchronization
+import Testing
+
+private final class Started: Sendable {
+ private let labels = Mutex<[String]>([])
+
+ func add(_ label: String) { labels.withLock { $0.append(label) } }
+
+ var all: [String] { labels.withLock { $0 } }
+}
+
+/// A made-up home with an agent's file moved to its own Trash, and an edit written in its place.
+private struct EditedAgent: ~Copyable {
+ let directory: TemporaryDirectory
+ let place: URL
+ let trash: URL
+ let started = Started()
+
+ init() throws {
+ let directory = try TemporaryDirectory()
+ let place = try directory.file("home/Library/LaunchAgents/org.example.edit.plist", contents: Data("old".utf8))
+ let trash = try directory.directory("home/.Trash")
+ self.place = place
+ self.trash = trash
+ self.directory = directory
+ }
+
+ func service(exclusions: Exclusions = .none) -> TrashService {
+ let trash = trash
+ let started = started
+ return TrashService(
+ environment: SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ ),
+ exclusions: exclusions,
+ startJob: { job, _ in started.add(job.label) }
+ ) { url in
+ var destination = trash.appending(path: url.lastPathComponent)
+ if FileManager.default.fileExists(atPath: destination.path(percentEncoded: false)) {
+ destination = trash.appending(path: "\(UUID().uuidString)-\(url.lastPathComponent)")
+ }
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+ }
+
+ /// Moves the file at its place to the Trash, as a Save does, and writes `edit` there instead.
+ func edit(_ edit: String, with service: TrashService) async throws -> TrashedItem {
+ var moved = try #require(await service.trash([place]).trashed.first)
+ try Data(edit.utf8).write(to: place)
+ moved.replacedBy = TrashedItem.Identity(ofItemAt: place)
+ return moved
+ }
+
+ func text(at url: URL) throws -> String {
+ try String(contentsOf: url, encoding: .utf8)
+ }
+}
+
+struct EditPutBackTests {
+ @Test func aRecordKeepsWhatAnEditWroteInItsPlace() throws {
+ let directory = try TemporaryDirectory()
+ let edit = try directory.file("org.example.edit.plist", bytes: 3)
+ let item = TrashedItem(
+ originalURL: URL(filePath: "/Users/x/Library/LaunchAgents/org.example.edit.plist"),
+ trashedURL: URL(filePath: "/Users/x/.Trash/org.example.edit.plist"), date: .now
+ )
+ var edited = item
+ edited.replacedBy = TrashedItem.Identity(ofItemAt: edit)
+ #expect(edited.replacedBy != nil)
+ let record = RemovalRecord(batch: UUID(), item: edited, size: 3, source: "org.example.edit", tool: "backgroundItems")
+
+ let read = try JSONDecoder().decode(RemovalRecord.self, from: JSONEncoder().encode(record))
+ let older = try JSONDecoder().decode(
+ RemovalRecord.self,
+ from: JSONEncoder().encode(RemovalRecord(batch: UUID(), item: item, size: 3, source: "x", tool: "y"))
+ )
+
+ #expect(read.trashedItem.replacedBy == edited.replacedBy)
+ #expect(older.trashedItem.replacedBy == nil)
+ }
+
+ @Test func putBackRefusesAPlaceTakenByAnythingButTheEditItRecords() async throws {
+ let agent = try EditedAgent()
+ let service = agent.service()
+ let moved = try await agent.edit("edited", with: service)
+ var unrecorded = moved
+ unrecorded.replacedBy = nil
+ var another = moved
+ another.replacedBy = TrashedItem.Identity(ofItemAt: agent.trash)
+
+ #expect(moved.editStandsInItsPlace)
+ #expect(service.refusal(ofPuttingBack: moved, canUseHelper: false) == nil)
+ #expect(service.refusal(ofPuttingBack: unrecorded, canUseHelper: false) == .alreadyThere)
+ #expect(service.refusal(ofPuttingBack: another, canUseHelper: false) == .alreadyThere)
+ }
+
+ @Test func putBackMovesTheEditToTheTrashFirstThenPutsTheOldFileBackAndStartsItsJob() async throws {
+ let agent = try EditedAgent()
+ let service = agent.service()
+ var moved = try await agent.edit("edited", with: service)
+ moved.stoppedJob = "org.example.edit"
+
+ let result = await service.restore([moved])
+
+ #expect(result.failures == [nil])
+ let aside = try #require(result.movedAside.first ?? nil)
+ #expect(aside.originalURL == agent.place)
+ #expect(try agent.text(at: agent.place) == "old")
+ #expect(try agent.text(at: aside.trashedURL) == "edited")
+ #expect(aside.replacedBy == moved.identity)
+ #expect(agent.started.all.isEmpty, "the file holds no job launchd could read, so none starts")
+
+ let again = await service.restore([aside])
+ #expect(again.failures == [nil])
+ #expect(try agent.text(at: agent.place) == "edited")
+ let back = try #require(again.movedAside.first ?? nil)
+ #expect(try agent.text(at: back.trashedURL) == "old")
+ }
+
+ @Test func startsTheJobTheOldFileDeclaresOnceItIsBack() async throws {
+ let agent = try EditedAgent()
+ let job = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <plist version="1.0"><dict><key>Label</key><string>org.example.edit</string>
+ <key>ProgramArguments</key><array><string>/bin/sleep</string><string>1</string></array></dict></plist>
+ """
+ try Data(job.utf8).write(to: agent.place)
+ let service = agent.service()
+ var moved = try await agent.edit("edited", with: service)
+ moved.stoppedJob = "org.example.edit"
+
+ #expect(await service.restore([moved]).failures == [nil])
+ #expect(agent.started.all == ["org.example.edit"])
+ }
+
+ @Test func movesNothingWhenTheEditCannotGoToTheTrash() async throws {
+ let agent = try EditedAgent()
+ let service = agent.service()
+ let moved = try await agent.edit("edited", with: service)
+ #expect(chflags(agent.place.path(percentEncoded: false), UInt32(UF_IMMUTABLE)) == 0)
+ defer { _ = chflags(agent.place.path(percentEncoded: false), 0) }
+
+ let result = await service.restore([moved])
+
+ #expect(result.failures == [.editStays(.locked)])
+ #expect(result.movedAside == [nil])
+ #expect(try agent.text(at: agent.place) == "edited")
+ #expect(try agent.text(at: moved.trashedURL) == "old")
+ #expect(service.refusal(ofPuttingBack: moved, canUseHelper: false) == .editStays(.locked))
+ }
+
+ @Test func putsTheEditBackWhenTheOldFileCannotGoBack() async throws {
+ let agent = try EditedAgent()
+ let service = agent.service()
+ let moved = try await agent.edit("edited", with: service)
+ // The old file left the Trash meanwhile, so it can't go back.
+ try FileManager.default.removeItem(at: moved.trashedURL)
+ try Data("old".utf8).write(to: moved.trashedURL)
+
+ let result = await service.restore([moved])
+
+ #expect(result.failures == [.missingFromTrash])
+ #expect(result.movedAside == [nil])
+ #expect(try agent.text(at: agent.place) == "edited")
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
index 3da19249..58d49197 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
@@ -646,6 +646,50 @@ struct HistoryCommandTests {
#expect(real.failure != nil)
}
+ @Test func aRestoreMovesTheEditInItsPlaceToTheTrashFirstAndKeepsItInHistory() async throws {
+ let directory = try TemporaryDirectory()
+ let logs = logs(in: directory)
+ let place = try directory.file("home/Library/LaunchAgents/org.example.edit.plist", contents: Data("edited".utf8))
+ let trashed = try directory.file("home/.Trash/org.example.edit.plist", contents: Data("old".utf8))
+ let item = TrashedItem(
+ originalURL: place, trashedURL: trashed, date: .now, identity: TrashedItem.Identity(ofItemAt: trashed),
+ replacedBy: TrashedItem.Identity(ofItemAt: place)
+ )
+ let record = RemovalRecord(batch: UUID(), item: item, size: 3, source: "org.example.edit", tool: "backgroundItems")
+ _ = await logs.removals.add([record])
+ let trash = directory.url.appending(path: "home/.Trash")
+ let service = TrashService(
+ environment: SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ )
+ ) { url in
+ let destination = trash.appending(path: "edit-\(url.lastPathComponent)")
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+ func run(_ flag: String) async throws -> String {
+ let collected = Output.Collected()
+ let command: RestoreCommand = try command(["restore", String(record.batch.uuidString.prefix(8)), flag])
+ try await Output.$collected.withValue(collected) {
+ try await command.run(in: logs.removals, using: service)
+ }
+ return collected.output + collected.notes
+ }
+
+ let dry = try await run("--dry-run")
+ #expect(dry.contains("the edit in its place goes to the Trash first, and History keeps it"), "\(dry)")
+ #expect(try String(contentsOf: place, encoding: .utf8) == "edited")
+
+ let real = try await run("-y")
+ #expect(real.contains("Put 1 item back."), "\(real)")
+ #expect(try String(contentsOf: place, encoding: .utf8) == "old")
+ let kept = await logs.removals.load().records ?? []
+ #expect(kept.map(\.originalURL) == [place])
+ #expect(kept.first?.replacedBy == TrashedItem.Identity(ofItemAt: place))
+ #expect(try kept.first.map { try String(contentsOf: $0.trashedURL, encoding: .utf8) } == "edited")
+ }
+
@Test func saysSoWhenEverythingLeftIsRefused() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LaunchAgentFileTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LaunchAgentFileTests.swift
index 794eb1c7..3cbd4939 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/LaunchAgentFileTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LaunchAgentFileTests.swift
@@ -170,6 +170,7 @@ struct LaunchAgentFileTests {
guard case .saved(let moved, let reload) = outcome else { Issue.record("\(outcome)"); return }
#expect(reload == nil)
#expect(moved.trashed.map(\.originalURL) == [home.plist])
+ #expect(moved.trashed.first?.replacedBy == TrashedItem.Identity(ofItemAt: home.plist))
#expect(steps.all == ["move", "stop", "start true"])
#expect(try String(contentsOf: home.plist, encoding: .utf8) == job(seconds: 700))
#expect(try String(contentsOf: home.trash.appending(path: "org.example.edit.plist"), encoding: .utf8) == job())
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
index aea04443..40dc9a64 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
@@ -564,9 +564,9 @@ struct TrashServiceTests {
let moved = await service.trash([app, cache]).trashed
#expect(registered.withLock { $0 }.isEmpty)
- #expect(await service.restore(moved) == [nil, nil])
+ #expect(await service.restore(moved).failures == [nil, nil])
let appMoved = try #require(moved.first { $0.originalURL == app })
- #expect(await service.restore([appMoved]) == [.missingFromTrash])
+ #expect(await service.restore([appMoved]).failures == [.missingFromTrash])
#expect(registered.withLock { $0 } == [app.path(percentEncoded: false)])
}
@@ -588,7 +588,7 @@ struct TrashServiceTests {
}
let moved = await service.trash([data]).trashed
- #expect(await service.restore(moved) == [nil])
+ #expect(await service.restore(moved).failures == [nil])
#expect(registered.withLock { $0 }.isEmpty)
}
@@ -616,7 +616,7 @@ struct TrashServiceTests {
let moved = await service.trash([app, container]).trashed
let appFirst = moved.sorted { ($0.originalURL == app ? 0 : 1) < ($1.originalURL == app ? 0 : 1) }
- #expect(await service.restore(appFirst) == [nil, nil])
+ #expect(await service.restore(appFirst).failures == [nil, nil])
#expect(containerWasBack.withLock { $0 } == [true])
}
@@ -640,8 +640,8 @@ struct TrashServiceTests {
let moved = try #require(await service.trash([app]).trashed.first)
#expect(asked.withLock { $0 }.isEmpty)
- #expect(await service.restore([moved]) == [nil])
- #expect(await service.restore([moved]) != [nil])
+ #expect(await service.restore([moved]).failures == [nil])
+ #expect(await service.restore([moved]).failures != [nil])
#expect(asked.withLock { $0 } == ["org.example.Studio.app"])
}
diff --git a/Peel/Model/RemovalHistoryStore.swift b/Peel/Model/RemovalHistoryStore.swift
index 25edb467..8db2a71e 100644
--- a/Peel/Model/RemovalHistoryStore.swift
+++ b/Peel/Model/RemovalHistoryStore.swift
@@ -134,7 +134,7 @@ final class RemovalHistoryStore {
private let outcome: RemovalOutcome?
private let knowsTheExclusions: () -> Bool
private let removesPeel: () -> Bool
- private let restoring: ([TrashedItem], Bool) async -> [RestoreFailure?]
+ private let restoring: ([TrashedItem], Bool) async -> TrashService.Restored
private let announcing: (AttributedString) -> Void
/// Read again here once History has counted a removal, rather than by each tool.
var stats: LifetimeStats?
@@ -209,7 +209,7 @@ final class RemovalHistoryStore {
outcome: RemovalOutcome? = nil,
knowsTheExclusions: @escaping () -> Bool = { ExclusionsStore.shared.exclusions.isKnown },
removesPeel: @escaping () -> Bool = { false },
- restoring: @escaping ([TrashedItem], Bool) async -> [RestoreFailure?] = { items, canUseHelper in
+ restoring: @escaping ([TrashedItem], Bool) async -> TrashService.Restored = { items, canUseHelper in
await TrashService(exclusions: ExclusionsStore.shared.exclusions).restore(items, canUseHelper: canUseHelper)
},
announcing: @escaping (AttributedString) -> Void = { AccessibilityNotification.Announcement($0).post() },
@@ -529,7 +529,7 @@ final class RemovalHistoryStore {
let disks = await MountedDisks.read()
let ordered = records.map { $0.located(on: disks) }.inPutBackOrder
let answers = await restoring(ordered.map(\.trashedItem), canUseHelper)
- for (record, answer) in zip(ordered, answers) {
+ for (record, answer) in zip(ordered, answers.failures) {
if let failure = answer {
problems[record.id] = failure
stayed.append((record, failure))
@@ -537,6 +537,14 @@ final class RemovalHistoryStore {
restored.insert(record.id)
}
}
+ // An edit that made room goes into History under the same part, so it can come back too.
+ var aside = RemovalInProgress()
+ for (record, edit) in zip(ordered, answers.movedAside) {
+ guard let edit else { continue }
+ let size = await FileSize.reclaimableSize(of: edit.trashedURL)
+ let sizes = size.map { [edit.originalURL: $0] } ?? [:]
+ await self.record(TrashResult(trashed: [edit]), part: record.part, sizes: sizes, in: &aside)
+ }
for record in ordered {
failures[record.id] = problems[record.id]
}
diff --git a/Peel/Views/History/HistoryDetailView.swift b/Peel/Views/History/HistoryDetailView.swift
index 6df500a0..c5e454ca 100644
--- a/Peel/Views/History/HistoryDetailView.swift
+++ b/Peel/Views/History/HistoryDetailView.swift
@@ -226,11 +226,14 @@ private enum RecordPlace {
private enum RecordNote {
case sharedStorage
case loadsAfterARestart
+ case editStandsInItsPlace
var text: LocalizedStringResource {
switch self {
case .sharedStorage: "It shared most of its storage with another copy, so moving it freed only its own part."
case .loadsAfterARestart: "Once put back, macOS loads this audio driver only after you restart your Mac."
+ case .editStandsInItsPlace:
+ "Your edit of it stands in its place, so Put Back moves that edit to the Trash first, where History keeps it."
}
}
}
@@ -286,6 +289,7 @@ private struct HistoryRecordRow: View {
private var notes: [RecordNote] {
var notes: [RecordNote] = record.sharedStorage == true ? [.sharedStorage] : []
if place == .inTrash, AudioDrivers.isOne(record.originalURL) { notes.append(.loadsAfterARestart) }
+ if place == .inTrash, record.trashedItem.editStandsInItsPlace { notes.append(.editStandsInItsPlace) }
return notes
}
diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swift
index 73fb454b..ec0b9bbf 100644
--- a/Peel/Views/Presentation.swift
+++ b/Peel/Views/Presentation.swift
@@ -301,6 +301,9 @@ extension RestoreFailure {
String(localized: "macOS lets Peel put back another developer’s app only with App Management. Allow Peel in System Settings > Privacy & Security > App Management, then try again.")
case .notPermitted: String(localized: "macOS didn’t allow it.")
case .failed(let message): FixedSentence.translated(message)
+ case .editStays(let reason):
+ String(localized: "The edit in its place couldn’t move to the Trash first, so nothing changed.") + " "
+ + reason.explanation
}
}
}
diff --git a/PeelTests/RemovalHistoryStoreTests.swift b/PeelTests/RemovalHistoryStoreTests.swift
index fd306bd3..7fc06b38 100644
--- a/PeelTests/RemovalHistoryStoreTests.swift
+++ b/PeelTests/RemovalHistoryStoreTests.swift
@@ -1,7 +1,7 @@
import Foundation
import Observation
@testable import Peel
-import PeelCore
+@testable import PeelCore
import Synchronization
import Testing
@@ -172,7 +172,7 @@ struct RemovalHistoryStoreTests {
restoring: { items, _ in
// Back in place, and History's folder closed before History is told.
try? FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: path)
- return items.map { _ in nil }
+ return TrashService.Restored(failures: items.map { _ in nil }, movedAside: items.map { _ in nil })
}
)
var removal = RemovalInProgress()
@@ -187,6 +187,37 @@ struct RemovalHistoryStoreTests {
#expect(history.trashLooks == looks + 1, "the page kept saying it is in the Trash")
}
+ @Test func aPutBackWritesDownTheEditItMovedAsideUnderTheSamePart() async throws {
+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: folder) }
+ let edit = try JSONDecoder().decode(TrashedItem.Identity.self, from: Data(#"{"inode": 5, "birth": 6}"#.utf8))
+ let aside = TrashedItem(
+ originalURL: URL(filePath: "/Users/me/Library/LaunchAgents/org.example.edit.plist"),
+ trashedURL: URL(filePath: "/Users/me/.Trash/org.example.edit 2.plist"), date: .now, replacedBy: edit
+ )
+ let history = RemovalHistoryStore(
+ log: RemovalLog(url: folder.appending(path: "removals.json")),
+ refusals: RefusalLog(url: folder.appending(path: "refusals.json")),
+ knowsTheExclusions: { true },
+ restoring: { items, _ in
+ TrashService.Restored(failures: items.map { _ in nil }, movedAside: items.map { _ in aside })
+ }
+ )
+ var removal = RemovalInProgress()
+ let part = RemovalPart(source: "org.example.edit", sourceKey: nil, tool: Tool.backgroundItems.rawValue)
+ await history.record(try moved("org.example.edit.plist"), part: part, sizes: [:], in: &removal)
+ history.finish(removal)
+ let undoable = history.undoTitle
+
+ await history.restore(history.records, canUseHelper: false)
+
+ #expect(history.records.map(\.originalURL) == [aside.originalURL])
+ #expect(history.records.first?.part == part)
+ #expect(history.records.first?.replacedBy == edit)
+ #expect(history.undoTitle == nil, "nothing new to undo: the move aside is part of the Put Back")
+ #expect(undoable != nil)
+ }
+
@Test func tellsAPutBackThatEndsAsTheOneBefore() async throws {
let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: folder) }
@@ -196,7 +227,9 @@ struct RemovalHistoryStoreTests {
refusals: RefusalLog(url: folder.appending(path: "refusals.json")),
outcome: outcome,
knowsTheExclusions: { true },
- restoring: { items, _ in items.map { _ in .needsHelper } }
+ restoring: { items, _ in
+ TrashService.Restored(failures: items.map { _ in .needsHelper }, movedAside: items.map { _ in nil })
+ }
)
var removal = RemovalInProgress()
let part = RemovalPart(source: "Example", sourceKey: nil, tool: Tool.developer.rawValue)
@@ -222,7 +255,9 @@ struct RemovalHistoryStoreTests {
refusals: RefusalLog(url: folder.appending(path: "refusals.json")),
outcome: outcome,
knowsTheExclusions: { true },
- restoring: { items, _ in items.map { _ in .needsHelper } }
+ restoring: { items, _ in
+ TrashService.Restored(failures: items.map { _ in .needsHelper }, movedAside: items.map { _ in nil })
+ }
)
var removal = RemovalInProgress()
let part = RemovalPart(source: "Example", sourceKey: nil, tool: Tool.developer.rawValue)
diff --git a/PeelTests/RemovalOutcomeTests.swift b/PeelTests/RemovalOutcomeTests.swift
index 3c01e94f..f57b81c1 100644
--- a/PeelTests/RemovalOutcomeTests.swift
+++ b/PeelTests/RemovalOutcomeTests.swift
@@ -1,6 +1,6 @@
import Foundation
@testable import Peel
-import PeelCore
+@testable import PeelCore
import Testing
struct RemovalOutcomeTests {
@@ -55,7 +55,12 @@ struct RemovalOutcomeTests {
refusals: RefusalLog(url: folder.appending(path: "refusals.json")),
outcome: outcome,
knowsTheExclusions: { true },
- restoring: { items, _ in items.map { $0.originalURL.lastPathComponent == staying ? failure : nil } }
+ restoring: { items, _ in
+ TrashService.Restored(
+ failures: items.map { $0.originalURL.lastPathComponent == staying ? failure : nil },
+ movedAside: items.map { _ in nil }
+ )
+ }
)
}
diff --git a/SAFETY.md b/SAFETY.md
index 9cafc4f8..5c0e722b 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -271,7 +271,7 @@ Some of what Peel does is not a move to the Trash. Each is here with how it is u
| Build Artifacts leaves a project's build folders out of Time Machine, when you ask it to | The same checkbox takes the mark off, and leaves alone a mark a tool put on what Peel never marks |
| A background item is stopped, started, disabled, or enabled | The same buttons in Background Items; a disabled item stays disabled after a restart until you enable it |
| A background job a deleted app left loaded is removed (`launchctl bootout`) | Nothing to bring back: its app, and what the job ran, are gone |
-| An agent's file in your own `~/Library/LaunchAgents` is edited in Background Items, only when you save | The file as it was is in the Trash, and History puts it back once you move the edited one away |
+| An agent's file in your own `~/Library/LaunchAgents` is edited in Background Items, only when you save | Putting the file as it was back from History, which first moves your edit to the Trash, where History keeps it too |
| A tweak changes a setting of macOS, and the Dock, Finder, Control Center, or the window manager restarts to read it (`killall`, which for Finder stops anything it is copying) | Turning the tweak off puts back what was there before, or leaves it to macOS. Turn All Off puts back only what Peel changed, and leaves what you set yourself as it is |
| The Terminal page adds Peel's profiles and options to Terminal, makes `~/.hushlogin`, writes Peel's shell and ssh files, and changes Git's settings | Put Back, turning the setting off, or Turn All Off, as [Terminal's settings](#terminals-settings) says |