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.

Ask before forgetting the refusals, and move them to the Trash

Țugui Dragoș95c53054ab02
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 9f6f5095..fde36971 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -127,9 +127,9 @@ Take the most common case, uninstalling an app. Every other page follows the sam
A handful of ideas carry most of the weight. Each is enforced in one place and tested there.
- **The Trash, never deletion.** Nothing in Peel deletes anything of the user's; what it deletes outright is its own:
- its list of refusals, when `peel history --refused --clear` is asked to forget it; the empty placeholder `TrashMover`
- makes to hold a name on a disk that cannot rename without replacing (exFAT), when the move it was made for fails; and
- the folder `PreferenceBackup` makes for a reset's saved settings, when saving fails while it is still empty. Four
+ the empty placeholder `TrashMover` makes to hold a name on a disk that cannot rename without replacing (exFAT), when
+ the move it was made for fails, and the folder `PreferenceBackup` makes for a reset's saved settings, when saving
+ fails while it is still empty. Its list of refusals goes to the Trash when `peel history --refused --clear` asks. Four
actions can't be undone by History, and each says so where it is confirmed: Homebrew's own uninstall and clean up,
resetting an app's privacy permissions, and Force Quit for an app that is still open 10 seconds after Peel asked it to
quit (`QuitBeforeRemoving`). Forgetting a preference domain happens only once its file is in the Trash, so putting the
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0d734caa..1ac8bcd0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -11,10 +11,10 @@ from happening, and they are not up for negotiation.
**Nothing of the user's is ever deleted for good.** Every removal goes to the Trash through `TrashService` and is
recorded, so History can put it back; in the app it runs inside `QuitGuard.shared.run` from its first move until History
has it, and so does a Put Back, so that quitting waits for them. No code path in Peel deletes anything of the user's,
-and a change that adds one won't be accepted. What Peel deletes outright is its own: its list of refusals, when
-`peel history --refused --clear` is asked to forget it; the empty placeholder `TrashMover` makes to hold a name on a
-disk that cannot rename without replacing (exFAT), when the move it was made for fails; and the folder
-`PreferenceBackup` makes for a reset's saved settings, when saving fails while it is still empty. Four things Peel
+and a change that adds one won't be accepted. What Peel deletes outright is its own: the empty placeholder
+`TrashMover` makes to hold a name on a disk that cannot rename without replacing (exFAT), when the move it was made for
+fails, and the folder `PreferenceBackup` makes for a reset's saved settings, when saving fails while it is still empty.
+Its list of refusals goes to the Trash when `peel history --refused --clear` asks. Four things Peel
starts can't be undone by History, and each says so where the user confirms it: Homebrew's own uninstall and clean up,
resetting an app's privacy permissions, and Force Quit for an app that is still open 10 seconds after Peel asked it to
quit. `defaults delete` for an app's preferences runs only once their file is in the Trash, and a reset exports the
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
index 20aed7e2..dc504b21 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/HistoryCommands.swift
@@ -53,9 +53,12 @@ struct HistoryCommand: AsyncParsableCommand {
@Flag(help: "List what stayed and why, instead of what moved.")
var refused = false
- @Flag(help: "Forget every refusal on record. Only with --refused.")
+ @Flag(help: "Move the record of every refusal to the Trash. Only with --refused.")
var clear = false
+ @Flag(name: .shortAndLong, help: "Don't ask for confirmation. Only with --clear.")
+ var yes = false
+
@OptionGroup var output: OutputOptions
private struct Record: Encodable {
@@ -153,16 +156,21 @@ struct HistoryCommand: AsyncParsableCommand {
guard !clear || !output.json else {
throw ValidationError("--clear writes nothing to read, so it doesn't go with --json.")
}
+ guard !yes || clear else { throw ValidationError("--yes only goes with --clear.") }
+ if clear, !yes {
+ try Output.requireConfirmable()
+ }
}
private var shown: Int { limit ?? Self.defaultLimit }
func run() async throws {
- try await run(in: RemovalLog(), refusals: RefusalLog())
+ let trash = TrashService(exclusions: await ExclusionStore().load())
+ try await run(in: RemovalLog(), refusals: RefusalLog(), trash: trash)
}
- func run(in log: RemovalLog, refusals: RefusalLog) async throws {
- guard !refused else { return try await listRefusals(in: refusals) }
+ func run(in log: RemovalLog, refusals: RefusalLog, trash: TrashService) async throws {
+ guard !refused else { return try await listRefusals(in: refusals, trash: trash) }
let outcome = await log.load()
guard let records = outcome.records else {
throw CommandFailure("Peel couldn't read its History.\(outcome.problem.map { " \($0.summary)" } ?? "")")
@@ -219,10 +227,19 @@ struct HistoryCommand: AsyncParsableCommand {
TrashFailure.Reason(name: record.reason, detail: record.detail)?.summary ?? record.detail ?? record.reason
}
- private func listRefusals(in log: RefusalLog) async throws {
+ private func listRefusals(in log: RefusalLog, trash: TrashService) async throws {
guard !clear else {
- guard await log.clear() else { throw CommandFailure("Peel couldn't forget its refusals.") }
- Output.line("Forgot every refusal on record.")
+ guard await log.load().records?.isEmpty != true else {
+ Output.line("Peel hasn't refused anything it was asked to move.")
+ return
+ }
+ if !yes {
+ try Output.confirm("Move the record of every refusal to the Trash?")
+ }
+ guard await log.clear(through: trash) else {
+ throw CommandFailure("Peel couldn't move its record of refusals to the Trash.")
+ }
+ Output.line("Moved the record of every refusal to the Trash.")
return
}
let read = await log.load()
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
index bb81ce6c..09e3fdc1 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
@@ -88,11 +88,17 @@ public actor RefusalLog {
}
}
- /// Deletes the file for good, so `unlink`, which never takes a folder put in its place.
- public func clear() -> Bool {
- FileLock.whileHeld(beside: url) {
- url.isMissing || unlink(url.path(percentEncoded: false)) == 0
- }
+ /// Moves the file to the Trash, so every refusal is forgotten and the record can still be taken back from there.
+ /// Only the file moves, never a folder or a link put in its place, and a refusal written meanwhile waits for it.
+ public func clear(through service: TrashService) async -> Bool {
+ await FileLock.whileHeld(beside: url, waitingFor: {
+ guard !url.isMissing else { return true }
+ var info = stat()
+ guard lstat(url.path(percentEncoded: false), &info) == 0, info.st_mode & S_IFMT == S_IFREG else {
+ return false
+ }
+ return await service.trashOwnFiles([url]).failures.isEmpty
+ })
}
/// The records in the file. A file that fails to decode is set aside and its readable rows kept. Nil records
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FileLock.swift b/Packages/PeelCore/Sources/PeelCore/Support/FileLock.swift
index f9a76f69..cfcfc974 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FileLock.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FileLock.swift
@@ -10,19 +10,38 @@ enum FileLock {
private static let unstoppable = IgnoredSignals([SIGTSTP])
static func whileHeld<T>(beside url: URL, _ change: () -> T) -> T {
- try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
- let descriptor = open(url.path(percentEncoded: false) + ".lock", O_CREAT | O_RDWR | O_CLOEXEC, 0o600)
- guard descriptor >= 0 else { return change() }
+ guard let descriptor = openLock(beside: url) else { return change() }
defer { close(descriptor) }
return unstoppable.run {
- // A signal caught while waiting ends the wait early (EINTR), without the lock.
- var locked = flock(descriptor, LOCK_EX)
- while locked != 0, errno == EINTR {
- locked = flock(descriptor, LOCK_EX)
- }
- guard locked == 0 else { return change() }
- defer { flock(descriptor, LOCK_UN) }
+ let locked = lock(descriptor)
+ defer { if locked { flock(descriptor, LOCK_UN) } }
return change()
}
}
+
+ /// The same, for a change that has to wait for other work, such as a move to the Trash.
+ static func whileHeld<T>(beside url: URL, waitingFor change: () async -> T) async -> T {
+ guard let descriptor = openLock(beside: url) else { return await change() }
+ defer { close(descriptor) }
+ return await unstoppable.run {
+ let locked = lock(descriptor)
+ defer { if locked { flock(descriptor, LOCK_UN) } }
+ return await change()
+ }
+ }
+
+ private static func openLock(beside url: URL) -> Int32? {
+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ let descriptor = open(url.path(percentEncoded: false) + ".lock", O_CREAT | O_RDWR | O_CLOEXEC, 0o600)
+ return descriptor >= 0 ? descriptor : nil
+ }
+
+ private static func lock(_ descriptor: Int32) -> Bool {
+ // A signal caught while waiting ends the wait early (EINTR), without the lock.
+ var locked = flock(descriptor, LOCK_EX)
+ while locked != 0, errno == EINTR {
+ locked = flock(descriptor, LOCK_EX)
+ }
+ return locked == 0
+ }
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
index e5b24862..813249e7 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
@@ -1121,10 +1121,10 @@ struct CommandLineTests {
/// `--clear` only forgets the refusals. What moved is forgotten from History in the Peel app.
@Test func forgettingOnlyGoesWithTheRefusals() throws {
- let refused = try #require(try PeelCommand.parseAsRoot(["history", "--refused", "--clear"]) as? HistoryCommand)
+ let refused = try #require(try PeelCommand.parseAsRoot(["history", "--refused", "--clear", "-y"]) as? HistoryCommand)
#expect(refused.refused && refused.clear)
- #expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["history", "--clear"]) }
+ #expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["history", "--clear", "-y"]) }
#expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["history", "--refused", "--limit", "0"]) }
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
index ea19f5c5..2a26cd16 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/HistoryCommandTests.swift
@@ -10,6 +10,8 @@ struct HistoryCommandTests {
try #require(try PeelCommand.parseAsRoot(arguments) as? Command)
}
+ private let movesNothing = TrashService(environment: .current) { _ in throw CocoaError(.fileWriteUnknown) }
+
private func logs(in directory: borrowing TemporaryDirectory) -> (removals: RemovalLog, refusals: RefusalLog) {
(RemovalLog(url: directory.url.appending(path: "Peel/removals.json")),
RefusalLog(url: directory.url.appending(path: "Peel/refusals.json")))
@@ -102,7 +104,8 @@ struct HistoryCommandTests {
) async throws -> String {
let collected = Output.Collected()
try await Output.$collected.withValue(collected) {
- try await (command(arguments) as HistoryCommand).run(in: logs.removals, refusals: logs.refusals)
+ try await (command(arguments) as HistoryCommand)
+ .run(in: logs.removals, refusals: logs.refusals, trash: movesNothing)
}
return collected.output
}
@@ -302,14 +305,40 @@ struct HistoryCommandTests {
#expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["history", "--refused", "--clear", "--json"]) }
}
- @Test func forgetsTheRefusalsWhenAsked() async throws {
+ @Test func movesTheRefusalsToTheTrashWhenAsked() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
await logs.refusals.add([TrashFailure(url: URL(filePath: "/x"), reason: .lastCopy)], source: "Editor", tool: "duplicates")
+ let trash = try directory.directory("Trash")
+ let service = TrashService(
+ environment: SearchEnvironment(homeDirectory: directory.url, rootDirectory: directory.url)
+ ) { url in
+ let destination = trash.appending(path: url.lastPathComponent)
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
- try await (command(["history", "--refused", "--clear"]) as HistoryCommand).run(in: logs.removals, refusals: logs.refusals)
+ try await (command(["history", "--refused", "--clear", "--yes"]) as HistoryCommand)
+ .run(in: logs.removals, refusals: logs.refusals, trash: service)
#expect(await logs.refusals.load().records?.isEmpty == true)
+ #expect(FileManager.default.fileExists(atPath: trash.appending(path: "refusals.json").path(percentEncoded: false)))
+ }
+
+ @Test func movesNothingWhenNothingWasRefused() async throws {
+ let directory = try TemporaryDirectory()
+ let logs = logs(in: directory)
+
+ let said = try await printed(["history", "--refused", "--clear", "--yes"], from: logs)
+
+ #expect(said.contains("Peel hasn't refused anything it was asked to move."))
+ #expect(!said.contains("Moved"))
+ }
+
+ @Test func asksBeforeForgettingTheRefusals() throws {
+ #expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["history", "--refused", "--clear"]) }
+ #expect(throws: (any Error).self) { try PeelCommand.parseAsRoot(["history", "--refused", "--yes"]) }
+ _ = try PeelCommand.parseAsRoot(["history", "--refused", "--clear", "--yes"])
}
/// A History file that cannot be read is reported as an error, never shown as an empty History.
@@ -326,7 +355,8 @@ struct HistoryCommandTests {
}
await #expect(throws: CommandFailure.self) {
- try await (command(["history"]) as HistoryCommand).run(in: logs.removals, refusals: logs.refusals)
+ try await (command(["history"]) as HistoryCommand)
+ .run(in: logs.removals, refusals: logs.refusals, trash: movesNothing)
}
await #expect(throws: CommandFailure.self) {
try await (command(["restore", "abcd", "-y"]) as RestoreCommand).run(in: logs.removals, using: service(in: directory))
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
index 50da8db3..ebf01d7f 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RefusalLogTests.swift
@@ -8,6 +8,18 @@ struct RefusalLogTests {
TrashFailure(url: URL(filePath: path), reason: reason)
}
+ private func trash(in directory: borrowing TemporaryDirectory) throws -> (service: TrashService, folder: URL) {
+ let folder = try directory.directory("Trash")
+ let service = TrashService(
+ environment: SearchEnvironment(homeDirectory: directory.url, rootDirectory: directory.url)
+ ) { url in
+ let destination = folder.appending(path: UUID().uuidString + " " + url.lastPathComponent)
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+ return (service, folder)
+ }
+
@Test func writesWhatStayedAndWhy() async throws {
let directory = try TemporaryDirectory()
let log = RefusalLog(url: directory.url.appending(path: "Peel/refusals.json"))
@@ -172,27 +184,32 @@ struct RefusalLogTests {
try directory.setPermissions(0o600, of: "Peel")
defer { try? directory.setPermissions(0o755, of: "Peel") }
- #expect(await RefusalLog(url: url).clear() == false)
+ #expect(await RefusalLog(url: url).clear(through: try trash(in: directory).service) == false)
}
- @Test func clearForgetsEverything() async throws {
+ @Test func clearMovesTheRecordToTheTrash() async throws {
let directory = try TemporaryDirectory()
+ let (service, folder) = try trash(in: directory)
let log = RefusalLog(url: directory.url.appending(path: "Peel/refusals.json"))
await log.add([failure("/Users/me/a", .lastCopy)], source: "Editor", tool: "applications")
- #expect(await log.clear())
+ #expect(await log.clear(through: service))
#expect(await log.load().records?.isEmpty == true)
- #expect(await log.clear(), "forgetting what is already forgotten is no failure")
+ let trashed = try FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)
+ #expect(trashed.count == 1)
+ #expect(await RefusalLog(url: try #require(trashed.first)).load().records?.map(\.source) == ["Editor"])
+ #expect(await log.clear(through: service), "forgetting what is already forgotten is no failure")
}
- /// Forgetting refusals deletes for good, so it takes the file and never a folder put in its place.
- @Test func clearNeverDeletesAFolderInThePlaceOfTheFile() async throws {
+ @Test func clearNeverMovesAFolderInThePlaceOfTheFile() async throws {
let directory = try TemporaryDirectory()
+ let (service, folder) = try trash(in: directory)
let url = directory.url.appending(path: "Peel/refusals.json")
try directory.file("Peel/refusals.json/kept.txt", contents: Data("work".utf8))
- #expect(await RefusalLog(url: url).clear() == false)
+ #expect(await RefusalLog(url: url).clear(through: service) == false)
#expect(FileManager.default.fileExists(atPath: url.appending(path: "kept.txt").path(percentEncoded: false)))
+ #expect(try FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false)).isEmpty)
}
private static let everyReason: [TrashFailure.Reason] = [
diff --git a/SAFETY.md b/SAFETY.md
index e2e9d6f9..a4c4271b 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -150,9 +150,9 @@ A move to the Trash, or back from it, never replaces what is already at the new
themselves; on one that cannot, such as exFAT, Peel first takes the name with an empty placeholder, which only a
free name allows, and the move then replaces the placeholder.
-What Peel deletes outright is only its own: its list of refusals, when `peel history --refused --clear` is asked to
-forget it; such a placeholder, when the move it was made for fails; and the folder it makes to save an app's settings
-before a reset, when saving fails before anything is written in it.
+What Peel deletes outright is only its own: such a placeholder, when the move it was made for fails, and the folder it
+makes to save an app's settings before a reset, when saving fails before anything is written in it. Its list of
+refusals goes to the Trash when `peel history --refused --clear` is asked to forget it, after a question.
Four things Peel starts can't be undone by History, and Peel says so before you confirm each of them: Homebrew's own
uninstall and its clean ups (Clean Up, and clearing older or every download), which delete what they remove; resetting
diff --git a/Support/peel.1 b/Support/peel.1
index a100f6ef..e5cfb692 100644
--- a/Support/peel.1
+++ b/Support/peel.1
@@ -1,5 +1,5 @@
.\" "Generated by swift-argument-parser"
-.Dd October 6, 2026
+.Dd October 7, 2026
.Dt PEEL 1
.Os
.Sh NAME
@@ -121,7 +121,9 @@ Show at most this many removals. Without it, 20.
.It Fl -refused
List what stayed and why, instead of what moved.
.It Fl -clear
-Forget every refusal on record. Only with --refused.
+Move the record of every refusal to the Trash. Only with --refused.
+.It Fl y , -yes
+Don't ask for confirmation. Only with --clear.
.It Fl -json
Print JSON instead of text.
.It Fl -version