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
Ask brew.sh once per reading where Homebrew is
Țugui Dragoș5018abdf6a72
diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swiftindex 1bc70ac9..70ad215d 100644--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift@@ -1,5 +1,6 @@public import Foundationinternal import PeelPrivileged+import Synchronizationpublic struct HomebrewPackage: Sendable, Hashable, Identifiable {public enum Kind: String, Sendable, Hashable {@@ -551,9 +552,12 @@ public enum Homebrew {/// `PATH`, so `which brew` would find nothing. Taking the prefix from the environment would let anything that/// can set `HOMEBREW_PREFIX` choose which program Peel runs.public static var executableURL: URL? {- executable(chosen: HomebrewChoice().load())+ standIn ?? executable(chosen: HomebrewChoice().load())}+ /// A `brew` a test runs in place of this Mac's, whose folders it can't make unwritable or empty.+ @TaskLocal static var standIn: URL?+/// The prefixes Homebrew installs itself in by default, from the root of the disk.static let usualPrefixes = ["opt/homebrew", "usr/local"]@@ -603,6 +607,21 @@ public enum Homebrew {}.first}+ /// What `brew.sh` has answered on its own, without Ruby, each answer a `bin/brew` of its own. A reading of Homebrew+ /// asks through one of these, so it asks each question once, however many parts of the reading need the answer.+ public final class Answers: Sendable {+ private let known = Mutex<[[String]: String]>([:])++ public init() {}++ func answer(_ arguments: [String]) async -> String? {+ if let answer = known.withLock({ $0[arguments] }) { return answer }+ let answer = await Homebrew.answerWithoutTheAPI(arguments, home: .homeDirectory)+ known.withLock { $0[arguments] = answer }+ return answer+ }+ }+/// Returns whether Homebrew's local copy of its definitions is on disk. Without it, any command that may read/// them makes Homebrew download the copy first, even with `HOMEBREW_NO_AUTO_UPDATE` set (`fetch_api_files!` in/// `brew.rb`, 7.0). So Peel looks for the copy itself, and runs nothing else when it is missing. It asks Homebrew@@ -610,8 +629,8 @@ public enum Homebrew {/// could tell it, and running one turns Homebrew's developer mode on for good. Whether Homebrew reads its taps/// instead is what its `brew.env` files say, since Peel's own environment never sets it.@concurrent- public static func hasLocalDefinitions() async -> Bool {- await hasLocalDefinitions(home: .homeDirectory)+ public static func hasLocalDefinitions(asking answers: Answers = Answers()) async -> Bool {+ await hasLocalDefinitions(home: .homeDirectory) { await answers.answer($0) }}static func hasLocalDefinitions(home: URL) async -> Bool {@@ -765,8 +784,8 @@ public enum Homebrew {/// When Homebrew last checked for new versions: the date of its definitions file while it reads its API, as by/// default, since a fetch of its own code leaves them as they were, else when `.git/FETCH_HEAD` was last touched.@concurrent- public static func lastUpdateCheck() async -> Date? {- await lastUpdateCheck(home: .homeDirectory, system: systemSettingsFile) { try? await answer($0) }+ public static func lastUpdateCheck(asking answers: Answers = Answers()) async -> Date? {+ await lastUpdateCheck(home: .homeDirectory, system: systemSettingsFile) { await answers.answer($0) }}static func lastUpdateCheck(@@ -808,13 +827,13 @@ public enum Homebrew {/// The installed packages, each with what Homebrew's own settings make of it, and those settings, or nil when/// Homebrew would not say them.- public static func installed() async throws(CommandFailure)+ public static func installed(asking answers: Answers = Answers()) async throws(CommandFailure)-> (packages: [HomebrewPackage], overrides: Overrides?) {// Read first, so a check made while the packages are read leaves them dated older than they are, never newer.- let checked = await lastUpdateCheck()+ let checked = await lastUpdateCheck(asking: answers)async let settings = overrides()let output = try await answer(["info", "--json=v2", "--installed"])- let caskroom = (try? await answer(["--caskroom"])).flatMap(folder(answering:))+ let caskroom = await answers.answer(["--caskroom"]).flatMap(folder(answering:))guard let packages = parseInstalled(Data(output.utf8), caskroom: caskroom) else {throw CommandFailure(output: output)}@@ -936,13 +955,13 @@ public enum Homebrew {/// Returns the version and prefix of the Homebrew at `executableURL`. The prefix is the folder holding the/// `bin` that `brew` was found in, never one the environment names.@concurrent- public static func installation() async -> HomebrewInstallation? {- guard executableURL != nil, let version = try? await answer(["--version"]) else { return nil }+ public static func installation(asking answers: Answers = Answers()) async -> HomebrewInstallation? {+ guard executableURL != nil, let version = await answers.answer(["--version"]) else { return nil }let found = installation(versionAnswer: version,- prefixAnswer: try? await answer(["--prefix"]),- cellarAnswer: try? await answer(["--cellar"]),- repositoryAnswer: try? await answer(["--repository"])+ prefixAnswer: await answers.answer(["--prefix"]),+ cellarAnswer: await answers.answer(["--cellar"]),+ repositoryAnswer: await answers.answer(["--repository"]))return found?.judgedForThisAccount()}diff --git a/Peel/Model/HomebrewLibrary.swift b/Peel/Model/HomebrewLibrary.swiftindex 72ebffac..ae4aae5d 100644--- a/Peel/Model/HomebrewLibrary.swift+++ b/Peel/Model/HomebrewLibrary.swift@@ -220,6 +220,8 @@ final class HomebrewLibrary {/// Whether Homebrew answered the last reading, so its definitions are on this Mac.private(set) var hasAnswered = false+ /// What `brew.sh` told the last reading about where Homebrew is.+ private var answers = Homebrew.Answers()/// Homebrew's last check for new versions as the last reading found it (`Homebrew.lastUpdateCheck()`).private var checkedForUpdates: Date?@@ -312,8 +314,14 @@ final class HomebrewLibrary {isInstalled || isNotRun}+ /// When Homebrew last checked for new versions, from the folders the last reading asked about, so looking starts+ /// no `brew`.+ func lastUpdateCheck() async -> Date? {+ await Homebrew.lastUpdateCheck(asking: answers)+ }+/// Reads the packages again when Homebrew checked for new versions since they were read, as `brew update` in- /// Terminal does: `checked` is its last check now (`Homebrew.lastUpdateCheck()`). Returns whether it read them.+ /// Terminal does: `checked` is its last check now (`lastUpdateCheck()`). Returns whether it read them.func readAgain(ifHomebrewCheckedAt checked: Date?) async -> Bool {guard packages != nil, runningCommand == nil, checked != checkedForUpdates else { return false }await refresh()@@ -335,8 +343,12 @@ final class HomebrewLibrary {forgetHomebrew()return}- let checked = await Homebrew.lastUpdateCheck()- guard let reading = await scanRun.run({ await self.read(includingReclaimable: includingReclaimable) }),+ let answers = Homebrew.Answers()+ self.answers = answers+ let checked = await Homebrew.lastUpdateCheck(asking: answers)+ guard let reading = await scanRun.run({+ await self.read(includingReclaimable: includingReclaimable, asking: answers)+ }),isInstalledelse { return }checkedForUpdates = checked@@ -373,6 +385,12 @@ final class HomebrewLibrary {keepSelectionOnItsPage()}+ /// Reads the `brew` the person just chose, and keeps nothing the other one said of what it would free.+ func readAnotherBrew() async {+ (reclaimable, autoremovable) = (nil, [])+ await refresh(includingReclaimable: true)+ }+/// With no Homebrew on the Mac, nothing it said still holds, so the library becomes what it is when Peel starts/// without one. The installer receipts stay: they are the Mac's, and an uninstall reads them on their own.private func forgetHomebrew() {@@ -381,6 +399,7 @@ final class HomebrewLibrary {(packages, installation, hasAnswered, couldNotRead, needsDefinitions) = (nil, nil, false, nil, false)(reclaimable, autoremovable, overrides, findings, advisories) = (nil, [], [], nil, nil)(knownCasks, selection) = ([], nil)+ answers = Homebrew.Answers()revision += 1if hadEvidence {evidenceRevision += 1@@ -389,22 +408,22 @@ final class HomebrewLibrary {/// Nil while Homebrew has no local definitions to read, as when `brew update` has never run.private func read(- includingReclaimable: Bool+ includingReclaimable: Bool, asking answers: Homebrew.Answers) async -> (HomebrewInstallation?, Result<[HomebrewPackage], Homebrew.CommandFailure>, Homebrew.CleanupPreview?,Homebrew.Overrides?)? {- guard await Homebrew.hasLocalDefinitions() else { return nil }+ guard await Homebrew.hasLocalDefinitions(asking: answers) else { return nil }needsDefinitions = false// The installation is read first, since it says how to read the figures that follow. The other questions// take about as long as each other, so they run at the same time. Only the page shows the cleanup's figure.- let found = await Homebrew.installation()+ let found = await Homebrew.installation(asking: answers)let kept = found.flatMap { ExclusionsStore.shared.exclusions.keptFormulae(inCellar: $0.cellar) } ?? []async let preview = includingReclaimable ? Homebrew.cleanupPreview(asWrittenBy: found, keeping: kept) : nillet installed: Result<[HomebrewPackage], Homebrew.CommandFailure>var overridden: Homebrew.Overrides?do {- let reading = try await Homebrew.installed()+ let reading = try await Homebrew.installed(asking: answers)installed = .success(reading.packages)overridden = reading.overrides} catch {diff --git a/Peel/PeelApp.swift b/Peel/PeelApp.swiftindex 4bfe7031..5b4d7f7d 100644--- a/Peel/PeelApp.swift+++ b/Peel/PeelApp.swift@@ -286,7 +286,7 @@ struct PeelApp: App {/// Reads Homebrew again once it checked for new versions since Peel last read it, as `brew update` in Terminal/// does, so what it says now reaches Applications.private func followHomebrewsChecks() async {- guard await homebrew.readAgain(ifHomebrewCheckedAt: Homebrew.lastUpdateCheck()) else { return }+ guard await homebrew.readAgain(ifHomebrewCheckedAt: homebrew.lastUpdateCheck()) else { return }library.loadHomebrewCasks(homebrew.caskEvidence, knowsItsOwnApps: homebrew.knowsItsOwnApps)}diff --git a/Peel/Views/Settings/HomebrewSection.swift b/Peel/Views/Settings/HomebrewSection.swiftindex f92c5930..f1a77772 100644--- a/Peel/Views/Settings/HomebrewSection.swift+++ b/Peel/Views/Settings/HomebrewSection.swift@@ -86,7 +86,7 @@ struct HomebrewSection: View {private func use(_ brew: URL?) {couldNotSave = !HomebrewChoice().save(brew)choice = HomebrewChoice().load()- Task { await homebrew.refresh() }+ Task { await homebrew.readAnotherBrew() }}}diff --git a/PeelTests/HomebrewLibraryTests.swift b/PeelTests/HomebrewLibraryTests.swiftindex f51f72a9..e63de189 100644--- a/PeelTests/HomebrewLibraryTests.swift+++ b/PeelTests/HomebrewLibraryTests.swift@@ -4,7 +4,84 @@ import Observation@testable import PeelCoreimport Testing+/// A `brew` that answers for a made-up Homebrew and notes what it was asked.+private struct StandInBrew {+ let folder = FileManager.default.temporaryDirectory.appending(+ path: "PeelTests-brew-\(UUID().uuidString)", directoryHint: .isDirectory+ )++ var url: URL { folder.appending(path: "bin/brew") }++ private var log: URL { folder.appending(path: "asked") }++ /// `cleanup` is what its `brew cleanup` runs, in shell.+ init(hasDefinitions: Bool = true, cleanup: String = ":") throws {+ let manager = FileManager.default+ let path = folder.path(percentEncoded: false)+ let script = """+ #!/bin/sh+ echo "$1" >> '\(log.path(percentEncoded: false))'+ case "$1" in+ --version) echo 'Homebrew 7.0.0' ;;+ --prefix|--repository) echo '\(path)' ;;+ --cellar) echo '\(path)Cellar' ;;+ --caskroom) echo '\(path)Caskroom' ;;+ --cache) echo '\(path)cache' ;;+ info) echo '{"formulae":[],"casks":[]}' ;;+ cleanup) \(cleanup) ;;+ esac++ """+ try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data(script.utf8).write(to: url)+ try manager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path(percentEncoded: false))+ guard hasDefinitions else { return }+ let definitions = folder.appending(path: "cache/api/internal/packages.made_up.jws.json")+ try manager.createDirectory(at: definitions.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data().write(to: definitions)+ }++ func asked() throws -> [String] {+ try String(contentsOf: log, encoding: .utf8).split(separator: "\n").map(String.init)+ }++ func goAway() {+ try? FileManager.default.removeItem(at: folder)+ }+}+@Suite(.serialized) struct HomebrewLibraryTests {+ @Test func aReadingAsksOnceWhatBrewShAnswersOnItsOwn() async throws {+ let brew = try StandInBrew()+ defer { brew.goAway() }+ let homebrew = HomebrewLibrary()++ await Homebrew.$standIn.withValue(brew.url) { await homebrew.refresh(includingReclaimable: true) }++ #expect(homebrew.installation?.version == "7.0.0")+ #expect(homebrew.hasAnswered)+ let asked = try brew.asked()+ for question in ["--version", "--prefix", "--cellar", "--repository", "--cache", "--caskroom"] {+ #expect(asked.count { $0 == question } == 1, "\(question), in \(asked)")+ }+ }++ @Test func oneBrewsFigureDoesNotOutliveTheChoiceOfAnother() async throws {+ let first = try StandInBrew(cleanup: "echo '==> This operation would free approximately 2GB of disk space.'")+ let second = try StandInBrew(cleanup: "exit 1")+ defer {+ first.goAway()+ second.goAway()+ }+ let homebrew = HomebrewLibrary()++ await Homebrew.$standIn.withValue(first.url) { await homebrew.refresh(includingReclaimable: true) }+ #expect(homebrew.reclaimable == 2_000_000_000)+ await Homebrew.$standIn.withValue(second.url) { await homebrew.readAnotherBrew() }++ #expect(homebrew.reclaimable == nil)+ }+@Test func namesInHistoryOnlyTheCasksWhoseRecordMoved() throws {let caskroom = URL(filePath: "/opt/homebrew/Caskroom", directoryHint: .isDirectory)let casks = ["alpha", "beta", "gamma"].map { HomebrewPackage(name: $0, kind: .cask).kept(inCaskroom: caskroom) }@@ -20,7 +97,7 @@ import Testinglet homebrew = HomebrewLibrary()await homebrew.refresh()let read = homebrew.revision- let checked = await Homebrew.lastUpdateCheck()+ let checked = await homebrew.lastUpdateCheck()#expect(await !homebrew.readAgain(ifHomebrewCheckedAt: checked))#expect(homebrew.revision == read)