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.

Show what Homebrew writes in the order it wrote it

Țugui Dragoșbc79c4eec702
diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
index 6a04cc2d..135539b4 100644
--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
@@ -541,7 +541,8 @@ public enum Homebrew {
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()
+ return try await execute(arguments, autoUpdate: true, timeout: nil, inWritingOrder: true, onOutput: onOutput)
+ .transcript()
}
/// Upgrades `packages` the same way.
@@ -553,7 +554,7 @@ public enum Homebrew {
// 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: nil, onOutput: onOutput)
+ try await execute(arguments, autoUpdate: true, timeout: nil, inWritingOrder: true, onOutput: onOutput)
}
}
@@ -694,7 +695,7 @@ public enum Homebrew {
/// Returns what `brew doctor` prints, for a Homebrew that cannot be asked for JSON.
@concurrent
public static func healthReport() async -> String {
- let attempt = try? await execute(["doctor"], autoUpdate: false, timeout: longestCommand)
+ let attempt = try? await execute(["doctor"], autoUpdate: false, timeout: longestCommand, inWritingOrder: true)
return attempt?.output ?? ""
}
@@ -704,7 +705,9 @@ public enum Homebrew {
_ 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()
+ return try await execute(
+ arguments, autoUpdate: false, keeping: kept, timeout: longestCommand, inWritingOrder: true
+ ).transcript()
}
@concurrent
@@ -734,7 +737,9 @@ public enum Homebrew {
public static func cleanup(
_ cleanup: Cleanup = .standard, keeping kept: [String]
) async throws(CommandFailure) -> String {
- try await execute(cleanup.arguments, autoUpdate: false, keeping: kept, timeout: longestCommand).transcript()
+ try await execute(
+ cleanup.arguments, autoUpdate: false, keeping: kept, timeout: longestCommand, inWritingOrder: true
+ ).transcript()
}
static let repairTapsArguments = ["tap", "--repair"]
@@ -743,7 +748,8 @@ public enum Homebrew {
/// main branch (`brew tap --help`). It deletes nothing.
@concurrent
public static func repairTaps() async throws(CommandFailure) -> String {
- try await execute(repairTapsArguments, autoUpdate: false, timeout: longestCommand).transcript()
+ try await execute(repairTapsArguments, autoUpdate: false, timeout: longestCommand, inWritingOrder: true)
+ .transcript()
}
/// True when Homebrew, its own `brew.env` files read, still keeps every formula in `kept`. Such a file can
@@ -830,7 +836,8 @@ public enum Homebrew {
/// Runs a command whose output is shown to the user, and returns everything it printed.
private static func run(_ arguments: [String], autoUpdate: Bool) async throws(CommandFailure) -> String {
- try await execute(arguments, autoUpdate: autoUpdate, timeout: longestCommand).transcript()
+ try await execute(arguments, autoUpdate: autoUpdate, timeout: longestCommand, inWritingOrder: true)
+ .transcript()
}
/// Runs a command whose output Peel reads (JSON, a path, a list, or a version), and returns its stdout.
@@ -861,12 +868,14 @@ public enum Homebrew {
}
}
- /// Runs `brew`, or `executable` when a test stands in for it, since a real upgrade would change this Mac.
+ /// Runs `brew`, or `executable` when a test stands in for it, since a real upgrade would change this Mac. A run
+ /// shown to the person keeps what Homebrew writes `inWritingOrder`: its warnings and errors among its steps.
static func execute(
_ arguments: [String],
autoUpdate: Bool,
keeping kept: [String] = [],
timeout: TimeInterval?,
+ inWritingOrder: Bool = false,
onOutput: (@Sendable (Data) -> Void)? = nil,
executable: URL? = executableURL,
readsTheAPI: Bool = true,
@@ -879,7 +888,10 @@ public enum Homebrew {
let environment = environment(
autoUpdate: autoUpdate, keeping: kept, executable: executable, readsTheAPI: readsTheAPI, home: home
)
- switch await Subprocess.run(path, arguments, environment: environment, timeout: timeout, onOutput: onOutput) {
+ switch await Subprocess.run(
+ path, arguments, environment: environment, timeout: timeout, errorsIntoOutput: inWritingOrder,
+ onOutput: onOutput
+ ) {
case .success(let output):
return Attempt(status: output.status, standardOutput: output.text, standardError: output.errorText)
case .failure(let failure):
@@ -956,6 +968,9 @@ public enum Homebrew {
// `brew upgrade` asks before it goes on unless this is set, and nobody is there to answer. It skips
// the question only because no terminal is attached (`ask.rb`). A version without it ignores it.
"HOMEBREW_NO_ASK": "1",
+ // `brew.rb` writes each line as it goes only under `CI`. Otherwise Ruby holds what goes to standard
+ // output back in a pipe, and an error printed after a step shows before it.
+ "CI": "1",
]
if !autoUpdate {
values["HOMEBREW_NO_AUTO_UPDATE"] = "1"
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/Subprocess.swift b/Packages/PeelCore/Sources/PeelPrivileged/Subprocess.swift
index fea9e120..8517b54b 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/Subprocess.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/Subprocess.swift
@@ -41,13 +41,15 @@ public enum Subprocess {
/// 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.
+ /// what either stream brings as it comes. With `errorsIntoOutput`, the tool writes its errors into its output's
+ /// pipe, so the two read in the order it wrote them and `standardError` is empty.
@concurrent
public static func run(
_ executable: String,
_ arguments: [String],
environment: [String: String]? = nil,
timeout: TimeInterval?,
+ errorsIntoOutput: Bool = false,
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
@@ -58,9 +60,10 @@ public enum Subprocess {
process.arguments = arguments
if let environment { process.environment = environment }
process.standardInput = FileHandle.nullDevice
- let (outputPipe, errorPipe) = (Pipe(), Pipe())
+ let outputPipe = Pipe()
+ let errorPipe = errorsIntoOutput ? nil : Pipe()
process.standardOutput = outputPipe
- process.standardError = errorPipe
+ process.standardError = errorPipe ?? outputPipe
let run = Run(process)
// The handler holds the run, which holds the process that holds the handler (`NSTask.h`), so it is let go
@@ -73,7 +76,7 @@ public enum Subprocess {
return .failure(.couldNotStart(error.localizedDescription))
}
let output = Reader(outputPipe.fileHandleForReading.fileDescriptor, onRead: onOutput)
- let errors = Reader(errorPipe.fileHandleForReading.fileDescriptor, onRead: onOutput)
+ let errors = errorPipe.map { Reader($0.fileHandleForReading.fileDescriptor, onRead: onOutput) }
if let timeout {
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout) { [weak run] in
run?.stop(because: .timedOut)
@@ -85,10 +88,11 @@ public enum Subprocess {
} onCancel: {
run.stop(because: .canceled)
}
- let (standardOutput, standardError) = (await output.data(within: drain), await errors.data(within: drain))
+ let standardOutput = await output.data(within: drain)
+ let standardError = await errors?.data(within: drain) ?? Data()
// Both readers have stopped by now, so nothing reads the descriptors any more.
try? outputPipe.fileHandleForReading.close()
- try? errorPipe.fileHandleForReading.close()
+ try? errorPipe?.fileHandleForReading.close()
if let failure = run.failure { return .failure(failure) }
return .success(
Output(status: process.terminationStatus, standardOutput: standardOutput, standardError: standardError)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift
index f799e131..245f44a4 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/HomebrewTests.swift
@@ -26,6 +26,31 @@ struct HomebrewTests {
#expect(tap.contains("--repair"))
}
+ @Test func whatHomebrewWritesIsShownInTheOrderItWroteIt() async throws {
+ let directory = try TemporaryDirectory()
+ let brew = try directory.file("bin/brew", contents: Data("""
+ #!/usr/bin/ruby
+ if ENV["CI"]
+ $stdout.sync = true
+ $stderr.sync = true
+ end
+ puts "==> Upgrading example"
+ $stderr.puts "Error: It seems the App source is not there."
+ puts "==> Summary"
+ exit 1
+ """.utf8))
+ try directory.setPermissions(0o755, of: brew)
+
+ let shown = try await Homebrew.execute(
+ ["upgrade"], autoUpdate: false, timeout: 30, inWritingOrder: true, executable: brew
+ )
+ let read = try await Homebrew.execute(["upgrade"], autoUpdate: false, timeout: 30, executable: brew)
+
+ #expect(shown.output == "==> Upgrading example\nError: It seems the App source is not there.\n==> Summary\n")
+ #expect(read.standardOutput == "==> Upgrading example\n==> Summary\n")
+ #expect(read.standardError == "Error: It seems the App source is not there.\n")
+ }
+
@Test func anUpgradeNeverWaitsForAnAnswer() {
for autoUpdate in [true, false] {
#expect(Homebrew.environment(autoUpdate: autoUpdate)["HOMEBREW_NO_ASK"] == "1")
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SubprocessTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SubprocessTests.swift
index 626294a6..9d5e12db 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/SubprocessTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/SubprocessTests.swift
@@ -15,6 +15,14 @@ struct SubprocessTests {
#expect(output.errorText == "err\n")
}
+ @Test func aToolsErrorsCanBeReadInTheOrderItWroteThem() async throws {
+ let script = "echo first; echo second >&2; echo third"
+ let output = try await Subprocess.run("/bin/sh", ["-c", script], timeout: 30, errorsIntoOutput: true).get()
+
+ #expect(output.text == "first\nsecond\nthird\n")
+ #expect(output.standardError.isEmpty)
+ }
+
/// A pipe holds at most 64 KB. If one stream were read to its end before the other, a tool that fills the
/// other would block and never end.
@Test func aToolThatWritesALotToBothStreamsStillEnds() async throws {