forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeiumService.swift
More file actions
382 lines (343 loc) · 13.9 KB
/
CodeiumService.swift
File metadata and controls
382 lines (343 loc) · 13.9 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import Foundation
import LanguageClient
import LanguageServerProtocol
import Logger
import SuggestionModel
import XcodeInspector
public protocol CodeiumSuggestionServiceType {
func getCompletions(
fileURL: URL,
content: String,
cursorPosition: CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool,
ignoreSpaceOnlySuggestions: Bool
) async throws -> [CodeSuggestion]
func notifyAccepted(_ suggestion: CodeSuggestion) async
func notifyOpenTextDocument(fileURL: URL, content: String) async throws
func notifyChangeTextDocument(fileURL: URL, content: String) async throws
func notifyCloseTextDocument(fileURL: URL) async throws
func cancelRequest() async
func terminate()
}
enum CodeiumError: Error, LocalizedError {
case languageServerNotInstalled
case languageServerOutdated
case languageServiceIsInstalling
var errorDescription: String? {
switch self {
case .languageServerNotInstalled:
return "Language server is not installed. Please install it in the host app."
case .languageServerOutdated:
return "Language server is outdated. Please update it in the host app or update the extension."
case .languageServiceIsInstalling:
return "Language service is installing, please try again later."
}
}
}
public class CodeiumSuggestionService {
static let sessionId = UUID().uuidString
let projectRootURL: URL
var server: CodeiumLSP?
var heartbeatTask: Task<Void, Error>?
var requestCounter: UInt64 = 0
var cancellationCounter: UInt64 = 0
let openedDocumentPool = OpenedDocumentPool()
let onServiceLaunched: () -> Void
let languageServerURL: URL
let supportURL: URL
let authService = CodeiumAuthService()
var fallbackXcodeVersion = "14.0.0"
var languageServerVersion = CodeiumInstallationManager.latestSupportedVersion
private var ongoingTasks = Set<Task<[CodeSuggestion], Error>>()
init(designatedServer: CodeiumLSP) {
projectRootURL = URL(fileURLWithPath: "/")
server = designatedServer
onServiceLaunched = {}
languageServerURL = URL(fileURLWithPath: "/")
supportURL = URL(fileURLWithPath: "/")
}
public init(projectRootURL: URL, onServiceLaunched: @escaping () -> Void) throws {
self.projectRootURL = projectRootURL
self.onServiceLaunched = onServiceLaunched
let urls = try CodeiumSuggestionService.createFoldersIfNeeded()
languageServerURL = urls.executableURL.appendingPathComponent("language_server")
supportURL = urls.supportURL
Task {
try await setupServerIfNeeded()
}
}
@discardableResult
func setupServerIfNeeded() async throws -> CodeiumLSP {
if let server { return server }
let binaryManager = CodeiumInstallationManager()
let installationStatus = binaryManager.checkInstallation()
switch installationStatus {
case let .installed(version), let .unsupported(version, _):
languageServerVersion = version
case .notInstalled:
throw CodeiumError.languageServerNotInstalled
case let .outdated(version, _):
languageServerVersion = version
throw CodeiumError.languageServerOutdated
}
let metadata = try getMetadata()
let tempFolderURL = FileManager.default.temporaryDirectory
let managerDirectoryURL = tempFolderURL
.appendingPathComponent("com.intii.CopilotForXcode")
.appendingPathComponent(UUID().uuidString)
if !FileManager.default.fileExists(atPath: managerDirectoryURL.path) {
try FileManager.default.createDirectory(
at: managerDirectoryURL,
withIntermediateDirectories: true
)
}
let server = CodeiumLanguageServer(
languageServerExecutableURL: languageServerURL,
managerDirectoryURL: managerDirectoryURL,
supportURL: supportURL
)
server.terminationHandler = { [weak self] in
self?.server = nil
self?.heartbeatTask?.cancel()
self?.requestCounter = 0
self?.cancellationCounter = 0
Logger.codeium.info("Language server is terminated, will be restarted when needed.")
}
server.launchHandler = { [weak self] in
guard let self else { return }
self.onServiceLaunched()
self.heartbeatTask = Task { [weak self, metadata] in
while true {
try Task.checkCancellation()
_ = try? await self?.server?.sendRequest(
CodeiumRequest.Heartbeat(requestBody: .init(metadata: metadata))
)
try await Task.sleep(nanoseconds: 5_000_000_000)
}
}
}
self.server = server
server.start()
return server
}
public static func createFoldersIfNeeded() throws -> (
applicationSupportURL: URL,
gitHubCopilotURL: URL,
executableURL: URL,
supportURL: URL
) {
let supportURL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first!.appendingPathComponent(
Bundle.main
.object(forInfoDictionaryKey: "APPLICATION_SUPPORT_FOLDER") as! String
)
if !FileManager.default.fileExists(atPath: supportURL.path) {
try? FileManager.default
.createDirectory(at: supportURL, withIntermediateDirectories: false)
}
let gitHubCopilotFolderURL = supportURL.appendingPathComponent("Codeium")
if !FileManager.default.fileExists(atPath: gitHubCopilotFolderURL.path) {
try? FileManager.default
.createDirectory(at: gitHubCopilotFolderURL, withIntermediateDirectories: false)
}
let supportFolderURL = gitHubCopilotFolderURL.appendingPathComponent("support")
if !FileManager.default.fileExists(atPath: supportFolderURL.path) {
try? FileManager.default
.createDirectory(at: supportFolderURL, withIntermediateDirectories: false)
}
let executableFolderURL = gitHubCopilotFolderURL.appendingPathComponent("executable")
if !FileManager.default.fileExists(atPath: executableFolderURL.path) {
try? FileManager.default
.createDirectory(at: executableFolderURL, withIntermediateDirectories: false)
}
return (supportURL, gitHubCopilotFolderURL, executableFolderURL, supportFolderURL)
}
}
extension CodeiumSuggestionService {
func getMetadata() throws -> Metadata {
guard let key = authService.key else {
struct E: Error, LocalizedError {
var errorDescription: String? { "Codeium not signed in." }
}
throw E()
}
var ideVersion = XcodeInspector.shared.latestActiveXcode?.version ?? fallbackXcodeVersion
let versionNumberSegmentCount = ideVersion.split(separator: ".").count
if versionNumberSegmentCount == 2 {
ideVersion += ".0"
} else if versionNumberSegmentCount == 1 {
ideVersion += ".0.0"
}
return Metadata(
ide_name: "xcode",
ide_version: ideVersion,
extension_version: languageServerVersion,
api_key: key,
session_id: CodeiumSuggestionService.sessionId,
request_id: requestCounter
)
}
func getRelativePath(of fileURL: URL) -> String {
let filePath = fileURL.path
let rootPath = projectRootURL.path
if let range = filePath.range(of: rootPath),
range.lowerBound == filePath.startIndex
{
let relativePath = filePath.replacingCharacters(
in: filePath.startIndex..<range.upperBound,
with: ""
)
return relativePath
}
return filePath
}
}
extension CodeiumSuggestionService: CodeiumSuggestionServiceType {
public func getCompletions(
fileURL: URL,
content: String,
cursorPosition: CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool,
ignoreSpaceOnlySuggestions: Bool
) async throws -> [CodeSuggestion] {
ongoingTasks.forEach { $0.cancel() }
ongoingTasks.removeAll()
await cancelRequest()
requestCounter += 1
let languageId = languageIdentifierFromFileURL(fileURL)
let relativePath = getRelativePath(of: fileURL)
let task = Task {
let request = await CodeiumRequest.GetCompletion(requestBody: .init(
metadata: try getMetadata(),
document: .init(
absolute_path: fileURL.path,
relative_path: relativePath,
text: content,
editor_language: languageId.rawValue,
language: .init(codeLanguage: languageId),
cursor_position: .init(
row: cursorPosition.line,
col: cursorPosition.character
)
),
editor_options: .init(tab_size: indentSize, insert_spaces: !usesTabsForIndentation),
other_documents: openedDocumentPool.getOtherDocuments(exceptURL: fileURL)
.map { openedDocument in
let languageId = languageIdentifierFromFileURL(openedDocument.url)
return .init(
absolute_path: openedDocument.url.path,
relative_path: openedDocument.relativePath,
text: openedDocument.content,
editor_language: languageId.rawValue,
language: .init(codeLanguage: languageId)
)
}
))
try Task.checkCancellation()
let result = try await (try await setupServerIfNeeded()).sendRequest(request)
try Task.checkCancellation()
return result.completionItems?.filter { item in
if ignoreSpaceOnlySuggestions {
return !item.completion.text.allSatisfy { $0.isWhitespace || $0.isNewline }
}
return true
}.map { item in
CodeSuggestion(
text: item.completion.text,
position: cursorPosition,
uuid: item.completion.completionId,
range: CursorRange(
start: .init(
line: item.range.startPosition?.row.flatMap(Int.init) ?? 0,
character: item.range.startPosition?.col.flatMap(Int.init) ?? 0
),
end: .init(
line: item.range.endPosition?.row.flatMap(Int.init) ?? 0,
character: item.range.endPosition?.col.flatMap(Int.init) ?? 0
)
),
displayText: item.completion.text
)
} ?? []
}
ongoingTasks.insert(task)
return try await task.value
}
public func cancelRequest() async {
_ = try? await server?.sendRequest(
CodeiumRequest.CancelRequest(requestBody: .init(
request_id: requestCounter,
session_id: CodeiumSuggestionService.sessionId
))
)
}
public func notifyAccepted(_ suggestion: CodeSuggestion) async {
_ = try? await (try setupServerIfNeeded())
.sendRequest(CodeiumRequest.AcceptCompletion(requestBody: .init(
metadata: getMetadata(),
completion_id: suggestion.uuid
)))
}
public func notifyOpenTextDocument(fileURL: URL, content: String) async throws {
let relativePath = getRelativePath(of: fileURL)
await openedDocumentPool.openDocument(
url: fileURL,
relativePath: relativePath,
content: content
)
}
public func notifyChangeTextDocument(fileURL: URL, content: String) async throws {
let relativePath = getRelativePath(of: fileURL)
await openedDocumentPool.updateDocument(
url: fileURL,
relativePath: relativePath,
content: content
)
}
public func notifyCloseTextDocument(fileURL: URL) async throws {
await openedDocumentPool.closeDocument(url: fileURL)
}
public func terminate() {
server?.terminate()
server = nil
}
}
func getXcodeVersion() async throws -> String {
let task = Process()
task.launchPath = "/usr/bin/xcodebuild"
task.arguments = ["-version"]
let outpipe = Pipe()
task.standardOutput = outpipe
task.standardError = Pipe()
return try await withUnsafeThrowingContinuation { continuation in
do {
task.terminationHandler = { _ in
do {
if let data = try outpipe.fileHandleForReading.readToEnd(),
let content = String(data: data, encoding: .utf8)
{
let firstLine = content.split(separator: "\n").first ?? ""
var version = firstLine.replacingOccurrences(of: "Xcode ", with: "")
if version.isEmpty {
version = "14.0"
}
continuation.resume(returning: version)
return
}
continuation.resume(returning: "")
} catch {
continuation.resume(throwing: error)
}
}
try task.run()
} catch {
continuation.resume(throwing: error)
}
}
}