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
An upgrade is followed as it runs, and can be stopped
Țugui Dragoș6768b94c2c85
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 3e252329..c3ed0976 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -6832,6 +6832,112 @@}}},+ "A package Homebrew is in the middle of installing may be left half installed, and may need installing again." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Balíček, který Homebrew právě instaluje, může zůstat napůl nainstalovaný a možná ho bude potřeba nainstalovat znovu."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ein Paket, das Homebrew gerade installiert, bleibt möglicherweise nur teilweise installiert und muss eventuell erneut installiert werden."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Un paquete que Homebrew esté instalando en este momento puede quedar a medio instalar, y puede que haya que volver a instalarlo."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Un paquet que Homebrew est en train d’installer pourrait rester partiellement installé, et il faudrait peut-être le réinstaller."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Un pacchetto che Homebrew sta installando potrebbe restare installato a metà e dover essere reinstallato."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrewがインストールしている途中のパッケージは、不完全にインストールされたままになり、再インストールが必要になる場合があります。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrew가 설치 중인 패키지는 일부만 설치된 상태로 남을 수 있으며, 다시 설치해야 할 수도 있습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Een pakket dat Homebrew nog aan het installeren is, kan half geïnstalleerd achterblijven en moet dan misschien opnieuw worden geïnstalleerd."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Pakiet, który Homebrew właśnie instaluje, może zostać zainstalowany częściowo i może wymagać ponownej instalacji."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Um pacote que o Homebrew estiver instalando no momento pode ficar instalado pela metade, e talvez precise ser instalado de novo."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Un pachet pe care Homebrew încă îl instalează poate rămâne instalat pe jumătate și poate fi necesar să fie instalat din nou."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Пакет, который Homebrew устанавливает в этот момент, может остаться установленным наполовину, и его, возможно, придется установить снова."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ett paket som Homebrew håller på att installera kan bli halvt installerat och behöva installeras igen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrew’un yüklemekte olduğu bir paket yarım yüklenmiş hâlde kalabilir ve yeniden yüklenmesi gerekebilir."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Пакет, який Homebrew саме інсталює, може залишитися інстальованим лише частково, і його, можливо, доведеться інсталювати знову."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrew正在安装的软件包可能只安装了部分,之后可能需要重新安装。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrew正在安裝的套件可能只有一部分完成安裝,因此可能需要重新安裝。"+ }+ }+ }+ },"A page jumps to where you sent it instead of gliding." : {"localizations" : {"cs" : {@@ -105527,6 +105633,112 @@}}},+ "Stop Homebrew?" : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Zastavit Homebrew?"+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrew stoppen?"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "¿Detener Homebrew?"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Arrêter Homebrew ?"+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vuoi interrompere Homebrew?"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrewを停止しますか?"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrew를 중단하겠습니까?"+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrew stoppen?"+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Zatrzymać Homebrew?"+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Parar o Homebrew?"+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Opriți Homebrew?"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Остановить Homebrew?"+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Vill du stoppa Homebrew?"+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Homebrew durdurulsun mu?"+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Зупинити Homebrew?"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要停止Homebrew吗?"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要停止Homebrew嗎?"+ }+ }+ }+ },"Stop Looking in %@" : {"localizations" : {"cs" : {@@ -117613,108 +117825,108 @@}}},- "This can take several minutes, and Peel can’t stop it once it starts." : {+ "This can take a long time, since Homebrew builds some packages on this Mac. Its progress shows on this page as it works, and you can stop it there." : {"localizations" : {"cs" : {"stringUnit" : {"state" : "translated",- "value" : "Může to trvat několik minut a jakmile to začne, Peel to nemůže zastavit."+ "value" : "Může to trvat dlouho, protože Homebrew některé balíčky sestavuje přímo v tomto Macu. Na této stránce můžete sledovat průběh a případně Homebrew zastavit."}},"de" : {"stringUnit" : {"state" : "translated",- "value" : "Das kann einige Minuten dauern, und Peel kann den Vorgang nicht mehr stoppen, sobald er begonnen hat."+ "value" : "Das kann lange dauern, da Homebrew manche Pakete auf diesem Mac kompiliert. Während Homebrew arbeitet, wird der Fortschritt auf dieser Seite angezeigt, und du kannst den Vorgang dort stoppen."}},"es" : {"stringUnit" : {"state" : "translated",- "value" : "Puede tardar varios minutos, y Peel no puede detenerlo una vez que empiece."+ "value" : "Puede tardar mucho, ya que Homebrew compila algunos paquetes en este Mac. Mientras Homebrew trabaja, esta página muestra su progreso, y desde ella puedes detenerlo."}},"fr" : {"stringUnit" : {"state" : "translated",- "value" : "Cela peut prendre plusieurs minutes, et Peel ne peut pas l’interrompre une fois l’opération lancée."+ "value" : "Cela peut prendre beaucoup de temps, car Homebrew compile certains paquets sur ce Mac. Sa progression s’affiche sur cette page au fur et à mesure, et vous pouvez l’y arrêter."}},"it" : {"stringUnit" : {"state" : "translated",- "value" : "Può richiedere diversi minuti e, dopo l’avvio, Peel non può interromperlo."+ "value" : "Può richiedere molto tempo, perché Homebrew compila alcuni pacchetti su questo Mac. L’avanzamento compare in questa pagina durante l’aggiornamento, e puoi interromperlo da qui."}},"ja" : {"stringUnit" : {"state" : "translated",- "value" : "数分かかることがあり、一度始まるとPeelでは止められません。"+ "value" : "Homebrewは一部のパッケージをこのMacでビルドするため、かなり時間がかかる場合があります。実行中は、進行状況がこのページに表示され、そこから停止することもできます。"}},"ko" : {"stringUnit" : {"state" : "translated",- "value" : "몇 분 정도 걸릴 수 있으며, 일단 시작되면 Peel이 중단할 수 없습니다."+ "value" : "Homebrew가 일부 패키지를 이 Mac에서 빌드하므로 시간이 오래 걸릴 수 있습니다. 작업하는 동안 진행 상황이 이 페이지에 표시되며, 여기에서 중단할 수 있습니다."}},"nl" : {"stringUnit" : {"state" : "translated",- "value" : "Dit kan enkele minuten duren en Peel kan het niet stoppen zodra het is begonnen."+ "value" : "Dit kan lang duren, omdat Homebrew sommige pakketten op deze Mac bouwt. De voortgang verschijnt op deze pagina terwijl Homebrew bezig is, en je kunt het daar stoppen."}},"pl" : {"stringUnit" : {"state" : "translated",- "value" : "Może to potrwać kilka minut, a gdy się zacznie, Peel nie może tego zatrzymać."+ "value" : "Może to potrwać dłuższy czas, ponieważ Homebrew kompiluje niektóre pakiety na tym Macu. Na tej stronie możesz na bieżąco śledzić postęp i zatrzymać uaktualnianie."}},"pt" : {"stringUnit" : {"state" : "translated",- "value" : "Isso pode levar vários minutos, e o Peel não pode interrompê-lo depois que começar."+ "value" : "Isso pode levar muito tempo, já que o Homebrew compila alguns pacotes neste Mac. O progresso aparece nesta página enquanto ele trabalha, e você pode interrompê-lo ali."}},"ro" : {"stringUnit" : {"state" : "translated",- "value" : "Procesul poate dura câteva minute, iar Peel nu îl poate opri odată pornit."+ "value" : "Procesul poate dura mult timp, deoarece Homebrew compilează unele pachete pe acest Mac. Progresul apare pe această pagină pe măsură ce Homebrew lucrează, iar de acolo îl puteți opri."}},"ru" : {"stringUnit" : {"state" : "translated",- "value" : "Это может занять несколько минут, и Peel не сможет остановить процесс, когда он начнется."+ "value" : "Это может занять много времени, потому что Homebrew собирает некоторые пакеты на этом Mac. Пока Homebrew работает, ход обновления отображается на этой странице, и там же его можно остановить."}},"sv" : {"stringUnit" : {"state" : "translated",- "value" : "Det kan ta flera minuter, och Peel kan inte stoppa det när det väl har börjat."+ "value" : "Det kan ta lång tid, eftersom Homebrew bygger vissa paket på den här datorn. Förloppet visas på den här sidan medan Homebrew arbetar, och där kan du stoppa det."}},"tr" : {"stringUnit" : {"state" : "translated",- "value" : "Bu işlem birkaç dakika sürebilir ve başladıktan sonra Peel onu durduramaz."+ "value" : "Bu işlem uzun sürebilir, çünkü Homebrew bazı paketleri bu Mac’te derler. Homebrew çalışırken ilerleme durumu bu sayfada görünür ve işlemi buradan durdurabilirsiniz."}},"uk" : {"stringUnit" : {"state" : "translated",- "value" : "Це може тривати кілька хвилин, і після початку Peel не зможе це зупинити."+ "value" : "Це може тривати довго, бо Homebrew збирає деякі пакети на цьому Mac. Перебіг оновлення видно на цій сторінці, поки воно триває, і тут його можна зупинити."}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "这可能需要几分钟,而且一旦开始,Peel就无法停止它。"+ "value" : "这可能需要很长时间,因为Homebrew会在这台Mac上构建某些软件包。升级进度会实时显示在此页面上,你也可以在此处停止升级。"}},"zh-Hant" : {"stringUnit" : {"state" : "translated",- "value" : "這可能需要幾分鐘,而且一旦開始,Peel就無法停止。"+ "value" : "這可能需要較長的時間,因為Homebrew會在這部Mac上建置某些套件。升級進行時,進度會顯示在此頁面上,你也可以在此停止升級。"}}}diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swiftindex 87890991..0ae987ea 100644--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift@@ -390,30 +390,36 @@ public enum Homebrew {return parseInstalled(Data(output.utf8))?.filter { $0.kind == .cask } ?? []}+ /// Upgrades `package` with no time limit, since Homebrew builds some packages on this Mac and that can take+ /// hours: `onOutput` is handed what Homebrew writes as it writes it, so the person can follow it, and the+ /// upgrade stops when its task is canceled.@concurrent- public static func upgrade(_ package: HomebrewPackage) async throws(CommandFailure) -> String {- try await run(["upgrade", package.kind == .cask ? "--cask" : "--formula", package.name], autoUpdate: true)+ public static func upgrade(_ package: HomebrewPackage, onOutput: @escaping @Sendable (Data) -> Void) async throws(CommandFailure) -> String {+ let arguments = ["upgrade", package.kind == .cask ? "--cask" : "--formula", package.name]+ return try await execute(arguments, autoUpdate: true, timeout: nil, onOutput: onOutput).transcript()}+ /// Upgrades `packages` the same way.@concurrent- public static func upgrade(_ packages: [HomebrewPackage]) async throws(CommandFailure) -> String {+ public static func upgrade(_ packages: [HomebrewPackage], onOutput: @escaping @Sendable (Data) -> Void) async throws(CommandFailure) -> String {// Said once: both calls below would fail the same way.guard executableURL != nil else { throw CommandFailure(output: notInstalled) }return try await upgrade(packages) { arguments throws(CommandFailure) in- try await execute(arguments, autoUpdate: true, timeout: longestCommand)+ try await execute(arguments, autoUpdate: true, timeout: nil, onOutput: onOutput)}}/// Formulae and casks go in separate calls because a name can belong to both. Both are attempted even when/// the first fails, whether `brew` reported the failure or never finished, so the report covers the whole- /// run. `execute` is a parameter so a test can stand in for `brew`.+ /// run, but nothing starts once the person has stopped it. `execute` is a parameter so a test can stand in for+ /// `brew`.static func upgrade(_ packages: [HomebrewPackage],execute: (_ arguments: [String]) async throws(CommandFailure) -> Attempt) async throws(CommandFailure) -> String {var output = ""var didFail = false- for kind in [HomebrewPackage.Kind.formula, .cask] {+ for kind in [HomebrewPackage.Kind.formula, .cask] where !Task.isCancelled {let names = packages.filter { $0.kind == kind }.map(\.name)guard !names.isEmpty else { continue }do {@@ -577,7 +583,7 @@ public enum Homebrew {return (formulae + casks).sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }}- /// The time limit for a command that can run long, such as an upgrade, which downloads and installs.+ /// The time limit for a command that can run long, such as an uninstall or a cleanup. An upgrade has none.private static let longestCommand: TimeInterval = 30 * 60/// The time limit for a question Homebrew answers from its local files.private static let longestAnswer: TimeInterval = 2 * 60@@ -612,14 +618,24 @@ public enum Homebrew {}}- private static func execute(_ arguments: [String], autoUpdate: Bool, timeout: TimeInterval) async throws(CommandFailure) -> Attempt {- guard let executable = executableURL else {+ /// Runs `brew`, or `executable` when a test stands in for it, since a real upgrade would change this Mac.+ static func execute(+ _ arguments: [String],+ autoUpdate: Bool,+ timeout: TimeInterval?,+ onOutput: (@Sendable (Data) -> Void)? = nil,+ executable: URL? = executableURL+ ) async throws(CommandFailure) -> Attempt {+ guard let executable else {throw CommandFailure(output: Self.notInstalled)}- switch await Subprocess.run(executable.path(percentEncoded: false), arguments, environment: environment(autoUpdate: autoUpdate), timeout: timeout) {+ let path = executable.path(percentEncoded: false)+ switch await Subprocess.run(path, arguments, environment: environment(autoUpdate: autoUpdate), timeout: timeout, onOutput: onOutput) {case .success(let output):return Attempt(status: output.status, standardOutput: output.text, standardError: output.errorText)case .failure(let failure):+ // A run someone follows shows Peel's own sentence where it happened, after what the tool wrote.+ onOutput?(Data((failure.explanation + "\n").utf8))throw CommandFailure(output: failure.explanation)}}diff --git a/Packages/PeelCore/Sources/PeelPrivileged/Subprocess.swift b/Packages/PeelCore/Sources/PeelPrivileged/Subprocess.swiftindex d147ef76..e7b3a284 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/Subprocess.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/Subprocess.swift@@ -2,10 +2,11 @@ import Darwinpublic import Foundationimport Synchronization-/// The one way Peel and its helper run a tool. Every run has a time limit and stops when its task is-/// canceled: a removal waits for `launchctl` and `defaults`, and a tool that never answers must not hold it-/// forever. The pipes are read with `read(2)`, because `FileHandle`'s `readDataToEndOfFile` and-/// `availableData` raise an exception on failure that Swift cannot catch (`NSFileHandle.h`).+/// The one way Peel and its helper run a tool. Every run stops when its task is canceled, and has a time limit+/// unless the person follows it and can stop it themselves: a removal waits for `launchctl` and `defaults`, and a+/// tool that never answers must not hold it forever. The pipes are read with `read(2)`, because `FileHandle`'s+/// `readDataToEndOfFile` and `availableData` raise an exception on failure that Swift cannot catch+/// (`NSFileHandle.h`).public enum Subprocess {public struct Output: Sendable, Hashable {public let status: Int32@@ -37,15 +38,17 @@ public enum Subprocess {/// outlive it and hold a pipe open, and the answer does not wait for that.static let drain: TimeInterval = 0.5- /// Runs `executable` with `arguments`, and stops it after `timeout` seconds or when the task is canceled.- /// When `environment` is given, it replaces Peel's own. Both streams are read while the tool runs, so a- /// tool that fills one pipe never waits on a reader that is busy with the other.+ /// Runs `executable` with `arguments`, and stops it after `timeout` seconds, when there is one, or when the task+ /// is canceled. When `environment` is given, it replaces Peel's own. Both streams are read while the tool runs,+ /// so a tool that fills one pipe never waits on a reader that is busy with the other, and `onOutput` is handed+ /// what either stream brings as it comes.@concurrentpublic static func run(_ executable: String,_ arguments: [String],environment: [String: String]? = nil,- timeout: TimeInterval+ timeout: TimeInterval?,+ onOutput: (@Sendable (Data) -> Void)? = nil) async -> Result<Output, Failure> {// A task stopped before this step starts nothing: launching the tool only to kill it would hold the Stop// for as long as the kill takes.@@ -66,9 +69,11 @@ public enum Subprocess {} catch {return .failure(.couldNotStart(error.localizedDescription))}- let output = Reader(outputPipe.fileHandleForReading.fileDescriptor)- let errors = Reader(errorPipe.fileHandleForReading.fileDescriptor)- DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout) { run.stop(because: .timedOut) }+ let output = Reader(outputPipe.fileHandleForReading.fileDescriptor, onRead: onOutput)+ let errors = Reader(errorPipe.fileHandleForReading.fileDescriptor, onRead: onOutput)+ if let timeout {+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout) { run.stop(because: .timedOut) }+ }await withTaskCancellationHandler {await run.wait()@@ -146,8 +151,11 @@ public enum Subprocess {}private let state = Mutex(State())+ /// Handed each piece as it is read, on the reading thread.+ private let onRead: (@Sendable (Data) -> Void)?- init(_ descriptor: Int32) {+ init(_ descriptor: Int32, onRead: (@Sendable (Data) -> Void)?) {+ self.onRead = onReadlet thread = Thread { [self] inread(descriptor)let waiter = state.withLock { state in@@ -185,6 +193,7 @@ public enum Subprocess {let count = Darwin.read(descriptor, &buffer, buffer.count)if count > 0 {state.withLock { $0.data.append(contentsOf: buffer[0..<count]) }+ onRead?(Data(buffer[0..<count]))} else if count == 0 || errno != EINTR {return}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swiftindex 009acb35..daa920f6 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift@@ -32,6 +32,28 @@ struct HomebrewTests {#expect(asked.withLock { $0 } == ["--formula", "--cask"])}+ /// A stop is the person's: once the formulae were stopped, the casks are not started.+ @Test func aStoppedUpgradeStartsNothingMore() async {+ let packages = [HomebrewPackage(name: "wget", kind: .formula, installedVersion: "1.0"), HomebrewPackage(name: "firefox", kind: .cask, installedVersion: "1.0")]+ let asked = Mutex<[String]>([])++ let run = Task { () -> String? in+ do throws(Homebrew.CommandFailure) {+ _ = try await Homebrew.upgrade(packages) { arguments throws(Homebrew.CommandFailure) in+ asked.withLock { $0.append(arguments[1]) }+ withUnsafeCurrentTask { $0?.cancel() }+ throw Homebrew.CommandFailure(output: "Stopped before it finished.")+ }+ return nil+ } catch {+ return error.output+ }+ }++ #expect(await run.value == "Stopped before it finished.\n")+ #expect(asked.withLock { $0 } == ["--formula"])+ }+/// Homebrew writes warnings to stderr and still exits 0, for example for a formula from a tap that uses a/// deprecated method. So the answer is read from stdout alone: JSON with a warning after it is not JSON.@Test func readsAnAnswerFromWhatWasPrintedAsTheAnswer() throws {@@ -138,6 +160,24 @@ struct HomebrewTests {#expect(needs("helper") == [true, true], "a kernel extension is unloaded with sudo, when upgrading too")}+ /// An upgrade someone follows shows what Homebrew wrote, then Peel's own sentence where it stopped. `/bin/sh`+ /// stands in for `brew`, since a real upgrade would change this Mac's packages.+ @Test func aFollowedRunSaysWhereItWasStopped() async throws {+ let written = Mutex(Data())+ let run = Task {+ try await Homebrew.execute(+ ["-c", "echo first; sleep 60"], autoUpdate: false, timeout: nil,+ onOutput: { piece in written.withLock { $0.append(piece) } },+ executable: URL(filePath: "/bin/sh")+ )+ }+ while written.withLock({ $0.isEmpty }) { await Task.yield() }+ run.cancel()++ await #expect(throws: Homebrew.CommandFailure.self) { try await run.value }+ #expect(String(decoding: written.withLock { $0 }, as: UTF8.self) == "first\nStopped before it finished.\n")+ }+/// The JSON follows what Homebrew 7.0.4 reports for packages it has stopped or will stop offering. A package/// can be deprecated and disabled at once (disabled wins), a deprecated one carries the day it will be/// disabled, and a reason is one of Homebrew's keywords or a sentence a maintainer wrote.diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SubprocessTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SubprocessTests.swiftindex 204536ac..ac070a23 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SubprocessTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SubprocessTests.swift@@ -1,9 +1,10 @@import Foundation@testable import PeelPrivileged+import Synchronizationimport Testing-/// A tool Peel runs must never hang Peel or crash it. Every run has a time limit, stops when its caller is-/// canceled, and returns a failure as a value, never as an exception.+/// A tool Peel runs must never hang Peel or crash it. Every run stops when its caller is canceled, has a time limit+/// unless the person follows it and can stop it, and returns a failure as a value, never as an exception.struct SubprocessTests {@Test func readsBothStreamsAndTheStatus() async throws {let result = await Subprocess.run("/bin/sh", ["-c", "echo out; echo err >&2; exit 3"], timeout: 30)@@ -46,6 +47,30 @@ struct SubprocessTests {#expect(result == .failure(.timedOut))}+ /// What a tool writes reaches whoever asked while the tool still runs, from either stream, so a long run can+ /// be followed as it goes.+ @Test func handsOverWhatTheToolWritesAsItWrites() async throws {+ let started = ContinuousClock.now+ let seen = Mutex<[(text: String, at: Duration)]>([])+ let output = try await Subprocess.run("/bin/sh", ["-c", "echo first; sleep 1; echo second >&2"], timeout: 30) { data in+ seen.withLock { $0.append((String(decoding: data, as: UTF8.self), ContinuousClock.now - started)) }+ }.get()++ let chunks = seen.withLock { $0 }+ let first = try #require(chunks.first { $0.text.contains("first") })+ let second = try #require(chunks.first { $0.text.contains("second") })+ #expect(second.at - first.at > .milliseconds(500), "the first line came only when the tool ended")+ #expect(output.text == "first\n" && output.errorText == "second\n")+ }++ /// A run without a time limit, which Homebrew's upgrades need, still stops when whoever asked goes away.+ @Test func aRunWithNoTimeLimitStopsWhenAsked() async {+ let task = Task { await Subprocess.run("/bin/sleep", ["600"], timeout: nil) }+ try? await Task.sleep(for: .milliseconds(300))+ task.cancel()+ #expect(await task.value == .failure(.canceled))+ }+@Test func aToolIsStoppedWhenWhoeverAskedGoesAway() async {let task = Task { await Subprocess.run("/bin/sleep", ["600"], timeout: 3_600) }// Long enough for the tool to start, even on a busy machine.diff --git a/Peel/Model/HomebrewLibrary.swift b/Peel/Model/HomebrewLibrary.swiftindex cd846490..f9301b12 100644--- a/Peel/Model/HomebrewLibrary.swift+++ b/Peel/Model/HomebrewLibrary.swift@@ -23,6 +23,14 @@ final class HomebrewLibrary {case .upgrade, .upgradeAll, .uninstall, .update, .cleanup: false}}++ /// An upgrade has no time limit, so its output is shown as it comes and the person can stop it.+ var isUpgrade: Bool {+ switch self {+ case .upgrade, .upgradeAll: true+ case .uninstall, .update, .cleanup, .health, .vulnerabilities: false+ }+ }}struct CommandResult: Identifiable {@@ -77,6 +85,11 @@ final class HomebrewLibrary {let scanRun = ScanRun()var isScanning: Bool { scanRun.isRunning }private(set) var runningCommand: Command?+ /// What Homebrew has written so far in the running upgrade. Nil when no upgrade runs.+ private(set) var progress: String?+ /// True once the person asked the running upgrade to stop.+ private(set) var isStopping = false+ private var runningTask: Task<CommandResult?, Never>?var selection: HomebrewPackage.ID?var result: CommandResult?@@ -159,13 +172,24 @@ final class HomebrewLibrary {func run(_ command: Command, showsResult: Bool = true) async -> CommandResult? {guard runningCommand == nil else { return nil }runningCommand = command- defer { runningCommand = nil }- let outcome = await outcome(of: command)+ defer {+ (runningCommand, runningTask, progress, isStopping) = (nil, nil, nil, false)+ }+ let task = Task { await outcome(of: command) }+ runningTask = task+ let outcome = await task.valueif showsResult, let outcome { result = outcome }if !command.onlyLooks { await refresh(includingReclaimable: true) }return outcome}+ /// Stops the running upgrade: Homebrew is asked to stop, and killed if it does not.+ func stopUpgrade() {+ guard runningCommand?.isUpgrade == true else { return }+ isStopping = true+ runningTask?.cancel()+ }+/// Nil for a command that only looks and keeps what it found in `findings` or `advisories`.private func outcome(of command: Command) async -> CommandResult? {if !command.onlyLooks {@@ -178,9 +202,10 @@ final class HomebrewLibrary {switch command {case .upgrade(let id):guard let package = package(id) else { return gone }- output = try await Homebrew.upgrade(package)+ return await following { onOutput throws(Homebrew.CommandFailure) in try await Homebrew.upgrade(package, onOutput: onOutput) }case .upgradeAll:- output = try await Homebrew.upgrade(upgradable)+ let packages = upgradable+ 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)@@ -207,6 +232,38 @@ final class HomebrewLibrary {}}+ /// Runs an upgrade while `progress` shows what Homebrew writes, in the order it writes it, with Peel's own+ /// sentence where a stop or a failure to start happened. That whole transcript is the result, a stopped run's+ /// included, since it is where Homebrew says what it had done.+ private func following(+ _ upgrade: (@escaping @Sendable (Data) -> Void) async throws(Homebrew.CommandFailure) -> String+ ) async -> CommandResult {+ progress = ""+ let (pieces, sink) = AsyncStream.makeStream(of: Data.self)+ let shown = Task {+ var written = Data()+ for await piece in pieces {+ written.append(piece)+ progress = String(decoding: written, as: UTF8.self)+ }+ }+ let outcome: Result<String, Homebrew.CommandFailure>+ do {+ outcome = .success(try await upgrade { sink.yield($0) })+ } catch {+ outcome = .failure(error)+ }+ sink.finish()+ await shown.value+ let written = progress ?? ""+ switch outcome {+ case .success(let output):+ return CommandResult(succeeded: true, output: written.isEmpty ? output : written)+ case .failure(let failure):+ return CommandResult(succeeded: false, output: written.isEmpty ? failure.output : written)+ }+ }+private func package(_ id: HomebrewPackage.ID) -> HomebrewPackage? {packages?.first { $0.id == id }}diff --git a/Peel/Views/ContentView.swift b/Peel/Views/ContentView.swiftindex efd0f7a3..349335b7 100644--- a/Peel/Views/ContentView.swift+++ b/Peel/Views/ContentView.swift@@ -415,7 +415,9 @@ struct ContentView: View {@ViewBuilderprivate var homebrewDetail: some View {- if let package = homebrew.selectedPackage {+ if homebrew.progress != nil {+ HomebrewProgressView()+ } else if let package = homebrew.selectedPackage {HomebrewDetailView(package: package).id(package.id)} else {diff --git a/Peel/Views/Homebrew/HomebrewList.swift b/Peel/Views/Homebrew/HomebrewList.swiftindex 22866f94..97f3b29a 100644--- a/Peel/Views/Homebrew/HomebrewList.swift+++ b/Peel/Views/Homebrew/HomebrewList.swift@@ -59,7 +59,7 @@ struct HomebrewList: View {Button("Upgrade All") { start(.upgradeAll) }Button("Cancel", role: .cancel) {}} message: {- Text("This can take several minutes, and Peel can’t stop it once it starts.")+ Text("This can take a long time, since Homebrew builds some packages on this Mac. Its progress shows on this page as it works, and you can stop it there.")}// Clean Up is confirmed first, like Uninstall on a package's page, because Homebrew deletes these files// permanently and History can't put them back.diff --git a/Peel/Views/Homebrew/HomebrewProgressView.swift b/Peel/Views/Homebrew/HomebrewProgressView.swiftnew file mode 100644index 00000000..e576b4b4--- /dev/null+++ b/Peel/Views/Homebrew/HomebrewProgressView.swift@@ -0,0 +1,41 @@+import SwiftUI++/// What Homebrew writes while it upgrades, shown as it comes, with a way to stop it. An upgrade has no time limit,+/// since Homebrew builds some packages on this Mac, so the person decides when it has run long enough.+struct HomebrewProgressView: View {+ @Environment(HomebrewLibrary.self) private var homebrew+ @State private var isConfirmingStop = false++ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 8) {+ ProgressView()+ .controlSize(.small)+ Text("Running Homebrew…")+ .font(.headline)+ Spacer()+ Button("Stop", systemImage: "stop.fill") { isConfirmingStop = true }+ .disabled(homebrew.isStopping)+ }+ ScrollView {+ Text(verbatim: lastLines)+ .font(.system(.callout, design: .monospaced))+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .defaultScrollAnchor(.bottom)+ }+ .padding(20)+ .confirmationDialog("Stop Homebrew?", isPresented: $isConfirmingStop) {+ Button("Stop", role: .destructive) { homebrew.stopUpgrade() }+ Button("Cancel", role: .cancel) {}+ } message: {+ Text("A package Homebrew is in the middle of installing may be left half installed, and may need installing again.")+ }+ }++ /// The last lines only, so a long build costs no more to draw than a screenful. The result shows them all.+ private var lastLines: String {+ (homebrew.progress ?? "").split(separator: "\n", omittingEmptySubsequences: false).suffix(400).joined(separator: "\n")+ }+}