forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSuggestionServiceMiddleware.swift
More file actions
230 lines (202 loc) · 7.78 KB
/
Copy pathSuggestionServiceMiddleware.swift
File metadata and controls
230 lines (202 loc) · 7.78 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import Foundation
import Logger
import SuggestionBasic
public protocol SuggestionServiceMiddleware {
typealias Next = (SuggestionRequest) async -> AsyncThrowingStream<[CodeSuggestion], Error>
func getSuggestion(
_ request: SuggestionRequest,
configuration: SuggestionServiceConfiguration,
next: @escaping Next
) async -> AsyncThrowingStream<[CodeSuggestion], Error>
}
public enum SuggestionServiceMiddlewareContainer {
static var frontMiddlewares: [SuggestionServiceMiddleware] = [
PostProcessingSuggestionServiceMiddleware(),
]
static var builtInMiddlewares: [SuggestionServiceMiddleware] = [
DisabledLanguageSuggestionServiceMiddleware(),
MockResultSuggestionServiceMiddleware(),
]
static var leadingMiddlewares: [SuggestionServiceMiddleware] = []
static var trailingMiddlewares: [SuggestionServiceMiddleware] = []
public static var middlewares: [SuggestionServiceMiddleware] {
frontMiddlewares + leadingMiddlewares + builtInMiddlewares + trailingMiddlewares
}
public static func addMiddleware(_ middleware: SuggestionServiceMiddleware) {
trailingMiddlewares.append(middleware)
}
public static func addMiddlewares(_ middlewares: [SuggestionServiceMiddleware]) {
trailingMiddlewares.append(contentsOf: middlewares)
}
public static func addLeadingMiddleware(_ middleware: SuggestionServiceMiddleware) {
leadingMiddlewares.append(middleware)
}
public static func addLeadingMiddlewares(_ middlewares: [SuggestionServiceMiddleware]) {
leadingMiddlewares.append(contentsOf: middlewares)
}
}
public struct DisabledLanguageSuggestionServiceMiddleware: SuggestionServiceMiddleware {
public init() {}
struct DisabledLanguageError: Error, LocalizedError {
let language: String
var errorDescription: String? {
"Suggestion service is disabled for \(language)."
}
}
public func getSuggestion(
_ request: SuggestionRequest,
configuration: SuggestionServiceConfiguration,
next: @escaping Next
) async -> AsyncThrowingStream<[CodeSuggestion], Error> {
let language = languageIdentifierFromFileURL(request.fileURL)
if UserDefaults.shared.value(for: \.suggestionFeatureDisabledLanguageList)
.contains(where: { $0 == language.rawValue })
{
return .init {
$0.finish(throwing: DisabledLanguageError(language: language.rawValue))
}
}
return await next(request)
}
}
public struct DebugSuggestionServiceMiddleware: SuggestionServiceMiddleware {
public init() {}
public func getSuggestion(
_ request: SuggestionRequest,
configuration: SuggestionServiceConfiguration,
next: @escaping Next
) async -> AsyncThrowingStream<[CodeSuggestion], Error> {
Logger.service.info("""
Get suggestion for \(request.fileURL) at \(request.cursorPosition)
""")
return await next(request).handled(
handleCodeSuggestions: { suggestions in
Logger.service.info("""
Receive \(suggestions.count) suggestions for \(request.fileURL) \
at \(request.cursorPosition)
""")
return suggestions
},
handleError: { error in
Logger.service.info("""
Error: \(error.localizedDescription)
""")
return error
}
)
}
}
public struct MockResultSuggestionServiceMiddleware: SuggestionServiceMiddleware {
public init() {}
let mock = false
public func getSuggestion(
_ request: SuggestionRequest,
configuration: SuggestionServiceConfiguration,
next: @escaping Next
) async -> AsyncThrowingStream<[CodeSuggestion], any Error> {
#if DEBUG
let stream = await next(request)
if !mock {
return stream
}
return .init { continuation in
let task = Task {
let lineNumber = request.cursorPosition.line
let lineContent = request.lines[lineNumber]
continuation.yield([
CodeSuggestion(
id: "mock-suggestion-1",
text: lineContent.replacingOccurrences(of: "\n", with: "!"),
position: CursorPosition(
line: lineNumber,
character: lineContent.utf16.count - 1
),
range: CursorRange(
start: CursorPosition(line: lineNumber, character: 0),
end: CursorPosition(
line: lineNumber,
character: lineContent.utf16.count - 1
)
),
effectiveRange: .replacingRange,
replacingLines: [lineContent],
descriptions: [],
middlewareComments: ["MockResultSuggestionServiceMiddleware"],
metadata: [.group: "Mock Suggestions"]
),
])
continuation.yield([
CodeSuggestion(
id: "mock-suggestion-2",
text: "",
position: .zero,
range: .zero,
effectiveRange: .full,
replacingLines: [],
descriptions: [.init(kind: .action, content: "mock")],
middlewareComments: ["MockResultSuggestionServiceMiddleware"],
metadata: [.group: "Mock Action"]
),
])
do {
for try await suggestions in stream {
continuation.yield(suggestions)
}
continuation.finish()
} catch {
continuation.finish()
}
}
continuation.onTermination = { _ in
task.cancel()
}
}
#else
return await next(request)
#endif
}
}
public extension AsyncThrowingStream<[CodeSuggestion], Error> {
func handled(
handleCodeSuggestions: @escaping ([CodeSuggestion]) async -> [CodeSuggestion] = { $0 },
handleError: @escaping (Error) -> Error = { $0 },
onFinish: @escaping () -> Void = {}
) async -> AsyncThrowingStream<[CodeSuggestion], Error> {
.init { continuation in
let task = Task {
do {
for try await suggestions in self {
await continuation.yield(handleCodeSuggestions(suggestions))
}
continuation.finish()
onFinish()
} catch {
continuation.finish(throwing: handleError(error))
}
}
continuation.onTermination = { _ in
task.cancel()
}
}
}
static func suggestions(_ suggestions: [CodeSuggestion])
-> AsyncThrowingStream<[CodeSuggestion], Error>
{
.init { continuation in
continuation.yield(suggestions)
continuation.finish()
}
}
static func error(_ error: Error) -> AsyncThrowingStream<[CodeSuggestion], Error> {
.init { continuation in
continuation.finish(throwing: error)
}
}
func allSuggestions() async throws -> [CodeSuggestion] {
var all = [CodeSuggestion]()
for try await codeSuggestions in self {
all.append(contentsOf: codeSuggestions)
}
return all
}
}