|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/// Represents a stream that can write text with a specific set of ANSI colors |
| 4 | +protocol ColoredStream: TextOutputStream { |
| 5 | + mutating func write(_ string: String, with: [ANSIColor]) |
| 6 | +} |
| 7 | + |
| 8 | +extension ColoredStream { |
| 9 | + /// Default conformance to TextOutputStream |
| 10 | + mutating func write(_ string: String) { |
| 11 | + write(string, with: []) |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +/// An output stream that prints to an underlying stream including ANSI color |
| 16 | +/// codes. |
| 17 | +class ColoredANSIStream<StreamTy: TextOutputStream>: ColoredStream { |
| 18 | + |
| 19 | + typealias StreamType = StreamTy |
| 20 | + |
| 21 | + var currentColors = [ANSIColor]() |
| 22 | + var stream: StreamType |
| 23 | + let colored: Bool |
| 24 | + |
| 25 | + /// Creates a new ColoredANSIStream that prints to an underlying stream. |
| 26 | + /// |
| 27 | + /// - Parameters: |
| 28 | + /// - stream: The underlying stream |
| 29 | + /// - colored: Whether to provide any colors or to pass text through |
| 30 | + /// unmodified. Set this to false and ColoredANSIStream is |
| 31 | + /// a transparent wrapper. |
| 32 | + init(_ stream: inout StreamType, colored: Bool = true) { |
| 33 | + self.stream = stream |
| 34 | + self.colored = colored |
| 35 | + } |
| 36 | + |
| 37 | + /// Initializes with a stream, always colored. |
| 38 | + /// |
| 39 | + /// - Parameter stream: The underlying stream receiving writes. |
| 40 | + required init(_ stream: inout StreamType) { |
| 41 | + self.stream = stream |
| 42 | + self.colored = true |
| 43 | + } |
| 44 | + |
| 45 | + /// Adds a color to the in-progress colors. |
| 46 | + func addColor(_ color: ANSIColor) { |
| 47 | + guard colored else { return } |
| 48 | + stream.write(color.rawValue) |
| 49 | + currentColors.append(color) |
| 50 | + } |
| 51 | + |
| 52 | + /// Resets this stream back to the default color. |
| 53 | + func reset() { |
| 54 | + if currentColors.isEmpty { return } |
| 55 | + stream.write(ANSIColor.reset.rawValue) |
| 56 | + currentColors = [] |
| 57 | + } |
| 58 | + |
| 59 | + /// Sets the current ANSI color codes to the passed-in colors. |
| 60 | + func setColors(_ colors: [ANSIColor]) { |
| 61 | + guard colored else { return } |
| 62 | + reset() |
| 63 | + for color in colors { |
| 64 | + stream.write(color.rawValue) |
| 65 | + } |
| 66 | + currentColors = colors |
| 67 | + } |
| 68 | + |
| 69 | + /// Writes the string to the output with the provided colors. |
| 70 | + /// |
| 71 | + /// - Parameters: |
| 72 | + /// - string: The string to write |
| 73 | + /// - colors: The colors used on the string |
| 74 | + func write(_ string: String, with colors: [ANSIColor]) { |
| 75 | + self.setColors(colors) |
| 76 | + stream.write(string) |
| 77 | + self.reset() |
| 78 | + } |
| 79 | +} |
0 commit comments