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.

The app and peel exclusions no longer overwrite each other's exclusions

Țugui Dragoș6548c0827cb9
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/ExclusionCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/ExclusionCommands.swift
index f86482fd..960f397c 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/ExclusionCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/ExclusionCommands.swift
@@ -15,20 +15,27 @@ struct ExclusionsCommand: AsyncParsableCommand {
/// file aside and silently drop what the user chose. Only the app starts a new list, after warning the user.
static func current(in store: ExclusionStore) async throws -> Exclusions {
let exclusions = await store.load()
- guard !exclusions.isUnreadable else {
- throw CommandFailure("Peel couldn't read its exclusions file, so it won't change it. Open Peel and click Start Over in Settings > Exclusions.")
- }
+ guard !exclusions.isUnreadable else { throw CommandFailure(unreadable) }
return exclusions
}
+ private static let unreadable = "Peel couldn't read its exclusions file, so it won't change it. Open Peel and click Start Over in Settings > Exclusions."
+
/// Returns the bundle identifier of `app`, found by path, bundle identifier, or name, as the other commands do.
static func identifier(of app: String, among apps: [InstalledApp]? = nil) async throws -> String {
let installed = if let apps { apps } else { await AppCatalog.installedApps() }
return try AppLookup.app(matching: app, in: installed).bundleIdentifier
}
- static func save(_ exclusions: Exclusions, in store: ExclusionStore) async throws {
- guard await store.save(exclusions) else {
+ /// Changes the saved list with `transform`, read again and written under the file's lock, so what the app or
+ /// another command saved meanwhile is kept.
+ static func change(in store: ExclusionStore, _ transform: @Sendable (inout Exclusions) -> Void) async throws {
+ switch await store.change(transform) {
+ case .saved:
+ return
+ case .unreadable:
+ throw CommandFailure(unreadable)
+ case .notSaved:
throw CommandFailure("Peel couldn't write its exclusions, so nothing changed.")
}
}
@@ -95,12 +102,17 @@ struct ExclusionsCommand: AsyncParsableCommand {
}
func run(in store: ExclusionStore, among apps: [InstalledApp]? = nil) async throws {
- var exclusions = try await ExclusionsCommand.current(in: store)
- exclusions.paths.formUnion(paths.map { URL(argument: $0).standardizedFileURL })
+ _ = try await ExclusionsCommand.current(in: store)
+ // The app is looked up before the list is changed, since looking it up can take a while.
+ var identifier: String?
if let app {
- exclusions.bundleIdentifiers.insert(try await ExclusionsCommand.identifier(of: app, among: apps))
+ identifier = try await ExclusionsCommand.identifier(of: app, among: apps)
+ }
+ let added = paths.map { URL(argument: $0).standardizedFileURL }
+ try await ExclusionsCommand.change(in: store) { [identifier] exclusions in
+ exclusions.paths.formUnion(added)
+ if let identifier { exclusions.bundleIdentifiers.insert(identifier) }
}
- try await ExclusionsCommand.save(exclusions, in: store)
Output.line("Peel will leave \(Output.count(paths.count + (app == nil ? 0 : 1), "item", "items")) alone.")
}
}
@@ -125,21 +137,25 @@ struct ExclusionsCommand: AsyncParsableCommand {
}
func run(in store: ExclusionStore, among apps: [InstalledApp]? = nil) async throws {
- var exclusions = try await ExclusionsCommand.current(in: store)
- let before = exclusions
- exclusions.paths.subtract(paths.map { URL(argument: $0).standardizedFileURL })
- // First removes `app` exactly as written, so an app that isn't installed can still come off the
- // list. Only when that took off no app is `app` looked up among the installed apps.
+ let before = try await ExclusionsCommand.current(in: store)
+ let removed = Set(paths.map { URL(argument: $0).standardizedFileURL })
+ // `app` comes off exactly as written, so an app that isn't installed can still come off the list. Only
+ // when the list has no such identifier is `app` looked up among the installed apps.
+ var identifiers: Set<String> = []
if let app {
- exclusions.bundleIdentifiers.remove(app)
- if exclusions.bundleIdentifiers == before.bundleIdentifiers, let identifier = try? await ExclusionsCommand.identifier(of: app, among: apps) {
- exclusions.bundleIdentifiers.remove(identifier)
+ if before.bundleIdentifiers.contains(app) {
+ identifiers.insert(app)
+ } else if let identifier = try? await ExclusionsCommand.identifier(of: app, among: apps) {
+ identifiers.insert(identifier)
}
}
- guard exclusions != before else {
+ guard !before.paths.isDisjoint(with: removed) || !before.bundleIdentifiers.isDisjoint(with: identifiers) else {
throw CommandFailure("Peel wasn't leaving that alone. See `peel exclusions list`.")
}
- try await ExclusionsCommand.save(exclusions, in: store)
+ try await ExclusionsCommand.change(in: store) { [identifiers] exclusions in
+ exclusions.paths.subtract(removed)
+ exclusions.bundleIdentifiers.subtract(identifiers)
+ }
Output.line("Peel will treat it like anything else again.")
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift b/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
index fcc09c56..30f04f4d 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
@@ -159,10 +159,53 @@ public struct ExclusionStore: Sendable {
PeelFolder.url.appending(path: "exclusions.json")
}
+ /// What `change(_:)` did.
+ public enum Outcome: Sendable, Equatable {
+ /// The list as it was saved.
+ case saved(Exclusions)
+ /// The saved list cannot be read, so it was left as it is.
+ case unreadable
+ /// The list could not be written. It carries what the list would have been, which the app keeps until it
+ /// quits.
+ case notSaved(Exclusions)
+ }
+
/// Loads the saved list. No file means an empty list. A file that is there but cannot be read gives
/// `.unreadable`, never an empty list, so what the user excluded stays protected.
@concurrent
public func load() async -> Exclusions {
+ read()
+ }
+
+ /// Saves `exclusions` in place of the list, and returns false when they could not be written. A saved file that
+ /// cannot be read is first renamed with `DamagedFile`, never overwritten.
+ @concurrent
+ @discardableResult
+ public func save(_ exclusions: Exclusions) async -> Bool {
+ FileLock.whileHeld(beside: url) { write(exclusions) }
+ }
+
+ /// Changes the saved list with `transform`. The list is read again and written under the file's lock, so what
+ /// another process saved meanwhile, such as `peel exclusions add` while the app runs, is kept. A saved list that
+ /// cannot be read is left as it is, unless `startsOver`: it is then kept under another name and `transform`
+ /// starts a new list, which is what an edit in Settings does and what `peel` never does.
+ @concurrent
+ public func change(
+ startingOverIfUnreadable startsOver: Bool = false,
+ _ transform: @Sendable (inout Exclusions) -> Void
+ ) async -> Outcome {
+ FileLock.whileHeld(beside: url) {
+ var exclusions = read()
+ if exclusions.isUnreadable {
+ guard startsOver else { return .unreadable }
+ exclusions = .none
+ }
+ transform(&exclusions)
+ return write(exclusions) ? .saved(exclusions) : .notSaved(exclusions)
+ }
+ }
+
+ private func read() -> Exclusions {
guard FileManager.default.fileExists(atPath: url.path(percentEncoded: false)) else { return .none }
guard let data = BoundedRead.data(at: url), let saved = try? JSONDecoder().decode(Exclusions.self, from: data) else {
return .unreadable
@@ -170,15 +213,11 @@ public struct ExclusionStore: Sendable {
return saved
}
- /// Saves `exclusions`, and returns false when they could not be written. A saved file that cannot be read
- /// is first renamed with `DamagedFile`, never overwritten.
- @concurrent
- @discardableResult
- public func save(_ exclusions: Exclusions) async -> Bool {
+ private func write(_ exclusions: Exclusions) -> Bool {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
guard let data = try? encoder.encode(exclusions) else { return false }
- if await load().isUnreadable, DamagedFile.setAside(url) == nil { return false }
+ if read().isUnreadable, DamagedFile.setAside(url) == nil { return false }
do {
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try data.write(to: url, options: .atomic)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
index ab5d02d1..349101ab 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
@@ -126,6 +126,80 @@ struct ExclusionsTests {
#expect(await store.load() == exclusions)
}
+ /// The app reads the list at launch, and `peel exclusions` can change it while the app runs. A change reads the
+ /// list again under the file's lock, so what the other one saved meanwhile is kept.
+ @Test func aChangeKeepsWhatAnotherWriterSaved() async throws {
+ let directory = try TemporaryDirectory()
+ let file = directory.url.appending(path: "Peel/exclusions.json")
+ let (app, terminal) = (ExclusionStore(url: file), ExclusionStore(url: file))
+ let (kept, added) = (URL(filePath: "/Users/x/Kept"), URL(filePath: "/Users/x/Added"))
+ _ = await app.load()
+ await terminal.save(Exclusions(paths: [kept]))
+
+ let outcome = await app.change { $0.paths.insert(added) }
+
+ #expect(outcome == .saved(Exclusions(paths: [kept, added])))
+ #expect(await app.load().paths == [kept, added])
+ }
+
+ /// Changes made at once, as two processes can make them, each land.
+ @Test func changesMadeAtOnceAllLand() async throws {
+ let directory = try TemporaryDirectory()
+ let store = ExclusionStore(url: directory.url.appending(path: "Peel/exclusions.json"))
+
+ await withTaskGroup(of: Void.self) { group in
+ for index in 0..<16 {
+ group.addTask { _ = await store.change { $0.paths.insert(URL(filePath: "/Users/x/\(index)")) } }
+ }
+ }
+
+ #expect(await store.load().paths.count == 16)
+ }
+
+ /// A list that cannot be read is left as it is: changing it would throw away what the user chose.
+ @Test func aChangeLeavesAListItCannotReadAsItIs() async throws {
+ let directory = try TemporaryDirectory()
+ let file = try directory.file("exclusions.json", contents: Data("not json".utf8))
+
+ let outcome = await ExclusionStore(url: file).change { $0.bundleIdentifiers.insert("com.example.app") }
+
+ #expect(outcome == .unreadable)
+ #expect(try String(contentsOf: file, encoding: .utf8) == "not json")
+ }
+
+ /// An edit in Settings to a list that cannot be read starts a new list, as Settings says it does, and the old
+ /// file stays beside it under another name.
+ @Test func anEditThatStartsOverKeepsTheListItCannotReadAside() async throws {
+ let directory = try TemporaryDirectory()
+ let file = try directory.file("exclusions.json", contents: Data("not json".utf8))
+
+ let outcome = await ExclusionStore(url: file).change(startingOverIfUnreadable: true) {
+ $0.bundleIdentifiers.insert("com.example.app")
+ }
+
+ #expect(outcome == .saved(Exclusions(bundleIdentifiers: ["com.example.app"])))
+ #expect(await ExclusionStore(url: file).load() == Exclusions(bundleIdentifiers: ["com.example.app"]))
+ let names = try FileManager.default.contentsOfDirectory(atPath: directory.url.path(percentEncoded: false))
+ let aside = try #require(names.first { $0.hasPrefix("exclusions-damaged-") })
+ #expect(try String(contentsOf: directory.url.appending(path: aside), encoding: .utf8) == "not json")
+ }
+
+ /// A change that cannot be written says what the list would have been, so the app can keep it until it quits.
+ @Test func aChangeThatCannotBeWrittenSaysWhatItWouldHaveSaved() async throws {
+ let directory = try TemporaryDirectory()
+ let folder = directory.url.appending(path: "Peel", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let store = ExclusionStore(url: folder.appending(path: "exclusions.json"))
+ await store.save(Exclusions(paths: [URL(filePath: "/Users/x/Kept")]))
+ try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: folder.path(percentEncoded: false))
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: folder.path(percentEncoded: false)) }
+
+ let outcome = await store.change { $0.paths.insert(URL(filePath: "/Users/x/Added")) }
+
+ #expect(outcome == .notSaved(Exclusions(paths: [URL(filePath: "/Users/x/Kept"), URL(filePath: "/Users/x/Added")])))
+ #expect(await store.load().paths == [URL(filePath: "/Users/x/Kept")])
+ }
+
/// An entry that makes no sense is dropped, and the rest of the list is kept.
@Test func keepsTheRestOfAListWithABadEntry() async throws {
let directory = try TemporaryDirectory()
diff --git a/Peel/Model/ExclusionsStore.swift b/Peel/Model/ExclusionsStore.swift
index 38ba901c..129e2f76 100644
--- a/Peel/Model/ExclusionsStore.swift
+++ b/Peel/Model/ExclusionsStore.swift
@@ -14,7 +14,11 @@ final class ExclusionsStore {
private(set) var revision = 0
/// The last change could not be written, so it will not be there after a relaunch.
private(set) var couldNotSave = false
- private var hasLoaded = false
+ /// The changes that could not be written. They stay in force until Peel quits, as Settings says, laid again
+ /// over the list each time it is read, and the next change that is written takes them with it.
+ @ObservationIgnored private var unsaved: [@Sendable (inout Exclusions) -> Void] = []
+ /// The last read or change of the list, which the next one waits for, so they land in the order they were made.
+ @ObservationIgnored private var last: Task<Void, Never>?
/// The revision each page last scanned under. Kept here rather than in the page, because while Settings
/// takes the whole pane, no page is on screen to notice a change.
@ObservationIgnored private var scanned = ScannedRevisions()
@@ -23,14 +27,11 @@ final class ExclusionsStore {
scanned.needsRescan(page, at: revision)
}
- /// Loads the saved list. A page that scanned before it arrived filtered by nothing, so a loaded list that
- /// differs counts as a change.
+ /// Loads the saved list, at launch and whenever Peel comes forward, since `peel exclusions` can change it
+ /// meanwhile. A page that scanned before it arrived filtered by nothing, so a loaded list that differs counts
+ /// as a change.
func load() async {
- let loaded = await store.load()
- hasLoaded = true
- guard loaded != exclusions else { return }
- exclusions = loaded
- revision += 1
+ await inTurn { [self] in show(withUnsaved(await store.load())) }
}
static func isTooBroad(_ url: URL) -> Bool {
@@ -38,55 +39,76 @@ final class ExclusionsStore {
}
func add(paths: [URL]) async {
- var updated = await current()
- updated.paths.formUnion(paths.map { $0.standardizedFileURL })
- await save(updated)
+ let added = paths.map(\.standardizedFileURL)
+ await change { $0.paths.formUnion(added) }
}
func add(bundleIdentifier: String) async {
- var updated = await current()
- updated.bundleIdentifiers.insert(bundleIdentifier)
- await save(updated)
+ await change { $0.bundleIdentifiers.insert(bundleIdentifier) }
}
func remove(paths: [URL]) async {
- var updated = await current()
- updated.paths.subtract(paths.map { $0.standardizedFileURL })
- await save(updated)
+ let removed = paths.map(\.standardizedFileURL)
+ await change { $0.paths.subtract(removed) }
}
func remove(bundleIdentifiers: [String]) async {
- var updated = await current()
- updated.bundleIdentifiers.subtract(bundleIdentifiers)
- await save(updated)
+ await change { $0.bundleIdentifiers.subtract(bundleIdentifiers) }
}
/// Replaces a list that could not be read, which the store keeps under another name.
func startOver() async {
- await save(.none)
+ await inTurn { [self] in
+ couldNotSave = await !store.save(.none)
+ guard !couldNotSave else { return }
+ unsaved = []
+ show(.none)
+ }
}
- /// The list, loaded first if needed: a change made before the saved list is read would overwrite it.
- private func current() async -> Exclusions {
- if !hasLoaded { await load() }
- return exclusions
+ /// Changes the saved list, which the store reads again under the file's lock, so a change made in Terminal
+ /// meanwhile is kept. A change to a list that cannot be read starts a new one, as Settings says.
+ private func change(_ transform: @escaping @Sendable (inout Exclusions) -> Void) async {
+ await inTurn { [self] in
+ let changes = unsaved + [transform]
+ switch await store.change(startingOverIfUnreadable: true, { list in changes.forEach { $0(&list) } }) {
+ case .saved(let saved):
+ unsaved = []
+ couldNotSave = false
+ show(saved)
+ case .notSaved(let changed):
+ unsaved.append(transform)
+ couldNotSave = true
+ show(changed)
+ case .unreadable:
+ show(.unreadable)
+ }
+ }
}
- /// The last write, which the next one waits for. Writes land one at a time in the order they were made,
- /// so an older list can never overwrite a newer one.
- private var writing: Task<Void, Never>?
-
- private func save(_ updated: Exclusions) async {
- // Built anew, which clears `isUnreadable`, since the user has just edited the list.
- exclusions = Exclusions(paths: updated.paths, bundleIdentifiers: updated.bundleIdentifiers)
- revision += 1
- let saving = exclusions
- let previous = writing
- let write = Task { [store] in
+ /// Runs `operation` once the read or change before it has landed.
+ private func inTurn(_ operation: @escaping () async -> Void) async {
+ let previous = last
+ let current = Task {
await previous?.value
- return await store.save(saving)
+ await operation()
}
- writing = Task { _ = await write.value }
- couldNotSave = await !write.value
+ last = current
+ await current.value
+ }
+
+ /// `list` with the changes that could not be written laid over it. They started a new list if the saved one
+ /// could not be read.
+ private func withUnsaved(_ list: Exclusions) -> Exclusions {
+ guard !unsaved.isEmpty else { return list }
+ var changed = list.isUnreadable ? .none : list
+ unsaved.forEach { $0(&changed) }
+ return changed
+ }
+
+ private func show(_ list: Exclusions) {
+ guard list != exclusions else { return }
+ exclusions = list
+ revision += 1
}
}
diff --git a/Peel/PeelApp.swift b/Peel/PeelApp.swift
index 1ad2e16e..74539699 100644
--- a/Peel/PeelApp.swift
+++ b/Peel/PeelApp.swift
@@ -123,6 +123,8 @@ struct PeelApp: App {
private func followActivations() async {
for await _ in NotificationCenter.default.notifications(named: NSApplication.didBecomeActiveNotification) {
helper.refresh()
+ // `peel exclusions` may have changed the list while another app was in front.
+ Task { await exclusions.load() }
// Home's checks run again whatever page is showing: permissions change in System Settings, and the
// badge on Home in the sidebar shows a missing one.
Task { await home.refresh(helper: helper) }