|
| 1 | +import AppKit |
| 2 | +import Foundation |
| 3 | + |
| 4 | +public protocol TerminalType { |
| 5 | + func streamCommand( |
| 6 | + _ command: String, |
| 7 | + arguments: [String], |
| 8 | + currentDirectoryPath: String, |
| 9 | + environment: [String: String] |
| 10 | + ) -> AsyncThrowingStream<String, Error> |
| 11 | + |
| 12 | + func runCommand( |
| 13 | + _ command: String, |
| 14 | + arguments: [String], |
| 15 | + currentDirectoryPath: String, |
| 16 | + environment: [String: String] |
| 17 | + ) async throws -> String |
| 18 | +} |
| 19 | + |
| 20 | +public final class Terminal: TerminalType, @unchecked Sendable { |
| 21 | + var process: Process? |
| 22 | + var outputPipe: Pipe? |
| 23 | + var inputPipe: Pipe? |
| 24 | + |
| 25 | + public struct TerminationError: Error { |
| 26 | + public let reason: Process.TerminationReason |
| 27 | + public let status: Int32 |
| 28 | + } |
| 29 | + |
| 30 | + public init() {} |
| 31 | + |
| 32 | + func getEnvironmentVariables() -> [String: String] { |
| 33 | + let env = ProcessInfo.processInfo.environment |
| 34 | + .merging(["LANG": "en_US.UTF-8"], uniquingKeysWith: { $1 }) |
| 35 | + return env |
| 36 | + } |
| 37 | + |
| 38 | + public func streamCommand( |
| 39 | + _ command: String = "/bin/bash", |
| 40 | + arguments: [String], |
| 41 | + currentDirectoryPath: String = "/", |
| 42 | + environment: [String: String] |
| 43 | + ) -> AsyncThrowingStream<String, Error> { |
| 44 | + self.process?.terminate() |
| 45 | + let process = Process() |
| 46 | + self.process = process |
| 47 | + |
| 48 | + process.launchPath = command |
| 49 | + process.currentDirectoryPath = currentDirectoryPath |
| 50 | + process.arguments = arguments |
| 51 | + process.environment = getEnvironmentVariables() |
| 52 | + .merging(environment, uniquingKeysWith: { $1 }) |
| 53 | + |
| 54 | + let outputPipe = Pipe() |
| 55 | + process.standardOutput = outputPipe |
| 56 | + process.standardError = outputPipe |
| 57 | + self.outputPipe = outputPipe |
| 58 | + |
| 59 | + let inputPipe = Pipe() |
| 60 | + process.standardInput = inputPipe |
| 61 | + self.inputPipe = inputPipe |
| 62 | + |
| 63 | + var continuation: AsyncThrowingStream<String, Error>.Continuation! |
| 64 | + let contentStream = AsyncThrowingStream<String, Error> { cont in |
| 65 | + continuation = cont |
| 66 | + } |
| 67 | + |
| 68 | + Task { [continuation, self] in |
| 69 | + let notificationCenter = NotificationCenter.default |
| 70 | + let notifications = notificationCenter.notifications( |
| 71 | + named: FileHandle.readCompletionNotification, |
| 72 | + object: outputPipe.fileHandleForReading |
| 73 | + ) |
| 74 | + for await notification in notifications { |
| 75 | + let userInfo = notification.userInfo |
| 76 | + if let data = userInfo?[NSFileHandleNotificationDataItem] as? Data, |
| 77 | + let content = String(data: data, encoding: .utf8), |
| 78 | + !content.isEmpty |
| 79 | + { |
| 80 | + continuation?.yield(content) |
| 81 | + } |
| 82 | + if !(self.process?.isRunning ?? false) { |
| 83 | + let reason = self.process?.terminationReason ?? .exit |
| 84 | + let status = self.process?.terminationStatus ?? 1 |
| 85 | + if let output = (self.process?.standardOutput as? Pipe)?.fileHandleForReading.readDataToEndOfFile(), |
| 86 | + let content = String(data: output, encoding: .utf8), |
| 87 | + !content.isEmpty |
| 88 | + { |
| 89 | + continuation?.yield(content) |
| 90 | + } |
| 91 | + |
| 92 | + if status == 0 { |
| 93 | + continuation?.finish() |
| 94 | + } else { |
| 95 | + continuation?.finish(throwing: TerminationError( |
| 96 | + reason: reason, |
| 97 | + status: status |
| 98 | + )) |
| 99 | + } |
| 100 | + break |
| 101 | + } |
| 102 | + Task { @MainActor in |
| 103 | + outputPipe.fileHandleForReading.readInBackgroundAndNotify(forModes: [.common]) |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + Task { @MainActor in |
| 109 | + outputPipe.fileHandleForReading.readInBackgroundAndNotify(forModes: [.common]) |
| 110 | + } |
| 111 | + |
| 112 | + do { |
| 113 | + try process.run() |
| 114 | + } catch { |
| 115 | + continuation.finish(throwing: error) |
| 116 | + } |
| 117 | + |
| 118 | + return contentStream |
| 119 | + } |
| 120 | + |
| 121 | + public func runCommand( |
| 122 | + _ command: String = "/bin/bash", |
| 123 | + arguments: [String], |
| 124 | + currentDirectoryPath: String = "/", |
| 125 | + environment: [String: String] |
| 126 | + ) async throws -> String { |
| 127 | + let stream = streamCommand( |
| 128 | + command, |
| 129 | + arguments: arguments, |
| 130 | + currentDirectoryPath: currentDirectoryPath, |
| 131 | + environment: environment |
| 132 | + ) |
| 133 | + var result = "" |
| 134 | + for try await output in stream { |
| 135 | + result += output |
| 136 | + } |
| 137 | + return result |
| 138 | + } |
| 139 | + |
| 140 | + func writeInput(_ input: String) { |
| 141 | + guard let data = input.data(using: .utf8) else { |
| 142 | + return |
| 143 | + } |
| 144 | + |
| 145 | + inputPipe?.fileHandleForWriting.write(data) |
| 146 | + inputPipe?.fileHandleForWriting.closeFile() |
| 147 | + } |
| 148 | +} |
0 commit comments