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