xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XCLIUtils / CommandInput.swift
CommandInput.swift65 lines · 2.0 KiBRaw
| 1 | import Dependencies |
| 2 | import Foundation |
| 3 | import XUtils |
| 4 | |
| 5 | package struct CommandInput: DependencyKey, Sendable { |
| 6 | // nil = EOF |
| 7 | private let readImpl: @Sendable (DataChannel.Limit) async throws -> Data? |
| 8 | |
| 9 | package init( |
| 10 | read: @escaping @Sendable (DataChannel.Limit) async throws -> Data?, |
| 11 | ) { |
| 12 | self.readImpl = read |
| 13 | } |
| 14 | |
| 15 | package init(channel: DataChannel) { |
| 16 | self.init(read: { try await channel.read(upTo: $0) }) |
| 17 | } |
| 18 | |
| 19 | package func read(upTo limit: DataChannel.Limit = .unlimited) async throws -> Data? { |
| 20 | try Task.checkCancellation() |
| 21 | return try await readImpl(limit) |
| 22 | } |
| 23 | |
| 24 | /// Cancellation discards bytes already consumed for this line. |
| 25 | package func readLine() async throws -> String? { |
| 26 | var line = Data() |
| 27 | while let chunk = try await read(upTo: .newline) { |
| 28 | line.append(chunk) |
| 29 | if line.last == UInt8(ascii: "\n") { |
| 30 | line.removeLast() |
| 31 | return String(decoding: line, as: UTF8.self).trimmingTrailingCarriageReturn() |
| 32 | } |
| 33 | } |
| 34 | guard !line.isEmpty else { return nil } |
| 35 | return String(decoding: line, as: UTF8.self).trimmingTrailingCarriageReturn() |
| 36 | } |
| 37 | |
| 38 | package static var liveValue: CommandInput { |
| 39 | @Dependency(\.shutdownRegistry) var shutdownRegistry |
| 40 | do { |
| 41 | let input = try DispatchInput(fileDesciptor: .standardInput) |
| 42 | shutdownRegistry.register { await input.close() } |
| 43 | return Self(read: { try await input.read(upTo: $0) }) |
| 44 | } catch { |
| 45 | return Self(read: { _ in throw error }) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | package static var testValue: CommandInput { |
| 50 | Self(read: unimplemented("CommandInput.read", placeholder: nil)) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | private extension String { |
| 55 | func trimmingTrailingCarriageReturn() -> String { |
| 56 | hasSuffix("\r") ? String(dropLast()) : self |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | extension DependencyValues { |
| 61 | package var input: CommandInput { |
| 62 | get { self[CommandInput.self] } |
| 63 | set { self[CommandInput.self] = newValue } |
| 64 | } |
| 65 | } |