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
List the tools the Tools tab offers to install, and ask Homebrew about them
Țugui Dragoșdde5df7f41da
diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swiftindex 84ae8f4a..f6ffaec5 100644--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift@@ -329,6 +329,9 @@ indirect enum CaskValue: Decodable, Sendable {public enum Homebrew {static let notInstalled = "Homebrew isn’t installed."+ /// The command brew.sh gives for installing Homebrew. Its script says what it will do and waits before doing it.+ public static let installCommand = "/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""+ public static let website = URL(string: "https://brew.sh")!public struct CommandFailure: Error, Sendable, Hashable {public let output: String@@ -449,6 +452,22 @@ public enum Homebrew {return Set(output.split(whereSeparator: \.isNewline).map { String($0).trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty })}+ /// Returns the name of every formula Homebrew knows of, read from its local copy of the definitions.+ @concurrent+ public static func formulaNames() async -> Set<String> {+ guard let output = try? await answer(["formulae"]) else { return [] }+ return Set(output.split(whereSeparator: \.isNewline).map { String($0).trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty })+ }++ /// Asks about several formulae in one call. A single unknown name makes the whole call fail, so only names from+ /// `formulaNames()` are ever passed in.+ @concurrent+ public static func formulae(named names: [String]) async -> [HomebrewPackage] {+ guard !names.isEmpty else { return [] }+ guard let output = try? await answer(["info", "--json=v2", "--formula"] + names) else { return [] }+ return parseInstalled(Data(output.utf8))?.filter { $0.kind == .formula } ?? []+ }+/// Asks about several casks in one call, which is quicker than asking about each on its own. A single/// unknown name makes the whole call fail, so only names from `caskTokens()` are ever passed in.@concurrentdiff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalTool.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalTool.swiftnew file mode 100644index 00000000..51bd06cc--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalTool.swift@@ -0,0 +1,139 @@+public import Foundation++/// A tool the Tools tab offers to install with Homebrew, with what its own documentation says to do after. Peel+/// installs nothing: it shows the commands and lines to copy. The shell's tools are listed in the order their lines+/// load in `~/.zshrc`, which is the order they need.+public enum TerminalTool: CaseIterable, Sendable {+ case zshCompletions+ case fzfTab+ case zoxide+ case fzf+ case direnv+ case zshAutosuggestions+ case zshSyntaxHighlighting+ case delta+ case gitLFS+ case lazygit+ case bat+ case hyperfine+ case tlrc++ public enum Group: CaseIterable, Sendable {+ case shell, git, everyday+ }++ public enum Place: Sendable {+ case zshrc+ case lastLineOfZshrc+ case terminal+ }++ public struct Setup: Equatable, Sendable {+ public let place: Place+ public let lines: [String]+ }++ public enum Availability: Equatable, Sendable {+ case available+ case retired(HomebrewRetirement)+ case unknownToHomebrew+ }++ public var group: Group {+ switch self {+ case .zshCompletions, .fzfTab, .zoxide, .fzf, .direnv, .zshAutosuggestions, .zshSyntaxHighlighting: .shell+ case .delta, .gitLFS, .lazygit: .git+ case .bat, .hyperfine, .tlrc: .everyday+ }+ }++ public var formula: String {+ switch self {+ case .zshCompletions: "zsh-completions"+ case .fzfTab: "fzf-tab"+ case .zoxide: "zoxide"+ case .fzf: "fzf"+ case .direnv: "direnv"+ case .zshAutosuggestions: "zsh-autosuggestions"+ case .zshSyntaxHighlighting: "zsh-syntax-highlighting"+ case .delta: "git-delta"+ case .gitLFS: "git-lfs"+ case .lazygit: "lazygit"+ case .bat: "bat"+ case .hyperfine: "hyperfine"+ case .tlrc: "tlrc"+ }+ }++ public var name: String {+ switch self {+ case .delta: "delta"+ case .gitLFS: "Git LFS"+ default: formula+ }+ }++ public var project: URL {+ let address = switch self {+ case .zshCompletions: "https://github.com/zsh-users/zsh-completions"+ case .fzfTab: "https://github.com/Aloxaf/fzf-tab"+ case .zoxide: "https://github.com/ajeetdsouza/zoxide"+ case .fzf: "https://github.com/junegunn/fzf"+ case .direnv: "https://github.com/direnv/direnv"+ case .zshAutosuggestions: "https://github.com/zsh-users/zsh-autosuggestions"+ case .zshSyntaxHighlighting: "https://github.com/zsh-users/zsh-syntax-highlighting"+ case .delta: "https://github.com/dandavison/delta"+ case .gitLFS: "https://github.com/git-lfs/git-lfs"+ case .lazygit: "https://github.com/jesseduffield/lazygit"+ case .bat: "https://github.com/sharkdp/bat"+ case .hyperfine: "https://github.com/sharkdp/hyperfine"+ case .tlrc: "https://github.com/tldr-pages/tlrc"+ }+ return URL(string: address)!+ }++ /// fzf-tab runs fzf, which Homebrew does not install with it.+ public var formulae: [String] {+ self == .fzfTab ? ["fzf", formula] : [formula]+ }++ public var installCommand: String {+ "brew install " + formulae.joined(separator: " ")+ }++ public func setup(prefix: URL) -> [Setup] {+ let prefix = prefix.path(percentEncoded: false)+ return switch self {+ case .zshCompletions: [Setup(place: .zshrc, lines: ["FPATH=\"\(prefix)/share/zsh-completions:$FPATH\"", "autoload -Uz compinit && compinit"])]+ case .fzfTab: [Setup(place: .zshrc, lines: ["source \"\(prefix)/opt/fzf-tab/share/fzf-tab/fzf-tab.zsh\"", "zstyle ':completion:*' menu no"])]+ case .zoxide: [Setup(place: .zshrc, lines: ["eval \"$(zoxide init zsh)\""])]+ case .fzf: [Setup(place: .zshrc, lines: ["source <(fzf --zsh)", "export FZF_DEFAULT_OPTS=\"$FZF_DEFAULT_OPTS --color=16\""])]+ case .direnv: [Setup(place: .zshrc, lines: ["eval \"$(direnv hook zsh)\""])]+ case .zshAutosuggestions: [Setup(place: .zshrc, lines: ["source \"\(prefix)/share/zsh-autosuggestions/zsh-autosuggestions.zsh\""])]+ case .zshSyntaxHighlighting:+ [Setup(place: .lastLineOfZshrc, lines: ["source \"\(prefix)/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh\""])]+ case .delta:+ [Setup(place: .terminal, lines: [+ "git config --global core.pager delta",+ "git config --global interactive.diffFilter 'delta --color-only'",+ "git config --global delta.navigate true",+ ])]+ case .gitLFS: [Setup(place: .terminal, lines: ["git lfs install"])]+ // macOS's man marks bold text with backspaces, which bat would show as they are, so col -bx removes them first.+ case .bat: [Setup(place: .zshrc, lines: ["export BAT_THEME=ansi", "export MANPAGER=\"sh -c 'col -bx | bat -l man -p'\""])]+ case .lazygit, .hyperfine, .tlrc: []+ }+ }++ public func isInstalled(prefix: URL) -> Bool {+ formulae.allSatisfy { FileManager.default.fileExists(atPath: prefix.appending(path: "opt/\($0)").path(percentEncoded: false)) }+ }++ /// Whether Homebrew still offers the tool: `known` is every formula name it knows, and `packages` what it said+ /// of the tool's formulae, which carries a retirement and the formula that replaces it.+ public func availability(known: Set<String>, packages: [HomebrewPackage]) -> Availability {+ guard formulae.allSatisfy(known.contains) else { return .unknownToHomebrew }+ let retirement = packages.first { formulae.contains($0.name) && $0.retirement != nil }?.retirement+ return retirement.map(Availability.retired) ?? .available+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TerminalToolTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TerminalToolTests.swiftnew file mode 100644index 00000000..41ff0811--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/TerminalToolTests.swift@@ -0,0 +1,73 @@+import Foundation+@testable import PeelCore+import PeelPrivileged+import Testing++struct TerminalToolTests {+ static let prefix = URL(filePath: "/opt/homebrew", directoryHint: .isDirectory)++ @Test func everyLineForZshrcIsZshThatParses() async throws {+ for tool in TerminalTool.allCases {+ for setup in tool.setup(prefix: Self.prefix) where setup.place != .terminal {+ let answer = await Subprocess.run("/bin/zsh", ["-f", "-n", "-c", setup.lines.joined(separator: "\n")], environment: [:], timeout: 10)+ guard case .success(let output) = answer else { throw POSIXError(.EIO) }+ #expect(output.status == 0 && output.errorText.isEmpty, "\(tool): \(output.errorText)")+ }+ }+ }++ @Test func theShellsToolsAreListedInTheOrderTheirLinesLoad() throws {+ let shell = TerminalTool.allCases.filter { $0.group == .shell }+ let place = { (tool: TerminalTool) in try #require(shell.firstIndex(of: tool)) }+ #expect(try place(.zshCompletions) < place(.fzfTab))+ #expect(try place(.fzfTab) < place(.zshAutosuggestions))+ #expect(try place(.zoxide) > place(.zshCompletions))+ #expect(shell.last == .zshSyntaxHighlighting)+ let last = TerminalTool.allCases.filter { $0.setup(prefix: Self.prefix).contains { $0.place == .lastLineOfZshrc } }+ #expect(last == [.zshSyntaxHighlighting])+ }++ @Test func gitsOwnKeysInTheCommandsAreOnesTheGitOnThisMacKnows() async throws {+ let git = try #require(await GitConfig.find(home: FileManager.default.temporaryDirectory))+ let known = try #require(await git.knownKeys())+ let keys = TerminalTool.allCases.flatMap { $0.setup(prefix: Self.prefix) }.flatMap(\.lines)+ .filter { $0.hasPrefix("git config --global ") }+ .map { $0.split(separator: " ")[3].lowercased() }+ .filter { !$0.hasPrefix("delta.") }+ #expect(!keys.isEmpty)+ for key in keys {+ #expect(known.contains(key), "\(key)")+ }+ }++ @Test func eachInstallCommandNamesEveryFormulaTheToolNeeds() {+ #expect(TerminalTool.fzfTab.installCommand == "brew install fzf fzf-tab")+ #expect(TerminalTool.delta.installCommand == "brew install git-delta")+ for tool in TerminalTool.allCases {+ #expect(tool.formulae.contains(tool.formula), "\(tool)")+ #expect(tool.project.scheme == "https", "\(tool)")+ }+ #expect(Set(TerminalTool.allCases.map(\.formula)).count == TerminalTool.allCases.count)+ }++ @Test func homebrewSaysWhetherAToolIsStillOffered() {+ let names: Set<String> = ["fzf", "fzf-tab", "tlrc"]+ let retired = HomebrewRetirement(stage: .disabled, reason: .unmaintained, disableDate: nil, replacement: .formula("tlrc"))+ #expect(TerminalTool.tlrc.availability(known: names, packages: [HomebrewPackage(name: "tlrc", kind: .formula)]) == .available)+ #expect(TerminalTool.fzfTab.availability(known: ["fzf-tab"], packages: []) == .unknownToHomebrew)+ #expect(TerminalTool.tlrc.availability(known: names, packages: [HomebrewPackage(name: "tlrc", kind: .formula, retirement: retired)]) == .retired(retired))+ #expect(TerminalTool.fzfTab.availability(known: names, packages: [HomebrewPackage(name: "fzf", kind: .formula, retirement: retired)]) == .retired(retired))+ }++ @Test func aToolIsInstalledOnlyWhenHomebrewLinkedEveryFormulaItNeeds() throws {+ let prefix = FileManager.default.temporaryDirectory.appending(path: "TerminalToolTests-\(UUID().uuidString)", directoryHint: .isDirectory)+ let cellar = prefix.appending(path: "Cellar/fzf-tab/1.3.0", directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: cellar, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: prefix.appending(path: "opt"), withIntermediateDirectories: true)+ try FileManager.default.createSymbolicLink(at: prefix.appending(path: "opt/fzf-tab"), withDestinationURL: cellar)+ #expect(!TerminalTool.fzfTab.isInstalled(prefix: prefix))+ try FileManager.default.createDirectory(at: prefix.appending(path: "Cellar/fzf/0.74.4"), withIntermediateDirectories: true)+ try FileManager.default.createSymbolicLink(at: prefix.appending(path: "opt/fzf"), withDestinationURL: prefix.appending(path: "Cellar/fzf/0.74.4"))+ #expect(TerminalTool.fzfTab.isInstalled(prefix: prefix))+ }+}