Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Refuse to list orphaned files while some apps can't be read
Țugui Dragoș8975ddfa706e
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swiftindex ebb6afe6..3a589a34 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift@@ -64,7 +64,9 @@ struct OrphansCommand: AsyncParsableCommand {}func run() async throws {- let apps = await AppCatalog.installedApps()+ let catalog = await AppCatalog.scan()+ if let refusal = Self.refusal(for: catalog) { throw refusal }+ let apps = catalog.apps// The same signals the app uses (the apps Peel remembers and the apps running), so both judge these// files alike. The memory of apps is only read here, never written.let remembered = await AppMemory().load()@@ -105,6 +107,14 @@ struct OrphansCommand: AsyncParsableCommand {}}+ /// Why nothing is listed when some apps could not be read: their files would look orphaned.+ static func refusal(for catalog: AppScan) -> CommandFailure? {+ guard !catalog.unreadable.isEmpty else { return nil }+ let listed = Output.list(catalog.unreadable.map { Output.plain(Output.path($0)) })+ let access = catalog.needsFullDiskAccess ? " Give your terminal app Full Disk Access in System Settings." : ""+ return CommandFailure("Peel couldn't read \(listed), so it can't tell which apps are installed. Nothing is listed, since the files of an app it can't see would look orphaned.\(access)")+ }+static func report(for scan: OrphanScan) -> Report {Report(groups: scan.groups.map { group indiff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppCatalog.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppCatalog.swiftindex c32deec9..c69539d0 100644--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppCatalog.swift+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppCatalog.swift@@ -2,10 +2,20 @@ public import Foundationinternal import PeelPrivilegedimport Synchronization+/// One reading of the folders apps are kept in.+public struct AppScan: Sendable, Equatable {+ public let apps: [InstalledApp]+ /// What is there and could not be read: a folder of apps, an app, or the list of folders the person chose. The+ /// apps in it are missing from `apps`, so nothing can be called orphaned while this is not empty.+ public let unreadable: [URL]+ /// Whether Full Disk Access would open what could not be read.+ public let needsFullDiskAccess: Bool+}+public enum AppCatalog {/// Where Peel looks for apps: the Applications folders and the folders the person chose (`AppFolders`).public static var defaultDirectories: [URL] {- directories(adding: AppFolders().load())+ directories(adding: AppFolders().load() ?? [])}static var standardDirectories: [URL] {@@ -52,21 +62,46 @@ public enum AppCatalog {.max { $0.path.count < $1.path.count }?.app}- @concurrentpublic static func installedApps(in directories: [URL] = defaultDirectories) async -> [InstalledApp] {- let bundles = Set(directories.flatMap { appBundles(in: $0) })+ await scan(in: directories).apps+ }- let apps = await withTaskGroup(of: InstalledApp?.self) { group in+ /// Reads the apps in the Applications folders and in the folders the person chose. When the list of chosen+ /// folders cannot be read, the list itself is among what could not be read.+ @concurrent+ public static func scan(choices: AppFolders = AppFolders()) async -> AppScan {+ guard let chosen = choices.load() else {+ let standard = await scan(in: standardDirectories)+ return AppScan(+ apps: standard.apps,+ unreadable: standard.unreadable + [choices.url],+ needsFullDiskAccess: standard.needsFullDiskAccess+ )+ }+ return await scan(in: directories(adding: chosen))+ }++ @concurrent+ public static func scan(in directories: [URL]) async -> AppScan {+ let walks = directories.map { appBundles(in: $0) }+ let bundles = Set(walks.flatMap(\.bundles))++ let read = await withTaskGroup(of: (bundle: URL, app: InstalledApp?).self) { group infor bundle in bundles {- group.addTask { Reading.of(bundle) }- }- return await group.reduce(into: [InstalledApp]()) { apps, app in- if let app { apps.append(app) }+ group.addTask { (bundle, Reading.of(bundle)) }}+ return await group.reduce(into: [(bundle: URL, app: InstalledApp?)]()) { $0.append($1) }}Reading.forget(inside: directories, except: bundles)- return sorted(apps)+ let closedApps = read.filter { $0.app == nil && AppInspector.isClosed($0.bundle) }.map(\.bundle)+ let unreadable = (walks.flatMap(\.unreadable) + closedApps)+ .sorted { $0.path(percentEncoded: false) < $1.path(percentEncoded: false) }+ return AppScan(+ apps: sorted(read.compactMap(\.app)),+ unreadable: unreadable,+ needsFullDiskAccess: unreadable.contains { FullDiskAccess.canList($0) == .missing }+ )}/// Whether what was read about `bundle` is kept, so the next reading of its folder does not read it again.@@ -149,12 +184,19 @@ public enum AppCatalog {}}- static func appBundles(in directory: URL, maximumDepth: Int = 3) -> [URL] {+ /// The apps in `directory`, three levels deep, and the folders in it that are there and could not be read. A+ /// folder that is not there, such as an Applications folder nobody made, holds no app.+ static func appBundles(in directory: URL, maximumDepth: Int = 3) -> (bundles: [URL], unreadable: [URL]) {+ var unreadable: [URL] = []guard let enumerator = FileManager.default.enumerator(at: directory,includingPropertiesForKeys: [.isDirectoryKey],- options: [.skipsHiddenFiles, .skipsPackageDescendants]- ) else { return [] }+ options: [.skipsHiddenFiles, .skipsPackageDescendants],+ errorHandler: { url, error in+ if (error as? CocoaError)?.code != .fileReadNoSuchFile { unreadable.append(url) }+ return true+ }+ ) else { return ([], directory.isMissing ? [] : [directory]) }var bundles: [URL] = []for case let url as URL in enumerator {@@ -164,7 +206,7 @@ public enum AppCatalog {enumerator.skipDescendants()}}- return bundles+ return (bundles, unreadable)}private static func byName(_ lhs: InstalledApp, _ rhs: InstalledApp) -> Bool {diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppFolders.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppFolders.swiftindex cc2d115e..9940dfb2 100644--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppFolders.swift+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppFolders.swift@@ -21,8 +21,9 @@ public struct AppFolders: Sendable {PeelFolder.url.appending(path: "app-folders.json")}- public func load() -> [URL] {- FileLock.whileHeld(beside: url) { read() ?? [] }+ /// The folders chosen, or nil when the file is there and cannot be read: the apps in them are then not known.+ public func load() -> [URL]? {+ FileLock.whileHeld(beside: url) { url.isMissing ? [] : read() }}/// Adds `folders`. False when they could not be saved, or when the file is there and cannot be read, sincediff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swiftindex d97892ab..a24d1428 100644--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift@@ -120,6 +120,13 @@ public enum AppInspector {return try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]}+ /// Whether the bundle's Info.plist is there and macOS will not let Peel read it, so nothing can be told about+ /// the app.+ static func isClosed(_ bundle: URL) -> Bool {+ let info = bundle.appending(path: "Contents/Info.plist")+ return !info.isMissing && BoundedRead.data(at: info) == nil+ }+/// The name Finder shows for a bundle, in the user's language when the app translates its name.public static func displayName(of url: URL) -> String {let name = FileManager.default.displayName(atPath: url.path(percentEncoded: false))diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swiftindex 2e615f67..8a0336e9 100644--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift@@ -24,9 +24,7 @@ extension RememberedApp {let names = PathComponents.of(lastPath)let isOnADiskNotConnected = names.count > 2 && names[0] == "Volumes"&& URL(filePath: "/Volumes/\(names[1])").isMissing- let info = place.appending(path: "Contents/Info.plist")- let isClosedToPeel = !info.isMissing && BoundedRead.data(at: info) == nil- guard isOnADiskNotConnected || isClosedToPeel else { return nil }+ guard isOnADiskNotConnected || AppInspector.isClosed(place) else { return nil }return InstalledApp(url: place, bundleIdentifier: bundleIdentifier, name: name, teamIdentifier: teamIdentifier)}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppFoldersTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppFoldersTests.swiftindex 02e1132a..45c5cdc2 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppFoldersTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppFoldersTests.swift@@ -22,13 +22,26 @@ struct AppFoldersTests {let directory = try TemporaryDirectory()let folders = AppFolders(url: directory.url.appending(path: "app-folders.json"))let studio = directory.url.appending(path: "Studio Apps", directoryHint: .isDirectory)- #expect(folders.load().isEmpty)+ #expect(folders.load() == [])#expect(folders.add([studio]))- #expect(folders.load().map(\.lastPathComponent) == ["Studio Apps"])- #expect(AppCatalog.directories(adding: folders.load()).count == AppCatalog.standardDirectories.count + 1)+ #expect(folders.load()?.map(\.lastPathComponent) == ["Studio Apps"])+ let chosen = try #require(folders.load())+ #expect(AppCatalog.directories(adding: chosen).count == AppCatalog.standardDirectories.count + 1)#expect(folders.remove([studio]))- #expect(folders.load().isEmpty)+ #expect(folders.load() == [])+ }++ @Test(.permissionsHold) func aListThatCannotBeReadIsNoEmptyList() throws {+ let directory = try TemporaryDirectory()+ let damaged = try directory.file("damaged.json", contents: Data("not a list".utf8))+ let closed = try directory.file("closed.json", contents: Data("[]".utf8))+ try directory.setPermissions(0o000, of: "closed.json")+ defer { try? directory.setPermissions(0o644, of: "closed.json") }++ #expect(AppFolders(url: damaged).load() == nil)+ #expect(AppFolders(url: closed).load() == nil)+ #expect(AppFolders(url: directory.url.appending(path: "missing.json")).load() == [])}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swiftindex 61cc897b..fedf2c3d 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift@@ -145,6 +145,33 @@ struct AppInspectorTests {#expect(AppCatalog.remembers(two.appending(path: "Two.app")))}+ @Test(.permissionsHold) func saysWhatItCouldNotReadAndNotWhatIsNotThere() async throws {+ let directory = try TemporaryDirectory()+ try plist(["CFBundleIdentifier": "org.example.one", "CFBundleName": "One"], at: "Open/One.app/Contents/Info.plist", in: directory)+ try plist(["CFBundleIdentifier": "org.example.sealed", "CFBundleName": "Sealed"], at: "Open/Sealed.app/Contents/Info.plist", in: directory)+ try plist(["CFBundleIdentifier": "org.example.two", "CFBundleName": "Two"], at: "Closed/Two.app/Contents/Info.plist", in: directory)+ try directory.setPermissions(0o000, of: "Closed")+ try directory.setPermissions(0o000, of: "Open/Sealed.app/Contents/Info.plist")+ defer {+ try? directory.setPermissions(0o755, of: "Closed")+ try? directory.setPermissions(0o644, of: "Open/Sealed.app/Contents/Info.plist")+ }++ let scan = await AppCatalog.scan(in: ["Open", "Closed", "Missing"].map { directory.url.appending(path: $0) })++ #expect(scan.apps.map(\.bundleIdentifier) == ["org.example.one"])+ #expect(scan.unreadable.map(\.lastPathComponent) == ["Closed", "Sealed.app"])+ }++ @Test func aListOfFoldersThatCannotBeReadIsAmongWhatWasNotRead() async throws {+ let directory = try TemporaryDirectory()+ let list = try directory.file("app-folders.json", contents: Data("not a list".utf8))++ let scan = await AppCatalog.scan(choices: AppFolders(url: list))++ #expect(scan.unreadable.contains(list))+ }+/// A launchd plist too large to be a job is not read, and neither is a link to something that is not a file/// (reading `/dev/zero` never ends). A link to a real job is followed.@Test func readsThroughALinkedLaunchdJobAndRefusesWhatIsNoJob() throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swiftindex a1cd797b..a07e2bf8 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift@@ -510,6 +510,16 @@ struct FileCommandTests {#expect(report["unreadableLocations"] as? [String] == ["/Users/me/Library/Containers"])}+ @Test func orphansListsNothingWhileAnAppFolderCannotBeRead() {+ let studio = URL(filePath: "/Volumes/Studio/Apps", directoryHint: .isDirectory)++ #expect(OrphansCommand.refusal(for: AppScan(apps: [], unreadable: [], needsFullDiskAccess: false)) == nil)+ let refusal = OrphansCommand.refusal(for: AppScan(apps: [], unreadable: [studio], needsFullDiskAccess: false))+ #expect(refusal?.description == "Peel couldn't read /Volumes/Studio/Apps, so it can't tell which apps are installed. Nothing is listed, since the files of an app it can't see would look orphaned.")+ let locked = OrphansCommand.refusal(for: AppScan(apps: [], unreadable: [studio], needsFullDiskAccess: true))+ #expect(locked?.description.hasSuffix(" Give your terminal app Full Disk Access in System Settings.") == true)+ }+/// A chosen folder Peel didn't look in, such as a repository, is said, so an empty answer is not read as none.@Test func saysWhichFoldersItDidNotLookIn() {let skipped = URL(filePath: "/Users/me/Projects/app", directoryHint: .isDirectory)diff --git a/Peel/Model/AppLibrary.swift b/Peel/Model/AppLibrary.swiftindex 0a23a013..65f4b0f8 100644--- a/Peel/Model/AppLibrary.swift+++ b/Peel/Model/AppLibrary.swift@@ -77,7 +77,7 @@ final class AppLibrary {private(set) var hasLoaded = false/// The folders the person chose for apps, beside the Applications folders. `PeelApp` watches them and reads the/// apps again when they change.- private(set) var folders = AppFolders().load()+ private(set) var folders = AppFolders().load() ?? []private(set) var couldNotSaveFolders = falseprivate(set) var updateStatuses: [InstalledApp.ID: UpdateStatus] = [:] {didSet { updatesRevision += 1 }@@ -211,7 +211,7 @@ final class AppLibrary {private func changeFolders(_ change: (AppFolders) -> Bool) {let store = AppFolders()couldNotSaveFolders = !change(store)- folders = store.load()+ folders = store.load() ?? []}/// Reads the folders again without emptying the list first, so an app installed while Peel is open