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
Homebrew's clean up keeps the formulae the exclusions cover
Țugui Dragoșceb622c2dc61
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 376cf49d..4486bfaf 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -80222,6 +80222,112 @@}}},+ "Peel couldn’t make sure Homebrew keeps the formulae your exclusions cover, so it ran nothing. A brew.env file that sets HOMEBREW_NO_CLEANUP_FORMULAE replaces the list Peel gives it." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel nemohl ověřit, že Homebrew ponechá formulae, na které se vztahují vaše výjimky, a proto nic nespustil. Soubor brew.env, který nastavuje HOMEBREW_NO_CLEANUP_FORMULAE, nahradí seznam, který Peel předává Homebrew."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel konnte nicht sicherstellen, dass Homebrew die Formulae behält, die unter deine Ausschlüsse fallen, und hat daher nichts ausgeführt. Eine brew.env-Datei, die HOMEBREW_NO_CLEANUP_FORMULAE festlegt, ersetzt die Liste, die Peel an Homebrew übergibt."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel no ha podido asegurarse de que Homebrew conserve las formulae que cubren tus exclusiones, así que no ha ejecutado nada. Un archivo brew.env que establece HOMEBREW_NO_CLEANUP_FORMULAE reemplaza la lista que le da Peel."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel n’a pas pu s’assurer que Homebrew conserve les formulae concernées par vos exclusions : Peel n’a donc rien exécuté. Un fichier brew.env qui définit HOMEBREW_NO_CLEANUP_FORMULAE remplace la liste que Peel lui transmet."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel non è riuscito ad assicurarsi che Homebrew conservi le formulae coperte dalle tue esclusioni, quindi non ha eseguito nulla. Un file brew.env che imposta HOMEBREW_NO_CLEANUP_FORMULAE sostituisce l’elenco che Peel gli fornisce."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peelは、除外リストに含まれるformulaeをHomebrewが残すことを確認できなかったため、何も実行しませんでした。HOMEBREW_NO_CLEANUP_FORMULAEを設定するbrew.envファイルがあると、Peelが渡すリストはその設定に置き換えられます。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel은 제외 항목에 포함된 formulae를 Homebrew가 유지하는지 확인할 수 없어 아무것도 실행하지 않았습니다. brew.env 파일에서 HOMEBREW_NO_CLEANUP_FORMULAE를 설정하면 Peel이 Homebrew에 전달하는 목록이 그 설정으로 대체됩니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel kon niet nagaan of Homebrew de formulae behoudt die onder je uitsluitingen vallen, en heeft daarom niets uitgevoerd. Een brew.env-bestand dat HOMEBREW_NO_CLEANUP_FORMULAE instelt, vervangt de lijst die Peel aan Homebrew doorgeeft."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel nie mógł się upewnić, że Homebrew zachowa formulae objęte Twoimi wykluczeniami, więc niczego nie uruchomił. Plik brew.env, który ustawia HOMEBREW_NO_CLEANUP_FORMULAE, zastępuje listę, którą przekazuje mu Peel."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O Peel não conseguiu garantir que o Homebrew mantenha as formulae cobertas pelas suas exclusões, então não executou nada. Um arquivo brew.env que define HOMEBREW_NO_CLEANUP_FORMULAE substitui a lista que o Peel passa para ele."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel nu s‑a putut asigura că Homebrew păstrează formulele acoperite de excluderile dvs., așa că nu a rulat nimic. Un fișier brew.env care stabilește HOMEBREW_NO_CLEANUP_FORMULAE înlocuiește lista pe care i‑o dă Peel."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel не удалось убедиться, что Homebrew оставит formulae, на которые распространяются Ваши исключения, поэтому ничего не было запущено. Файл brew.env, который задает HOMEBREW_NO_CLEANUP_FORMULAE, заменяет список, который ему передает Peel."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel kunde inte säkerställa att Homebrew behåller de formulae som dina undantag omfattar, så Peel körde ingenting. En brew.env-fil som ställer in HOMEBREW_NO_CLEANUP_FORMULAE ersätter listan som Peel ger Homebrew."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel, hariç tutulanlarınızın kapsadığı formulae için Homebrew’un bunları koruyacağından emin olamadı, bu yüzden hiçbir şey çalıştırmadı. HOMEBREW_NO_CLEANUP_FORMULAE değerini ayarlayan bir brew.env dosyası, Peel’in Homebrew’a verdiği listenin yerini alır."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel не вдалося переконатися, що Homebrew збереже formulae, які є у ваших винятках, тож Peel нічого не запускала. Файл brew.env, у якому задано HOMEBREW_NO_CLEANUP_FORMULAE, замінює список, який йому передає Peel."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel未能确保Homebrew会保留你的排除项所涵盖的formulae,因此没有运行任何命令。设置了HOMEBREW_NO_CLEANUP_FORMULAE的brew.env文件会替换Peel提供给Homebrew的列表。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel無法確保Homebrew會保留你的排除項目所涵蓋的formulae,因此未執行任何Homebrew指令。設定了HOMEBREW_NO_CLEANUP_FORMULAE的brew.env檔案會取代Peel提供給Homebrew的列表。"+ }+ }+ }+ },"Peel couldn’t read History" : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swiftindex 9ecbf9b7..21292e2b 100644--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift@@ -466,8 +466,12 @@ public enum Homebrew {/// What `brew cleanup` would free. Nothing is removed: `--dry-run` only reports.@concurrent- public static func reclaimableBytes(asWrittenBy installation: HomebrewInstallation?) async -> Int64? {- guard let output = try? await answer(["cleanup", "--dry-run"]) else { return nil }+ public static func reclaimableBytes(+ asWrittenBy installation: HomebrewInstallation?, keeping kept: [String]+ ) async -> Int64? {+ guard let output = try? await execute(+ ["cleanup", "--dry-run"], autoUpdate: false, keeping: kept, timeout: longestAnswer+ ).answer() else { return nil }return reclaimableBytes(in: output, countsInThousands: installation?.countsInThousands ?? true)}@@ -519,9 +523,13 @@ public enum Homebrew {return attempt?.output ?? ""}+ /// `kept` are the formulae Homebrew must not autoremove afterward.@concurrent- public static func uninstall(_ package: HomebrewPackage) async throws(CommandFailure) -> String {- try await run(["uninstall", package.kind == .cask ? "--cask" : "--formula", package.name], autoUpdate: false)+ public static func uninstall(+ _ package: HomebrewPackage, keeping kept: [String]+ ) async throws(CommandFailure) -> String {+ let arguments = ["uninstall", package.kind == .cask ? "--cask" : "--formula", package.name]+ return try await execute(arguments, autoUpdate: false, keeping: kept, timeout: longestCommand).transcript()}@concurrent@@ -529,9 +537,28 @@ public enum Homebrew {try await run(["update"], autoUpdate: false)}+ /// `kept` are the formulae Homebrew must neither clean up nor autoremove.+ @concurrent+ public static func cleanup(keeping kept: [String]) async throws(CommandFailure) -> String {+ try await execute(["cleanup"], autoUpdate: false, keeping: kept, timeout: longestCommand).transcript()+ }++ /// True when Homebrew, its own `brew.env` files read, still keeps every formula in `kept`. Such a file can+ /// replace the list Peel gives it, and `brew config` says what is in effect.@concurrent- public static func cleanup() async throws(CommandFailure) -> String {- try await run(["cleanup"], autoUpdate: false)+ public static func keepsEvery(_ kept: [String]) async -> Bool {+ guard !kept.isEmpty else { return true }+ guard let config = try? await execute(["config"], autoUpdate: false, keeping: kept, timeout: longestAnswer)+ .answer() else { return false }+ return Set(kept).isSubset(of: keptFormulae(inConfig: config))+ }++ /// Reads the `HOMEBREW_NO_CLEANUP_FORMULAE: a,b` line of `brew config`'s answer.+ static func keptFormulae(inConfig config: String) -> Set<String> {+ let prefix = "HOMEBREW_NO_CLEANUP_FORMULAE: "+ let lines = config.split(whereSeparator: \.isNewline)+ guard let line = lines.first(where: { $0.hasPrefix(prefix) }) else { return [] }+ return Set(line.dropFirst(prefix.count).split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) })}static func parseInstalled(_ data: Data) -> [HomebrewPackage]? {@@ -622,6 +649,7 @@ public enum Homebrew {static func execute(_ arguments: [String],autoUpdate: Bool,+ keeping kept: [String] = [],timeout: TimeInterval?,onOutput: (@Sendable (Data) -> Void)? = nil,executable: URL? = executableURL@@ -630,7 +658,8 @@ public enum Homebrew {throw CommandFailure(output: Self.notInstalled)}let path = executable.path(percentEncoded: false)- switch await Subprocess.run(path, arguments, environment: environment(autoUpdate: autoUpdate), timeout: timeout, onOutput: onOutput) {+ let environment = environment(autoUpdate: autoUpdate, keeping: kept)+ switch await Subprocess.run(path, arguments, environment: environment, timeout: timeout, onOutput: onOutput) {case .success(let output):return Attempt(status: output.status, standardOutput: output.text, standardError: output.errorText)case .failure(let failure):@@ -681,7 +710,7 @@ public enum Homebrew {/// value set anywhere in the user's session would otherwise decide how Homebrew behaves, and/// `HOMEBREW_FORCE_API_AUTO_UPDATE` would undo the setting that keeps Peel off the network. Homebrew's own/// `brew.env` files are read after it and can still undo a setting here, which `overrides()` reports.- static func environment(autoUpdate: Bool) -> [String: String] {+ static func environment(autoUpdate: Bool, keeping kept: [String] = []) -> [String: String] {var values = ["PATH": "/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin","HOME": URL.homeDirectory.path(percentEncoded: false),@@ -696,6 +725,9 @@ public enum Homebrew {if !autoUpdate {values["HOMEBREW_NO_AUTO_UPDATE"] = "1"}+ if !kept.isEmpty {+ values["HOMEBREW_NO_CLEANUP_FORMULAE"] = kept.joined(separator: ",")+ }return values}diff --git a/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift b/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swiftindex 6ece9188..760f8a7c 100644--- a/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift+++ b/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift@@ -139,6 +139,20 @@ public struct Exclusions: Sendable, Codable, Hashable {return excludes(own) || holds(own)}+ /// The installed formulae whose own folder under `prefix` is excluded or holds something excluded, which+ /// Homebrew is told to keep: `brew cleanup`, and the autoremove `brew uninstall` runs, delete formulae and their+ /// old versions for good. An unreadable list, or one not read yet, keeps every formula.+ public func keptFormulae(inCellarOf prefix: URL) -> [String] {+ let cellar = prefix.appending(path: "Cellar", directoryHint: .isDirectory)+ let names = (try? FileManager.default.contentsOfDirectory(atPath: cellar.path(percentEncoded: false))) ?? []+ return names.filter { name in+ guard !name.hasPrefix(".") else { return false }+ guard isKnown else { return true }+ let own = cellar.appending(path: name, directoryHint: .isDirectory)+ return excludes(own) || holds(own)+ }.sorted()+ }+public func keeping<T>(_ items: [T], url: (T) -> URL) -> [T] {guard !paths.isEmpty else { return items }return items.filter { !excludes(url($0)) }diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swiftindex 3e03750f..475a9a0c 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift@@ -13,6 +13,41 @@ struct HomebrewTests {}}+ /// `brew cleanup` and the autoremove that `brew uninstall` runs delete formulae and their old versions for good,+ /// so the formulae the exclusions cover are named in `HOMEBREW_NO_CLEANUP_FORMULAE`, which Homebrew's own+ /// documentation says makes it refuse to clean up or autoremove them.+ @Test func homebrewIsToldToKeepTheFormulaeTheExclusionsCover() async throws {+ let directory = try TemporaryDirectory()+ try directory.directory("Cellar/wget/1.25.0")+ try directory.directory("Cellar/jq/1.8.1")+ try directory.directory("Cellar/[email protected]/3.13.7")+ let exclusions = Exclusions(paths: [+ directory.url.appending(path: "Cellar/jq"), directory.url.appending(path: "Cellar/[email protected]/3.13.7"),+ ])++ let kept = exclusions.keptFormulae(inCellarOf: directory.url)+ #expect(kept == ["jq", "[email protected]"])+ #expect(Exclusions.unreadable.keptFormulae(inCellarOf: directory.url) == ["jq", "[email protected]", "wget"])++ let attempt = try await Homebrew.execute(+ ["-c", "printf %s \"$HOMEBREW_NO_CLEANUP_FORMULAE\""], autoUpdate: false, keeping: kept, timeout: 10,+ executable: URL(filePath: "/bin/sh")+ )+ #expect(attempt.standardOutput == "jq,[email protected]")+ }++ /// `bin/brew` reads its `brew.env` files after Peel's environment, and one can replace the list, so Peel asks+ /// `brew config` what is in effect before it lets Homebrew delete anything.+ @Test func readsWhichFormulaeHomebrewKeepsFromItsOwnSettings() {+ let config = """+ HOMEBREW_VERSION: 7.0.4+ HOMEBREW_NO_CLEANUP_FORMULAE: jq,[email protected]+ HOMEBREW_NO_ANALYTICS: set+ """+ #expect(Homebrew.keptFormulae(inConfig: config) == ["jq", "[email protected]"])+ #expect(Homebrew.keptFormulae(inConfig: "HOMEBREW_VERSION: 7.0.4\n").isEmpty)+ }+/// Formulae and casks are upgraded in two calls, and the second is made even when the first never finished,/// as when it ran out of time: the casks were otherwise never tried, and the report left them out.@Test func upgradesTheCasksEvenWhenTheFormulaeNeverFinished() async {diff --git a/Peel/Model/HomebrewLibrary.swift b/Peel/Model/HomebrewLibrary.swiftindex dbd7e89c..1655f368 100644--- a/Peel/Model/HomebrewLibrary.swift+++ b/Peel/Model/HomebrewLibrary.swift@@ -162,7 +162,9 @@ final class HomebrewLibrary {// 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 last two.let found = await Homebrew.installation()- async let reclaimable = includingReclaimable ? Homebrew.reclaimableBytes(asWrittenBy: found) : nil+ let kept = found.map { ExclusionsStore.shared.exclusions.keptFormulae(inCellarOf: $0.prefix) } ?? []+ async let reclaimable = includingReclaimable+ ? Homebrew.reclaimableBytes(asWrittenBy: found, keeping: kept) : nilasync let overridden = includingReclaimable ? Homebrew.overrides() : nillet installed: Result<[HomebrewPackage], Homebrew.CommandFailure>do {@@ -219,11 +221,13 @@ final class HomebrewLibrary {return await following { onOutput throws(Homebrew.CommandFailure) in try await Homebrew.upgrade(packages, onOutput: onOutput) }case .uninstall(let id):guard let package = package(id) else { return gone }- output = try await Homebrew.uninstall(package)+ guard let kept = await keptFormulae() else { return keepsNothing }+ output = try await Homebrew.uninstall(package, keeping: kept)case .update:output = try await Homebrew.updateMetadata()case .cleanup:- output = try await Homebrew.cleanup()+ guard let kept = await keptFormulae() else { return keepsNothing }+ output = try await Homebrew.cleanup(keeping: kept)case .health:// An older Homebrew answers only in prose, which is shown as written. `--json` is a hidden// switch, so an answer Peel can't read is asked for again in prose rather than shown as an error.@@ -251,6 +255,18 @@ final class HomebrewLibrary {}}+ private var keepsNothing: CommandResult {+ CommandResult(succeeded: false, output: String(localized: "Peel couldn’t make sure Homebrew keeps the formulae your exclusions cover, so it ran nothing. A brew.env file that sets HOMEBREW_NO_CLEANUP_FORMULAE replaces the list Peel gives it."))+ }++ /// The formulae the exclusions cover, which Homebrew is told to keep, asked again right before a command that+ /// deletes for good. Nil when Peel can't tell which they are or Homebrew's own settings replace the list.+ private func keptFormulae() async -> [String]? {+ guard let prefix = installation?.prefix else { return nil }+ let kept = ExclusionsStore.shared.exclusions.keptFormulae(inCellarOf: prefix)+ return await Homebrew.keepsEvery(kept) ? kept : nil+ }+private static func announce(_ words: LocalizedStringResource) {AccessibilityNotification.Announcement(AttributedString(localized: words)).post()}