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.

Let This Belongs To name a command outside Homebrew too

Țugui Dragoș46a8779b5880
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index dd57af4b..fc637a1c 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -404,9 +404,10 @@ macOS asks the user to approve it once. It talks to the app over XPC.
(`nameKey`). An app macOS knows on another disk that claims something is remembered too
(`OrphanScan.appsOnOtherDisks`, `Disks`), so its files stay its own while that disk isn't connected, and a link into
an app on such a disk is not one into an app that is gone. A group the person gave to an app or to a command-line
- tool Homebrew installed (`OrphanOwner`) stays out while that app or tool is installed (`OrphanOwners.given`), the
- tools read from the Cellar as Homebrew counts them (`Homebrew.installedFormulae`) right before each scan, in the app
- and in `peel orphans` alike.
+ tool (`OrphanOwner`) stays out while that app or tool is installed (`OrphanOwners.given`), the tools read right before
+ each scan (`InstalledTools.read`), in the app and in `peel orphans` alike: Homebrew's formulae from its Cellar as
+ Homebrew counts them (`Homebrew.installedFormulae`), and the commands in the tool folders Intel Software reads
+ (`CommandLineTools`), a command that leads into an app or into the Cellar left to its app or formula.
- **Intel Software.** `IntelInspector` judges by the code itself: what a bundle runs, or a file, is Intel only when
its Mach-O slices are x86_64 alone (`MachOHeader`), and a file found inside an app or beside a printer driver counts
only when it is a program (`MH_EXECUTE`), since a library runs in whatever loads it. It looks at the installed apps
@@ -514,7 +515,7 @@ where a Homebrew install takes them from.
| `~/Library/Application Support/Peel/digests.bin` | What Duplicates already read, so an unchanged file isn't read again. |
| `~/Library/Application Support/Peel/apps.json` | The apps Peel has seen, and those macOS knows on another disk that claimed a file, kept once they are gone or out of reach, so Orphaned Files can name what they left (`AppMemory`). |
| `~/Library/Application Support/Peel/teams.json` | Which team signs each app, so a change of signer can be told (`TeamRegistry`). |
-| `~/Library/Application Support/Peel/orphan-owners.json` | The orphaned files the user said belong to an app, or to a command-line tool Homebrew installed, by its formula (`OrphanOwner`). |
+| `~/Library/Application Support/Peel/orphan-owners.json` | The orphaned files the user said belong to an app, to a command-line tool Homebrew installed, by its formula, or to a command in the tool folders, by its name (`OrphanOwner`). |
| `~/Library/Application Support/Peel/left-for-an-administrator.json` | What an uninstall left that only an administrator can move, from a place the helper doesn't serve, so Orphaned Files lists it under Needs an Administrator once the app is gone. |
| `~/Library/Application Support/Peel/dock-tiles.json` | The Dock icons an uninstall took out, and where each was, so History puts them back with their app. |
| `~/Library/Application Support/Peel/app-folders.json` | The folders the user chose for Peel to look for apps in, beside the Applications folders. |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 52cdd8f4..b1ebf2d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,8 +9,9 @@ its changes the way [Keep a Changelog](https://keepachangelog.com/) suggests.
#### Orphaned Files
-- This Belongs To… also offers the command-line tools Homebrew installed, so what a tool keeps under a dotted name
- stays out of the list while that tool is installed. Settings > Exclusions shows the tool beside its group.
+- This Belongs To… also offers command-line tools: the ones Homebrew installed, and the commands in `/usr/local/bin`,
+ MacPorts' `/opt/local/bin`, and your home's `bin` and `.local/bin`. What a tool keeps under a dotted name stays out of
+ the list while that tool is installed, and Settings > Exclusions shows the tool beside its group.
### Fixed
diff --git a/GUIDE.md b/GUIDE.md
index e6c03354..b8e81f16 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -397,8 +397,9 @@ It sets up the command line as well:
page the folders named exactly with its identifier, such as its caches, and an update it downloaded; to keep its
other files, such as plug-ins or a folder named after it, exclude them too. Add them in
Settings > Exclusions, or Control-click a row and choose Exclude from Peel. In Orphaned Files, Control-click a
- group and choose This Belongs To…, and Peel stops listing it while the app, or the command-line tool from Homebrew,
- you chose is installed.
+ group and choose This Belongs To…, and Peel stops listing it while the app or the command-line tool you chose is
+ installed: one Homebrew installed, or a command in `/usr/local/bin`, MacPorts' `/opt/local/bin`, or your home's `bin`
+ and `.local/bin`.
## Work your way
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
index 74460e35..920b6f2b 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
@@ -108,14 +108,14 @@ struct OrphansCommand: AsyncParsableCommand {
let exclusions = await UnreadableExclusions.load()
let scanner = OrphanScanner(exclusions: exclusions)
let owners = OrphanOwners().load()
- let formulae = await Homebrew.installedFormulae()
+ let tools = await InstalledTools.read()
let scan = await ProgressLine.counting {
await scanner.scan(
installedApps: apps,
remembered: remembered,
running: running,
owners: owners ?? [:],
- installedFormulae: formulae,
+ tools: tools,
leftForAnAdministrator: await LeftForAnAdministrator().load()
)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift b/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
index 2363218c..763eb4ac 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
@@ -100,6 +100,11 @@ public enum IntelInspector {
]
}
+ /// The folders a command is run from by name: the tool folders but `libexec`, whose helpers nobody calls.
+ static func commandDirectories(_ environment: SearchEnvironment) -> [String] {
+ toolDirectories(environment).flatMap(\.folders).filter { !$0.hasSuffix("/libexec") }
+ }
+
/// Folders inside an app that hold code of its own, as processes or as plug-ins the app loads, so an Intel-only one
/// there needs Rosetta even when the app doesn't.
///
@@ -283,12 +288,14 @@ public enum IntelInspector {
for (folders, place) in toolDirectories(environment) {
for tool in tools(in: folders, unreadable: &unreadable)
- where !Task.isCancelled && !exclusions.excludes(tool.url) {
- let path = PathPattern.comparablePath(of: tool.url)
+ where !Task.isCancelled && !exclusions.excludes(tool.program) {
+ let path = PathPattern.comparablePath(of: tool.program)
guard !listed.contains(where: { PathComponents.isPath(path, atOrInside: $0) }) else { continue }
- guard isIntelOnly(executable: tool.url, unreadable: &unreadable), isNew(tool.url) else { continue }
+ guard isIntelOnly(executable: tool.program, unreadable: &unreadable), isNew(tool.program) else {
+ continue
+ }
findings.append(IntelFinding(
- url: tool.url,
+ url: tool.program,
kind: .commandLineTool,
name: tool.name,
owner: nil,
@@ -558,23 +565,25 @@ public enum IntelInspector {
return programs
}
- /// The programs the commands in `directories` run, each under the command's name. A command is often a link,
- /// as every one a Homebrew in `/usr/local` makes into its `Cellar`, and the program it leads to is what runs.
- /// `isDataless` stands in for a program a file provider keeps only in the cloud, which no test can make. Such a
- /// program is left unread, since reading its header would download it.
+ /// The commands in `directories`, each with the program it runs. A command is often a link, as every one a
+ /// Homebrew in `/usr/local` makes into its `Cellar`, and the program it leads to is what runs. `isDataless` stands
+ /// in for a program a file provider keeps only in the cloud, which no test can make. Such a program is left
+ /// unread, since reading its header would download it.
static func tools(
in directories: [String],
unreadable: inout [URL],
isDataless: (URL) -> Bool = FileSize.isDataless(_:)
- ) -> [(name: String, url: URL)] {
- var tools: [(name: String, url: URL)] = []
+ ) -> [(name: String, command: URL, program: URL)] {
+ var tools: [(name: String, command: URL, program: URL)] = []
for directory in directories {
let folder = URL(filePath: directory, directoryHint: .isDirectory)
for command in entries(of: folder, unreadable: &unreadable) {
let program = command.resolvingSymlinksInPath()
var info = stat()
if stat(program.path(percentEncoded: false), &info) == 0 {
- if isRunnable(info), !isDataless(program) { tools.append((command.lastPathComponent, program)) }
+ if isRunnable(info), !isDataless(program) {
+ tools.append((command.lastPathComponent, command, program))
+ }
} else if ![ENOENT, ENOTDIR, ELOOP].contains(errno),
let place = FileAccess.refusedFolder(program.deletingLastPathComponent()) {
unreadable.append(place)
diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
index 393d3007..08980f04 100644
--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
@@ -911,10 +911,17 @@ public enum Homebrew {
@concurrent
public static func installedFormulae(asking answers: Answers = Answers()) async -> Set<String>? {
guard executableURL != nil else { return refusedInAUsualPlace() == nil ? [] : nil }
- guard let cellar = await answers.answer(["--cellar"]).flatMap(folder(answering:)) else { return nil }
+ guard let cellar = await cellar(asking: answers) else { return nil }
return formulae(inCellar: cellar)
}
+ /// Where Homebrew keeps its formulae, as it answers (`brew --cellar`, which `brew.sh` answers without Ruby), or
+ /// nil where no `brew` runs or it doesn't answer.
+ public static func cellar(asking answers: Answers = Answers()) async -> URL? {
+ guard executableURL != nil else { return nil }
+ return await answers.answer(["--cellar"]).flatMap(folder(answering:))
+ }
+
static func formulae(inCellar cellar: URL) -> Set<String>? {
let racks: [String]
do {
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/CommandLineTools.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/CommandLineTools.swift
new file mode 100644
index 00000000..1165d3b2
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/CommandLineTools.swift
@@ -0,0 +1,41 @@
+public import Foundation
+internal import PeelPrivileged
+
+/// The commands in the folders tools are put in by hand or by a package manager other than Homebrew: the tool folders
+/// Intel Software reads (`IntelInspector.toolDirectories`) but `libexec`, whose helpers nobody runs by name.
+public struct CommandLineTools: Sendable {
+ public struct Command: Sendable, Hashable, Identifiable {
+ public let name: String
+ public let url: URL
+
+ public var id: URL { url }
+ }
+
+ /// Every command's name, which keeps a group given to one out of Orphaned Files.
+ public let names: Set<String>
+ /// The commands a person may name as an owner: not one leading into an app, whose owner is the app, nor into
+ /// Homebrew's Cellar, whose owner is the formula. By name, then by place.
+ public let offered: [Command]
+
+ /// Nil when a tool folder is there and can't be listed: then what is installed isn't known.
+ public static func read(environment: SearchEnvironment = .current, cellar: URL?) -> CommandLineTools? {
+ var unreadable: [URL] = []
+ let tools = IntelInspector.tools(in: IntelInspector.commandDirectories(environment), unreadable: &unreadable)
+ guard unreadable.isEmpty else { return nil }
+ let cellarPath = cellar.map { PathPattern.comparablePath(of: $0) }
+ let offered = tools.filter { tool in
+ let program = PathPattern.comparablePath(of: tool.program)
+ return !tool.program.pathComponents.contains { $0.hasSuffix(".app") }
+ && !(cellarPath.map { PathComponents.isPath(program, atOrInside: $0) } ?? false)
+ }
+ return CommandLineTools(
+ names: Set(tools.map(\.name)),
+ offered: offered.map { Command(name: $0.name, url: $0.command) }.sorted {
+ let names = $0.name.localizedStandardCompare($1.name)
+ return names == .orderedSame
+ ? $0.url.path(percentEncoded: false) < $1.url.path(percentEncoded: false)
+ : names == .orderedAscending
+ }
+ )
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/Orphan.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/Orphan.swift
index 88bd632c..116b0085 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/Orphan.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/Orphan.swift
@@ -121,13 +121,13 @@ public struct OrphanScan: Sendable {
keeping { $0.id != id }
}
- /// The same scan without the groups `owners` give to an app of `installedApps` or a formula of
- /// `installedFormulae` (`OrphanOwners.given`), for a scan that ran while the person gave one away.
+ /// The same scan without the groups `owners` give to an app of `installedApps` or a tool of `tools`
+ /// (`OrphanOwners.given`), for a scan that ran while the person gave one away.
public func leavingOut(
- given owners: [String: OrphanOwner], installedApps: [InstalledApp], installedFormulae: Set<String>?
+ given owners: [String: OrphanOwner], installedApps: [InstalledApp], tools: InstalledTools
) -> OrphanScan {
let here = Set(installedApps.compactMap { $0.bundleIdentifier?.lowercased() })
- let given = OrphanOwners.given(owners, apps: here, formulae: installedFormulae)
+ let given = OrphanOwners.given(owners, apps: here, tools: tools)
return keeping { !OrphanScanner.isInAGroup($0.identifier, among: given) }
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanOwners.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanOwners.swift
index 4892f3e0..99bc0442 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanOwners.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanOwners.swift
@@ -1,25 +1,32 @@
public import Foundation
internal import PeelPrivileged
-/// What a group of orphaned files belongs to, as the person said: an app, by its bundle identifier, or a command-line
-/// tool Homebrew installed, by the name of its formula.
+/// What a group of orphaned files belongs to, as the person said: an app, by its bundle identifier, a command-line
+/// tool Homebrew installed, by the name of its formula, or a command in the tool folders (`CommandLineTools`), by name.
public enum OrphanOwner: Sendable, Hashable {
case app(String)
case formula(String)
+ case command(String)
}
extension OrphanOwner: Codable {
private enum CodingKeys: String, CodingKey {
case formula
+ case command
}
/// An app is written as its bundle identifier alone, as every list written before tools could be named, and a
- /// formula under its own key.
+ /// formula or a command under its own key.
public init(from decoder: any Decoder) throws {
if let identifier = try? decoder.singleValueContainer().decode(String.self) {
self = .app(identifier)
+ return
+ }
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ if let name = try container.decodeIfPresent(String.self, forKey: .formula) {
+ self = .formula(name)
} else {
- self = .formula(try decoder.container(keyedBy: CodingKeys.self).decode(String.self, forKey: .formula))
+ self = .command(try container.decode(String.self, forKey: .command))
}
}
@@ -31,10 +38,42 @@ extension OrphanOwner: Codable {
case .formula(let name):
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .formula)
+ case .command(let name):
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(name, forKey: .command)
}
}
}
+/// What is installed on this Mac that a group of orphaned files can belong to besides an app: Homebrew's formulae and
+/// the commands in the tool folders. A kind that isn't known is nil, and a group given to one of it stays out.
+public struct InstalledTools: Sendable {
+ public var formulae: Set<String>?
+ public var commands: Set<String>?
+ /// The commands a person may name, for a chooser.
+ public var offeredCommands: [CommandLineTools.Command]
+
+ public init(
+ formulae: Set<String>? = nil, commands: Set<String>? = nil, offeredCommands: [CommandLineTools.Command] = []
+ ) {
+ self.formulae = formulae
+ self.commands = commands
+ self.offeredCommands = offeredCommands
+ }
+
+ public static let notKnown = InstalledTools()
+
+ /// What is installed now, read right before a scan: Homebrew's Cellar, asked once, gives its formulae and keeps
+ /// its linked commands out of those offered.
+ public static func read(environment: SearchEnvironment = .current) async -> InstalledTools {
+ let answers = Homebrew.Answers()
+ let cellar = await Homebrew.cellar(asking: answers)
+ let formulae = await Homebrew.installedFormulae(asking: answers)
+ let commands = CommandLineTools.read(environment: environment, cellar: cellar)
+ return InstalledTools(formulae: formulae, commands: commands?.names, offeredCommands: commands?.offered ?? [])
+ }
+}
+
/// The orphaned files the person said belong to an app or a command-line tool, by the identifier of their group, so
/// Orphaned Files stops listing them while that app or tool is installed. It only ever takes rows out of the list:
/// nothing is moved.
@@ -83,17 +122,16 @@ public struct OrphanOwners: Sendable {
change { owners in groups.forEach { owners[$0.lowercased()] = nil } }
}
- /// The groups, lowercased, whose owner is on this Mac: an app among `apps`, the installed bundle identifiers, or a
- /// formula among `formulae`, the installed ones. While the formulae aren't known, every group given to one stays
- /// out, since the person's word stands until Peel knows better.
- public static func given(
- _ owners: [String: OrphanOwner], apps: Set<String>, formulae: Set<String>?
- ) -> Set<String> {
+ /// The groups, lowercased, whose owner is on this Mac: an app among `apps`, the installed bundle identifiers, or
+ /// a formula or a command among `tools`. While a kind of tool isn't known, every group given to one stays out,
+ /// since the person's word stands until Peel knows better.
+ public static func given(_ owners: [String: OrphanOwner], apps: Set<String>, tools: InstalledTools) -> Set<String> {
Set(
owners.filter { _, owner in
switch owner {
case .app(let identifier): apps.contains(identifier.lowercased())
- case .formula(let name): formulae?.contains(name) ?? true
+ case .formula(let name): tools.formulae?.contains(name) ?? true
+ case .command(let name): tools.commands?.contains(name) ?? true
}
}
.keys.map { $0.lowercased() }
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
index 1fc6c5d3..dd399377 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
@@ -64,14 +64,14 @@ public struct OrphanScanner: Sendable {
/// left it. `running` is what runs now, known by its bundle identifier: a helper or an agent can keep a
/// folder that no app bundle claims, and while it runs, its group is marked unsure. `owners` are the groups the
/// person said belong to an app or a command-line tool (`OrphanOwners`), left out while that app is installed or
- /// that tool is among `installedFormulae`, what Homebrew has installed, or while those aren't known (nil).
+ /// that tool is among `tools`, what is installed, or while its kind isn't known.
@concurrent
public func scan(
installedApps: [InstalledApp],
remembered: [RememberedApp] = [],
running: [RunningCopies.Process] = [],
owners: [String: OrphanOwner] = [:],
- installedFormulae: Set<String>? = nil,
+ tools: InstalledTools = .notKnown,
leftForAnAdministrator records: [LeftForAnAdministrator.Record] = []
) async -> OrphanScan {
let systemApps = if let systemApps { systemApps } else { await AppCatalog.systemApps.value }
@@ -181,7 +181,7 @@ public struct OrphanScanner: Sendable {
)
let folders = manifestFolders
let loadedByOtherApps = Plugins.LoadedByOtherApps(environment: environment)
- let given = OrphanOwners.given(owners, apps: here, formulae: installedFormulae)
+ let given = OrphanOwners.given(owners, apps: here, tools: tools)
let kept = found.compactMap { entry -> (identifier: String, item: OrphanItem, holds: Bool?)? in
guard !exclusions.excludes(entry.item.url), !exclusions.excludes(bundleIdentifier: entry.identifier),
!Self.isInAGroup(entry.identifier, among: given),
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineToolsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineToolsTests.swift
new file mode 100644
index 00000000..abf41e2f
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineToolsTests.swift
@@ -0,0 +1,53 @@
+import Foundation
+@testable import PeelCore
+import Testing
+
+struct CommandLineToolsTests {
+ @Test func offersTheCommandsOfTheToolFoldersButAnAppsAndHomebrews() throws {
+ let directory = try TemporaryDirectory()
+ let script = Data("#!/bin/sh\n".utf8)
+ for path in ["root/usr/local/bin/kav", "root/usr/local/sbin/served", "root/opt/local/bin/ported", "home/bin/mine",
+ "home/.local/bin/mytool", "root/usr/local/libexec/helper", "root/Applications/Dock.app/Contents/MacOS/dock",
+ "root/usr/local/Cellar/jq/1.7/bin/jq"] {
+ try directory.setPermissions(0o755, of: try directory.file(path, contents: script))
+ }
+ try directory.file("root/usr/local/bin/notes.txt", contents: script)
+ try directory.directory("root/usr/local/bin/.lock")
+ let bin = directory.url.appending(path: "root/usr/local/bin", directoryHint: .isDirectory)
+ try FileManager.default.createSymbolicLink(
+ at: bin.appending(path: "dock"),
+ withDestinationURL: directory.url.appending(path: "root/Applications/Dock.app/Contents/MacOS/dock")
+ )
+ try FileManager.default.createSymbolicLink(atPath: bin.appending(path: "jq").path(percentEncoded: false),
+ withDestinationPath: "../Cellar/jq/1.7/bin/jq")
+ try FileManager.default.createSymbolicLink(atPath: bin.appending(path: "gone").path(percentEncoded: false),
+ withDestinationPath: "/nowhere/gone")
+ let environment = SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ )
+ let cellar = directory.url.appending(path: "root/usr/local/Cellar", directoryHint: .isDirectory)
+
+ let tools = try #require(CommandLineTools.read(environment: environment, cellar: cellar))
+ #expect(tools.names == ["kav", "served", "ported", "mine", "mytool", "dock", "jq"])
+ #expect(tools.offered.map(\.name) == ["kav", "mine", "mytool", "ported", "served"])
+ #expect(tools.offered.first?.url == bin.appending(path: "kav"))
+
+ let cellarNotKnown = try #require(CommandLineTools.read(environment: environment, cellar: nil))
+ #expect(cellarNotKnown.offered.map(\.name) == ["jq", "kav", "mine", "mytool", "ported", "served"])
+ }
+
+ @Test(.permissionsHold) func isNotKnownWhenAToolFolderCannotBeListed() throws {
+ let directory = try TemporaryDirectory()
+ try directory.setPermissions(0o755, of: try directory.file("home/bin/mine", contents: Data("#!/bin/sh\n".utf8)))
+ try directory.directory("home/.local/bin")
+ try directory.setPermissions(0, of: "home/.local/bin")
+ defer { try? directory.setPermissions(0o755, of: "home/.local/bin") }
+ let environment = SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ )
+
+ #expect(CommandLineTools.read(environment: environment, cellar: nil) == nil)
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift
index 0758b37f..3a2fc32e 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift
@@ -446,7 +446,7 @@ struct IntelInspectorTests {
let tools = readable { IntelInspector.tools(in: [bin.path(percentEncoded: false)], unreadable: &$0) }
#expect(tools.map(\.name) == ["tool"])
- #expect(tools.map { PathPattern.comparablePath(of: $0.url) } == [PathPattern.comparablePath(of: program)])
+ #expect(tools.map { PathPattern.comparablePath(of: $0.program) } == [PathPattern.comparablePath(of: program)])
}
@Test func leavesUnreadAProgramWhoseContentsLiveOnlyInTheCloud() throws {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanOwnersTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanOwnersTests.swift
index f8460f6f..9cf48afb 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanOwnersTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanOwnersTests.swift
@@ -19,24 +19,34 @@ struct OrphanOwnersTests {
#expect(owners.give("org.example.helper", to: .app("com.installed.app")) == .saved)
#expect(owners.give("org.example.tool", to: .formula("exampletool")) == .saved)
+ #expect(owners.give("org.example.cmd", to: .command("mytool")) == .saved)
let written = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])
#expect(written["org.example.helper"] as? String == "com.installed.app")
#expect(written["org.example.tool"] as? [String: String] == ["formula": "exampletool"])
+ #expect(written["org.example.cmd"] as? [String: String] == ["command": "mytool"])
+ #expect(owners.load()?["org.example.cmd"] == .command("mytool"))
}
@Test func leavesOutWhatBelongsToAnInstalledAppOrToolAndToAToolNotYetKnown() {
let owners: [String: OrphanOwner] = [
"org.example.given": .app("com.installed.app"), "org.example.gone": .app("org.example.notinstalled"),
"org.example.tool": .formula("exampletool"), "org.example.lost": .formula("gonetool"),
+ "org.example.cmd": .command("mytool"), "org.example.nocmd": .command("gone"),
]
let apps: Set<String> = ["com.installed.app"]
- #expect(OrphanOwners.given(owners, apps: apps, formulae: ["exampletool"]) == ["org.example.given", "org.example.tool"])
- #expect(OrphanOwners.given(owners, apps: apps, formulae: []) == ["org.example.given"])
#expect(
- OrphanOwners.given(owners, apps: apps, formulae: nil)
- == ["org.example.given", "org.example.tool", "org.example.lost"]
+ OrphanOwners.given(owners, apps: apps, tools: InstalledTools(formulae: ["exampletool"], commands: ["mytool"]))
+ == ["org.example.given", "org.example.tool", "org.example.cmd"]
+ )
+ #expect(
+ OrphanOwners.given(owners, apps: apps, tools: InstalledTools(formulae: [], commands: []))
+ == ["org.example.given"]
+ )
+ #expect(
+ OrphanOwners.given(owners, apps: apps, tools: .notKnown)
+ == ["org.example.given", "org.example.tool", "org.example.lost", "org.example.cmd", "org.example.nocmd"]
)
}
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
index cfa11507..79aa2cf2 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
@@ -167,13 +167,15 @@ struct OrphanScannerTests {
"org.example.tool": .formula("exampletool"),
]
- let left = scan.leavingOut(given: owners, installedApps: installed, installedFormulae: ["exampletool"])
+ let left = scan.leavingOut(
+ given: owners, installedApps: installed, tools: InstalledTools(formulae: ["exampletool"])
+ )
#expect(left.groups.map(\.identifier) == ["org.example.kept", "org.example.gone"])
- let toolGone = scan.leavingOut(given: owners, installedApps: installed, installedFormulae: [])
+ let toolGone = scan.leavingOut(given: owners, installedApps: installed, tools: InstalledTools(formulae: []))
#expect(toolGone.groups.map(\.identifier) == ["org.example.kept", "org.example.gone", "org.example.tool"])
- let toolsNotKnown = scan.leavingOut(given: owners, installedApps: installed, installedFormulae: nil)
+ let toolsNotKnown = scan.leavingOut(given: owners, installedApps: installed, tools: .notKnown)
#expect(toolsNotKnown.groups.map(\.identifier) == ["org.example.kept", "org.example.gone"])
}
@@ -183,16 +185,33 @@ struct OrphanScannerTests {
let scanner = scanner(in: directory)
let owners: [String: OrphanOwner] = ["org.example.tool": .formula("exampletool")]
- let given = await scanner.scan(installedApps: installed, owners: owners, installedFormulae: ["exampletool"])
+ let given = await scanner.scan(
+ installedApps: installed, owners: owners, tools: InstalledTools(formulae: ["exampletool"])
+ )
#expect(given.groups.isEmpty)
- let toolGone = await scanner.scan(installedApps: installed, owners: owners, installedFormulae: [])
+ let toolGone = await scanner.scan(installedApps: installed, owners: owners, tools: InstalledTools(formulae: []))
#expect(toolGone.groups.map(\.identifier) == ["org.example.tool"])
- let toolsNotKnown = await scanner.scan(installedApps: installed, owners: owners, installedFormulae: nil)
+ let toolsNotKnown = await scanner.scan(installedApps: installed, owners: owners, tools: .notKnown)
#expect(toolsNotKnown.groups.isEmpty)
}
+ @Test func aGroupThePersonGaveToACommandIsNotListedWhileTheCommandIsThere() async throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("home/Library/Caches/org.example.cmd/cache.db")
+ let scanner = scanner(in: directory)
+ let owners: [String: OrphanOwner] = ["org.example.cmd": .command("mytool")]
+
+ let given = await scanner.scan(installedApps: installed, owners: owners, tools: InstalledTools(commands: ["mytool"]))
+ #expect(given.groups.isEmpty)
+
+ let commandGone = await scanner.scan(
+ installedApps: installed, owners: owners, tools: InstalledTools(commands: [])
+ )
+ #expect(commandGone.groups.map(\.identifier) == ["org.example.cmd"])
+ }
+
@Test func aTwoPartIdentifierNoAppDeclaredIsNeverAskedAboutAsAPrefix() {
let asked = Mutex<[String]>([])
let ownership = AppOwnership(installedApps: [], goneApps: ["com.example.gone"]) { identifier in
diff --git a/Peel/Model/OrphanLibrary.swift b/Peel/Model/OrphanLibrary.swift
index 174ec178..4de2c229 100644
--- a/Peel/Model/OrphanLibrary.swift
+++ b/Peel/Model/OrphanLibrary.swift
@@ -25,6 +25,8 @@ final class OrphanLibrary {
private(set) var owners: [String: OrphanOwner]?
/// Why that list can't be read, when Peel knows.
private(set) var whyOwnersUnreadable: FileProblem?
+ /// The commands in the tool folders a group can be given to, as the last scan read them.
+ private(set) var offeredCommands: [CommandLineTools.Command] = []
init() {
readOwners()
@@ -80,24 +82,23 @@ final class OrphanLibrary {
// helper or an agent can keep a folder that no app bundle claims.
let running = RunningCopies.current
// Read right before the scan, so a group given to a tool follows the tool.
- let formulae = await Homebrew.installedFormulae()
+ let tools = await InstalledTools.read()
let scan = await OrphanScanner(exclusions: ExclusionsStore.shared.exclusions).scan(
installedApps: installedApps,
remembered: remembered,
running: running,
owners: owners ?? [:],
- installedFormulae: formulae,
+ tools: tools,
leftForAnAdministrator: await LeftForAnAdministrator().load()
)
if !scan.appsOnOtherDisks.isEmpty {
await AppMemory().remember(scan.appsOnOtherDisks)
}
- return (scan: scan, formulae: formulae)
+ return (scan: scan, tools: tools)
}), library.readEverything else { return }
// The owners this scan began with may have grown while it ran.
- let result = found.scan.leavingOut(
- given: self.owners ?? [:], installedApps: library.apps, installedFormulae: found.formulae
- )
+ let result = found.scan.leavingOut(given: self.owners ?? [:], installedApps: library.apps, tools: found.tools)
+ offeredCommands = found.tools.offeredCommands
let remainingURLs = Set(result.groups.flatMap(\.items).filter { $0.leftAlone == nil }.map(\.url))
scan = result
scannedAgainst = listing
diff --git a/Peel/Views/AppChooser.swift b/Peel/Views/AppChooser.swift
index fc79450c..a4d441c1 100644
--- a/Peel/Views/AppChooser.swift
+++ b/Peel/Views/AppChooser.swift
@@ -2,20 +2,23 @@ import AppKit
import PeelCore
import SwiftUI
-/// What a chooser offers: an app, or a command-line tool Homebrew installed.
+/// What a chooser offers: an app, a command-line tool Homebrew installed, or a command in the tool folders.
enum OwnerChoice: Identifiable, Hashable {
case app(InstalledApp)
case tool(HomebrewPackage)
+ case command(CommandLineTools.Command)
enum ID: Hashable {
case app(InstalledApp.ID)
case tool(String)
+ case command(URL)
}
var id: ID {
switch self {
case .app(let app): .app(app.id)
case .tool(let tool): .tool(tool.name)
+ case .command(let command): .command(command.url)
}
}
@@ -23,15 +26,17 @@ enum OwnerChoice: Identifiable, Hashable {
switch self {
case .app(let app): app.name
case .tool(let tool): tool.name
+ case .command(let command): command.name
}
}
- /// What Orphaned Files keeps the choice as: an app by its bundle identifier, so nil for one without, and a tool by
- /// its formula.
+ /// What Orphaned Files keeps the choice as: an app by its bundle identifier, so nil for one without, a tool by its
+ /// formula, and a command by its name.
var owner: OrphanOwner? {
switch self {
case .app(let app): app.bundleIdentifier.map(OrphanOwner.app)
case .tool(let tool): .formula(tool.name)
+ case .command(let command): .command(command.name)
}
}
}
@@ -47,43 +52,54 @@ struct AppChooser: View {
@Environment(AppLibrary.self) private var library
private let apps: [InstalledApp]
private let tools: [HomebrewPackage]
+ private let commands: [CommandLineTools.Command]
private let choose: (OwnerChoice) -> Void
@State private var search = ""
@State private var highlighted: OwnerChoice.ID?
init(apps: [InstalledApp], choose: @escaping (InstalledApp) -> Void) {
- self.init(apps: apps, tools: []) { choice in
+ self.init(apps: apps, tools: [], commands: []) { choice in
if case .app(let app) = choice { choose(app) }
}
}
- init(apps: [InstalledApp], tools: [HomebrewPackage], choose: @escaping (OwnerChoice) -> Void) {
+ init(
+ apps: [InstalledApp],
+ tools: [HomebrewPackage],
+ commands: [CommandLineTools.Command],
+ choose: @escaping (OwnerChoice) -> Void
+ ) {
self.apps = apps
self.tools = tools
+ self.commands = commands
self.choose = choose
}
+ private var offersTools: Bool { !tools.isEmpty || !commands.isEmpty }
+
private var shownApps: [InstalledApp] {
apps.filter { AppListFilter.matches($0, text: search, developer: library.developer(of: $0)) }
.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
}
- private var shownTools: [HomebrewPackage] {
- tools.filter { search.isEmpty || SearchText.matches($0.name, search) }
+ /// Homebrew's formulae and the commands together, by name.
+ private var shownTools: [OwnerChoice] {
+ (tools.map(OwnerChoice.tool) + commands.map(OwnerChoice.command))
+ .filter { search.isEmpty || SearchText.matches($0.name, search) }
.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
}
private var shown: [OwnerChoice] {
- shownApps.map(OwnerChoice.app) + shownTools.map(OwnerChoice.tool)
+ shownApps.map(OwnerChoice.app) + shownTools
}
var body: some View {
let apps = shownApps
let tools = shownTools
- let shown = apps.map(OwnerChoice.app) + tools.map(OwnerChoice.tool)
+ let shown = apps.map(OwnerChoice.app) + tools
// The two kinds get a heading each only while both are offered.
- let headings = self.tools.isEmpty ? 0 : (apps.isEmpty ? 0 : 1) + (tools.isEmpty ? 0 : 1)
+ let headings = offersTools ? (apps.isEmpty ? 0 : 1) + (tools.isEmpty ? 0 : 1) : 0
ScrollViewReader { proxy in
VStack(spacing: 8) {
SearchBox(text: $search, prompt: prompt) { step in
@@ -97,7 +113,7 @@ struct AppChooser: View {
if headings > 0, !apps.isEmpty { heading("Apps") }
ForEach(apps.map(OwnerChoice.app)) { row($0) }
if headings > 0, !tools.isEmpty { heading("Command-Line Tools") }
- ForEach(tools.map(OwnerChoice.tool)) { row($0) }
+ ForEach(tools) { row($0) }
}
}
.scrollBounceBehavior(.basedOnSize)
@@ -119,7 +135,7 @@ struct AppChooser: View {
}
private var prompt: String {
- tools.isEmpty ? String(localized: "Search Applications") : String(localized: "Search Apps and Tools")
+ offersTools ? String(localized: "Search Apps and Tools") : String(localized: "Search Applications")
}
private func heading(_ title: LocalizedStringKey) -> some View {
@@ -140,7 +156,7 @@ struct AppChooser: View {
case .app(let app):
AppIcon(url: app.url)
.frame(width: 20, height: 20)
- case .tool:
+ case .tool, .command:
Image(systemName: "terminal")
.frame(width: 20, height: 20)
}
@@ -159,11 +175,12 @@ struct AppChooser: View {
.help(Text(verbatim: help(for: choice)))
}
- /// Where an app is, or what a tool does, as Homebrew says it.
+ /// Where an app or a command is, or what a tool does, as Homebrew says it.
private func help(for choice: OwnerChoice) -> String {
switch choice {
case .app(let app): app.url.abbreviatedPath
case .tool(let tool): tool.summary ?? tool.name
+ case .command(let command): command.url.abbreviatedPath
}
}
}
diff --git a/Peel/Views/Orphans/OrphanList.swift b/Peel/Views/Orphans/OrphanList.swift
index bc255ef5..170b48c6 100644
--- a/Peel/Views/Orphans/OrphanList.swift
+++ b/Peel/Views/Orphans/OrphanList.swift
@@ -155,9 +155,11 @@ struct OrphanList: View {
.lineLimit(1)
.truncationMode(.middle)
}
- // What a group belongs to is kept by the app's identifier or the tool's formula.
+ // What a group belongs to is kept by the app's identifier, the tool's formula or the command's name.
AppChooser(
- apps: library.apps.filter { $0.bundleIdentifier != nil }, tools: homebrew.formulae
+ apps: library.apps.filter { $0.bundleIdentifier != nil },
+ tools: homebrew.formulae,
+ commands: orphans.offeredCommands
) { choice in
groupToGive = nil
guard let owner = choice.owner else { return }
diff --git a/Peel/Views/Settings/ExclusionsSettingsView.swift b/Peel/Views/Settings/ExclusionsSettingsView.swift
index 7af2a991..6f9c05ce 100644
--- a/Peel/Views/Settings/ExclusionsSettingsView.swift
+++ b/Peel/Views/Settings/ExclusionsSettingsView.swift
@@ -201,7 +201,7 @@ struct ExclusionsSettingsView: View {
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
- case .formula(let name)?:
+ case .formula(let name)?, .command(let name)?:
HStack(spacing: 4) {
Image(systemName: "terminal")
Text(verbatim: name)