xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XUtils / CommandOutput.swift
CommandOutput.swift79 lines · 2.4 KiBRaw
| 1 | // swiftlint:disable prefer_dependency_print |
| 2 | |
| 3 | import Dependencies |
| 4 | import Foundation |
| 5 | import CXKit |
| 6 | |
| 7 | public struct CommandOutput: DependencyKey, Sendable { |
| 8 | public enum Stream: String, Codable, Sendable { |
| 9 | case stdout |
| 10 | case stderr |
| 11 | } |
| 12 | |
| 13 | public var write: @Sendable (_ data: Data, _ stream: Stream, _ flush: Bool) -> Void |
| 14 | |
| 15 | public init(write: @escaping @Sendable (Data, Stream, Bool) -> Void) { |
| 16 | self.write = write |
| 17 | } |
| 18 | |
| 19 | public func print( |
| 20 | _ message: String = "", |
| 21 | terminator: String = "\n", |
| 22 | stream: Stream = .stdout, |
| 23 | flush: Bool = false |
| 24 | ) { |
| 25 | write(Data((message + terminator).utf8), stream, flush) |
| 26 | } |
| 27 | |
| 28 | @_disfavoredOverload |
| 29 | public func print( |
| 30 | _ items: Any..., |
| 31 | separator: String = " ", |
| 32 | terminator: String = "\n", |
| 33 | stream: Stream = .stdout, |
| 34 | flush: Bool = false |
| 35 | ) { |
| 36 | print( |
| 37 | items.map { String(describing: $0) }.joined(separator: separator), |
| 38 | terminator: terminator, |
| 39 | stream: stream, |
| 40 | flush: flush |
| 41 | ) |
| 42 | } |
| 43 | |
| 44 | public static var liveValue: Self { |
| 45 | let outputLock = NSLock() |
| 46 | return Self { data, stream, flush in |
| 47 | let descriptor: FileDescriptor = stream == .stdout ? .standardOutput : .standardError |
| 48 | // Keep concurrent messages together, including across partial writes. |
| 49 | outputLock.withLock { |
| 50 | try? data.withUnsafeBytes { try descriptor.writeAllWaiting($0) } |
| 51 | if flush { fflush(get_stdout()) } |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | public static var testValue: Self { Self(write: unimplemented("CommandOutput.write")) } |
| 57 | } |
| 58 | |
| 59 | extension CommandOutput { |
| 60 | /// Create a `FileDescriptor` for writing to the given `CommandOutput` stream. |
| 61 | public func makeDescriptor(for stream: Stream) throws -> FileDescriptor { |
| 62 | let (readFD, writeFD) = try FileDescriptor.pipe() |
| 63 | let input = try DispatchInput(fileDesciptor: readFD) |
| 64 | // no need to keep a handle to the task, it'll terminate when writeFD is closed |
| 65 | Task { |
| 66 | while let next = try? await input.read() { |
| 67 | self.write(next, stream, false) |
| 68 | } |
| 69 | } |
| 70 | return writeFD |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | extension DependencyValues { |
| 75 | public var out: CommandOutput { |
| 76 | get { self[CommandOutput.self] } |
| 77 | set { self[CommandOutput.self] = newValue } |
| 78 | } |
| 79 | } |