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 app's settings back even when macOS wrote an empty copy there

Țugui Dragoșab9e101c2139
diff --git a/AGENTS.md b/AGENTS.md
index f32a1a0a..3b44d8ef 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -44,10 +44,12 @@ Tests enforce these rules. If a change makes one of them fail, the rule is right
- **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 quitting waits for them. Peel deletes outright only its own: the empty
- placeholder `TrashMover` makes to hold a name on a disk that can't 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.
+ History has it, and so does a Put Back, so quitting waits for them. Peel deletes outright only what holds nothing of
+ the user's: the empty placeholder `TrashMover` makes to hold a name on a disk that can't rename without replacing
+ (exFAT), when the move it was made for fails, the folder `PreferenceBackup` makes for a reset's saved settings, when
+ saving fails while it is still empty, and the empty file cfprefsd writes back where a moved settings file was when
+ `PreferenceCleanup` forgets a domain it still holds. Its list of refusals goes to the Trash when
+ `peel history --refused --clear` asks.
- **What History can't undo says so where the person 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
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 3bc47dae..73da91a3 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -134,10 +134,12 @@ 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:
- 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
+- **The Trash, never deletion.** Nothing in Peel deletes anything of the user's; what it deletes outright holds
+ nothing of theirs: 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, the folder `PreferenceBackup` makes for a reset's saved
+ settings, when saving fails while it is still empty, and the empty file cfprefsd writes back where a moved settings
+ file was when `PreferenceCleanup` forgets a domain it still holds, which would keep History from putting that file
+ back. 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/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
index 16a38d2a..2afcedaf 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
@@ -65,12 +65,32 @@ enum PreferenceCleanup {
/// `owner` is the bundle identifier of the app being reset. Its own domain is forgotten even when Apple wrote
/// the app; every other `com.apple.` domain is left alone.
@concurrent
- static func forgetDomains(for urls: [URL], ownedBy owner: String?) async {
+ static func forgetDomains(
+ for urls: [URL],
+ ownedBy owner: String?,
+ home: URL = .homeDirectory,
+ host: String = PreferenceCleanup.hostIdentifier,
// The files have already moved, and the removal is recorded only after this returns, so each call has a
// timeout: a `defaults` that never exits must not leave the removal unrecorded.
- for domain in domains(for: urls, ownedBy: owner) {
- _ = await Subprocess.run("/usr/bin/defaults", domain.command("delete"), timeout: 10)
+ delete: @Sendable (Domain) async -> Void = {
+ _ = await Subprocess.run("/usr/bin/defaults", $0.command("delete"), timeout: 10)
}
+ ) async {
+ let files = files(for: urls, ownedBy: owner, home: home, host: host)
+ var forgotten: Set<Domain> = []
+ for domain in files.map(\.domain) where forgotten.insert(domain).inserted {
+ // A file already back before the delete is not one the delete wrote.
+ let freed = files.filter { $0.domain == domain && $0.url.isMissing }.map(\.url)
+ await delete(domain)
+ freed.forEach(deleteWrittenBack)
+ }
+ }
+
+ /// Deletes the empty file `defaults delete` writes where `file` was when cfprefsd still held its domain, which
+ /// would keep History from putting that file back. Only a file of this user holding an empty dictionary goes.
+ private static func deleteWrittenBack(at file: URL) {
+ guard case .success(let item) = OpenItem.at(file.path(percentEncoded: false)) else { return }
+ item.deleteFile(ownedBy: getuid(), ofAtMost: 1_024) { BoundedRead.propertyList(in: $0)?.isEmpty == true }
}
struct Domain: Sendable, Hashable {
@@ -99,14 +119,28 @@ enum PreferenceCleanup {
host: String = PreferenceCleanup.hostIdentifier,
running: String? = Bundle.main.bundleIdentifier
) -> [Domain] {
+ var seen: Set<Domain> = []
+ return files(for: urls, ownedBy: owner, home: home, host: host, running: running)
+ .map(\.domain)
+ .filter { seen.insert($0).inserted }
+ }
+
+ /// Each of `urls` whose domain `defaults delete` may forget, with that domain.
+ private static func files(
+ for urls: [URL],
+ ownedBy owner: String?,
+ home: URL,
+ host: String,
+ running: String? = Bundle.main.bundleIdentifier
+ ) -> [(url: URL, domain: Domain)] {
// Only the user's `Library/Preferences` and its `ByHost` folder, plus the settings file in the container
// of the app being reset. `defaults` reads a name as this user's domain, so a file from
// `/Library/Preferences` or a copy in a backup must not clear the settings in use.
let plain = PathPattern.comparablePath(of: home.appending(path: "Library/Preferences", directoryHint: .isDirectory))
let byHost = plain + "/ByHost"
- var seen: Set<Domain> = []
- return urls.compactMap { url -> Domain? in
+ var containerKept: [Domain: Bool] = [:]
+ return urls.compactMap { url -> (url: URL, domain: Domain)? in
let path = url.path(percentEncoded: false)
guard path.hasSuffix(".plist") else { return nil }
let parent = PathPattern.comparablePath(of: url.deletingLastPathComponent())
@@ -132,9 +166,9 @@ enum PreferenceCleanup {
// Apple's name whatever its case, since the disk ignores it, and behind a team or group prefix too.
guard !ProtectedData.isApplesName(name) || isOwned(name, by: owner) else { return nil }
let domain = Domain(name: name, isByHost: isByHost)
- guard !seen.contains(domain), !containerKeeps(domain, apartFrom: urls, home: home) else { return nil }
- seen.insert(domain)
- return domain
+ let isKept = containerKept[domain] ?? containerKeeps(domain, apartFrom: urls, home: home)
+ containerKept[domain] = isKept
+ return isKept ? nil : (url, domain)
}
}
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift b/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
index 3b04b984..092d135e 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
@@ -132,6 +132,31 @@ public final class OpenItem: Sendable {
}
}
+extension OpenItem {
+ /// Deletes this item for good when it is a regular file of `owner`, at most `maximum` bytes, whose bytes
+ /// `isDisposable` accepts. The file is read without following a link, and its name is removed only while it
+ /// still leads to the file that was read.
+ public func deleteFile(ownedBy owner: uid_t, ofAtMost maximum: Int, if isDisposable: (Data) -> Bool) {
+ guard let identity, let mode, mode & S_IFMT == S_IFREG else { return }
+ let file = name.withCString { openat(parent.descriptor, $0, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) }
+ guard file >= 0 else { return }
+ var info = stat()
+ var bytes = [UInt8](repeating: 0, count: maximum + 1)
+ let count = fstat(file, &info) == 0 ? read(file, &bytes, bytes.count) : -1
+ close(file)
+ guard
+ ItemIdentity(info) == identity, info.st_uid == owner, count >= 0, count <= maximum,
+ Int64(count) == info.st_size, isDisposable(Data(bytes[..<count]))
+ else { return }
+ var now = stat()
+ guard
+ name.withCString({ fstatat(parent.descriptor, $0, &now, AT_SYMLINK_NOFOLLOW) }) == 0,
+ ItemIdentity(now) == identity
+ else { return }
+ _ = name.withCString { unlinkat(parent.descriptor, $0, 0) }
+ }
+}
+
extension POSIXError {
/// The error `errno` holds for the call that just failed. Read it before any other call can change `errno`.
static var last: POSIXError { POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OpenItemTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OpenItemTests.swift
new file mode 100644
index 00000000..d40839fe
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/OpenItemTests.swift
@@ -0,0 +1,85 @@
+import Darwin
+import Foundation
+@testable import PeelCore
+@testable import PeelPrivileged
+import Testing
+
+struct OpenItemTests {
+ private func item(_ url: URL) throws -> OpenItem {
+ try OpenItem.at(url.path(percentEncoded: false)).get()
+ }
+
+ private func move(_ item: URL, to destination: URL) -> Bool {
+ rename(item.path(percentEncoded: false), destination.path(percentEncoded: false)) == 0
+ }
+
+ @Test func deletesOnlyAFileItsCheckAccepts() throws {
+ let directory = try TemporaryDirectory()
+ let accepted = try directory.file("accepted", contents: Data("a".utf8))
+ let refused = try directory.file("refused", contents: Data("b".utf8))
+
+ for file in [accepted, refused] {
+ try item(file).deleteFile(ownedBy: getuid(), ofAtMost: 16) { $0 == Data("a".utf8) }
+ }
+
+ #expect(accepted.isMissing)
+ #expect(refused.isThere)
+ }
+
+ @Test func keepsAFileOfAnotherOwner() throws {
+ let directory = try TemporaryDirectory()
+ let file = try directory.file("file", contents: Data("a".utf8))
+
+ try item(file).deleteFile(ownedBy: getuid() + 1, ofAtMost: 16) { _ in true }
+
+ #expect(file.isThere)
+ }
+
+ @Test func keepsAFileLargerThanItReads() throws {
+ let directory = try TemporaryDirectory()
+ let file = try directory.file("file", contents: Data("12345".utf8))
+
+ try item(file).deleteFile(ownedBy: getuid(), ofAtMost: 4) { _ in true }
+
+ #expect(file.isThere)
+ }
+
+ @Test func keepsALinkAndWhatItLeadsTo() throws {
+ let directory = try TemporaryDirectory()
+ let target = try directory.file("target", contents: Data("a".utf8))
+ let link = directory.url.appending(path: "link")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target)
+
+ try item(link).deleteFile(ownedBy: getuid(), ofAtMost: 16) { _ in true }
+
+ #expect(link.isThere)
+ #expect(target.isThere)
+ }
+
+ @Test func deletesNothingButTheFileItJudged() throws {
+ let directory = try TemporaryDirectory()
+ let file = try directory.file("file", contents: Data("kept".utf8))
+ let opened = try item(file)
+ let aside = directory.url.appending(path: "aside")
+ let judged = try directory.file("judged", contents: Data("a".utf8))
+ try #require(move(file, to: aside))
+ try #require(move(judged, to: file))
+
+ opened.deleteFile(ownedBy: getuid(), ofAtMost: 16) { bytes in
+ move(aside, to: file) && bytes == Data("a".utf8)
+ }
+
+ #expect([file, aside].contains { (try? Data(contentsOf: $0)) == Data("kept".utf8) })
+ }
+
+ @Test func keepsAFileThatTookTheNameWhileItWasRead() throws {
+ let directory = try TemporaryDirectory()
+ let file = try directory.file("file", contents: Data("a".utf8))
+ let other = try directory.file("other", contents: Data("a".utf8))
+
+ try item(file).deleteFile(ownedBy: getuid(), ofAtMost: 16) { _ in move(other, to: file) }
+
+ #expect(file.isThere)
+ #expect(other.isMissing)
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
index 5c36f395..94135c90 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
@@ -121,6 +121,68 @@ struct RemovalHygieneTests {
#expect(plain.command("delete") == ["delete", "com.example.app"])
}
+ /// cfprefsd answers a `defaults delete` of a domain it still holds by writing it back, empty, where the moved
+ /// file was, which keeps History from putting that file back. These are the bytes it writes.
+ private static let writtenBack = try? PropertyListSerialization.data(
+ fromPropertyList: [String: Any](),
+ format: .binary,
+ options: 0
+ )
+
+ @Test func deletesTheEmptyFileTheDeleteWritesBack() async throws {
+ let directory = try TemporaryDirectory()
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+ let plain = try directory.file("home/Library/Preferences/org.example.app.plist")
+ let byHost = try directory.file("home/Library/Preferences/ByHost/org.example.app.\(host).plist")
+ let trash = try directory.directory("Trash")
+ for file in [plain, byHost] {
+ try FileManager.default.moveItem(at: file, to: trash.appending(path: file.lastPathComponent))
+ }
+
+ await PreferenceCleanup.forgetDomains(for: [plain, byHost], ownedBy: nil, home: home, host: host) { domain in
+ try? Self.writtenBack?.write(to: domain.isByHost ? byHost : plain)
+ }
+
+ #expect(plain.isMissing)
+ #expect(byHost.isMissing)
+ }
+
+ @Test func keepsWhatTheDeleteDidNotWriteBackEmpty() async throws {
+ let directory = try TemporaryDirectory()
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+ let settings = try PropertyListSerialization.data(
+ fromPropertyList: ["key": "value"],
+ format: .binary,
+ options: 0
+ )
+ let preferences = "home/Library/Preferences/"
+ let withSettings = directory.url.appending(path: preferences + "org.example.settings.plist")
+ let backBefore = try directory.file(
+ preferences + "org.example.before.plist",
+ contents: Self.writtenBack ?? Data()
+ )
+ let linked = directory.url.appending(path: preferences + "org.example.linked.plist")
+ let elsewhere = try directory.file("elsewhere/org.example.linked.plist", contents: Self.writtenBack ?? Data())
+
+ await PreferenceCleanup.forgetDomains(
+ for: [withSettings, backBefore, linked],
+ ownedBy: nil,
+ home: home,
+ host: host
+ ) { domain in
+ switch domain.name {
+ case "org.example.settings": try? settings.write(to: withSettings)
+ case "org.example.before": try? Self.writtenBack?.write(to: backBefore)
+ default: try? FileManager.default.createSymbolicLink(at: linked, withDestinationURL: elsewhere)
+ }
+ }
+
+ #expect(withSettings.isThere)
+ #expect(backBefore.isThere)
+ #expect(linked.isThere)
+ #expect(elsewhere.isThere)
+ }
+
/// The first five names all belong to the global preferences, and Apple gives its own agents one-word domains.
@Test func neverForgetsTheGlobalDomainOrAnAgentsDomain() {
let names = [
diff --git a/SAFETY.md b/SAFETY.md
index b4e38743..b4dee5ce 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -153,9 +153,10 @@ 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: 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.
+What Peel deletes outright holds nothing of yours: such a placeholder, when the move it was made for fails; the folder
+it makes to save an app's settings before a reset, when saving fails before anything is written in it; and the empty
+settings file macOS writes back when Peel forgets a preference domain, as described below. 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:
@@ -210,9 +211,12 @@ Some of what Peel does is not a move to the Trash. Each is here with how it is u
The first three happen after a move, and only for what really moved:
-- **A preference domain is forgotten** (`defaults delete`), or macOS could write the file again from memory. macOS
- then answers that the domain is not found and changes nothing, and a file put back from History is read again at
- once, so History undoes it for an app that has not run since. It is done only for a file that went from your own
+- **A preference domain is forgotten** (`defaults delete`), or macOS could write the file again from memory. While
+ macOS still holds the domain, as it does for a moment after the app quits, it answers by writing the domain back,
+ empty, where the moved file was. Peel deletes that file, which holds nothing, so History can put the real one back:
+ only when nothing was at that name before, the file is yours, and it holds no setting at all. Otherwise macOS
+ answers that the domain is not found and changes nothing. A file put back from History is read again at once, so
+ History undoes it for an app that has not run since. It is done only for a file that went from your own
`~/Library/Preferences`, or, when you reset a sandboxed app, from the Preferences folder in its container. Never
for the copy every account shares in `/Library/Preferences`, never while the app's container still holds its own
settings, never for one of Apple's domains on another app's behalf, never for Peel's own while it runs, and never