forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkspace+SuggestionService.swift
More file actions
266 lines (229 loc) · 9.19 KB
/
Copy pathWorkspace+SuggestionService.swift
File metadata and controls
266 lines (229 loc) · 9.19 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
import enum CopilotForXcodeKit.SuggestionServiceError
import struct CopilotForXcodeKit.WorkspaceInfo
import Foundation
import SuggestionBasic
import SuggestionProvider
import Workspace
import XPCShared
public protocol SuggestionServiceType {
func getSuggestions(
_ request: SuggestionRequest,
workspaceInfo: CopilotForXcodeKit.WorkspaceInfo
) async -> AsyncThrowingStream<[CodeSuggestion], Error>
func notifyAccepted(
_ suggestion: CodeSuggestion,
workspaceInfo: CopilotForXcodeKit.WorkspaceInfo
) async
func notifyRejected(
_ suggestions: [CodeSuggestion],
workspaceInfo: CopilotForXcodeKit.WorkspaceInfo
) async
func notifyDismissed(
_ suggestions: [CodeSuggestion],
workspaceInfo: CopilotForXcodeKit.WorkspaceInfo
) async
func cancelRequest(workspaceInfo: CopilotForXcodeKit.WorkspaceInfo) async
var configuration: SuggestionServiceConfiguration { get async }
}
public extension Workspace {
var suggestionPlugin: SuggestionServiceWorkspacePlugin? {
plugin(for: SuggestionServiceWorkspacePlugin.self)
}
var suggestionService: SuggestionServiceType? {
suggestionPlugin?.suggestionService
}
var isSuggestionFeatureEnabled: Bool {
suggestionPlugin?.isSuggestionFeatureEnabled ?? false
}
struct SuggestionFeatureDisabledError: Error, LocalizedError {
public var errorDescription: String? {
"Suggestion feature is disabled for this project."
}
}
}
public enum GenerateSuggestionCheck: CaseIterable {
case skipIfGitIgnored
case skipIfHasValidSuggestions
case skipIfSnapshotIsSame
}
public struct GenerateSuggestionSkipError: Error, LocalizedError {
var reason: GenerateSuggestionCheck
public var errorDescription: String? {
"Generate suggestion skipped. Check: \(reason)"
}
}
public extension Workspace {
@WorkspaceActor
@discardableResult
func generateSuggestions(
forFileAt fileURL: URL,
editor: EditorContent,
checks: Set<GenerateSuggestionCheck> = Set(GenerateSuggestionCheck.allCases)
) async throws -> [CodeSuggestion] {
refreshUpdateTime()
let filespace = try createFilespaceIfNeeded(fileURL: fileURL)
filespace.suggestionManager?.updateCursorPosition(editor.cursorPosition)
if checks.contains(.skipIfGitIgnored),
await filespace.isGitIgnored
{
throw GenerateSuggestionSkipError(reason: .skipIfGitIgnored)
}
if !editor.uti.isEmpty {
filespace.codeMetadata.uti = editor.uti
filespace.codeMetadata.tabSize = editor.tabSize
filespace.codeMetadata.indentSize = editor.indentSize
filespace.codeMetadata.usesTabsForIndentation = editor.usesTabsForIndentation
}
filespace.codeMetadata.guessLineEnding(from: editor.lines.first)
let activeCodeSuggestion = await filespace.activeCodeSuggestion
if checks.contains(.skipIfHasValidSuggestions), activeCodeSuggestion != nil {
// Check if the current suggestion is still valid.
if await filespace.validateSuggestions(
lines: editor.lines,
cursorPosition: editor.cursorPosition
) {
throw GenerateSuggestionSkipError(reason: .skipIfHasValidSuggestions)
}
}
let snapshot = FilespaceSuggestionSnapshot(
lines: editor.lines,
cursorPosition: editor.cursorPosition
)
if checks.contains(.skipIfSnapshotIsSame),
filespace.suggestionManager?.defaultSuggestionProvider
.suggestionSourceSnapshot == snapshot
{
throw GenerateSuggestionSkipError(reason: .skipIfSnapshotIsSame)
}
filespace.suggestionManager?.defaultSuggestionProvider.suggestionSourceSnapshot = snapshot
guard let suggestionService else { throw SuggestionFeatureDisabledError() }
let content = editor.lines.joined(separator: "")
let stream = await suggestionService.getSuggestions(
.init(
fileURL: fileURL,
relativePath: fileURL.path.replacingOccurrences(of: projectRootURL.path, with: ""),
content: content,
originalContent: content,
lines: editor.lines,
cursorPosition: editor.cursorPosition,
cursorOffset: editor.cursorOffset,
tabSize: editor.tabSize,
indentSize: editor.indentSize,
usesTabsForIndentation: editor.usesTabsForIndentation,
relevantCodeSnippets: []
),
workspaceInfo: .init(workspaceURL: workspaceURL, projectURL: projectRootURL)
)
var allCompletions: [CodeSuggestion] = []
for try await completions in stream {
try Task.checkCancellation()
// make sure the suggestions are still relevant
if snapshot != filespace.suggestionManager?.defaultSuggestionProvider
.suggestionSourceSnapshot { break }
allCompletions.append(contentsOf: completions)
filespace.suggestionManager?.receiveSuggestions(completions)
}
return allCompletions
}
@WorkspaceActor
func selectNextSuggestion(forFileAt fileURL: URL, groupIndex: Int? = nil) {
refreshUpdateTime()
guard let filespace = filespaces[fileURL] else { return }
filespace.selectNextSuggestion(inGroup: groupIndex)
}
@WorkspaceActor
func selectPreviousSuggestion(forFileAt fileURL: URL, groupIndex: Int? = nil) {
refreshUpdateTime()
guard let filespace = filespaces[fileURL] else { return }
filespace.selectPreviousSuggestion(inGroup: groupIndex)
}
@WorkspaceActor
func selectNextSuggestionGroup(forFileAt fileURL: URL) {
refreshUpdateTime()
guard let filespace = filespaces[fileURL] else { return }
filespace.selectNextSuggestionGroup()
}
@WorkspaceActor
func selectPreviousSuggestionGroup(forFileAt fileURL: URL) {
refreshUpdateTime()
guard let filespace = filespaces[fileURL] else { return }
filespace.selectPreviousSuggestionGroup()
}
@WorkspaceActor
func rejectSuggestion(
forFileAt fileURL: URL,
editor: EditorContent?,
groupIndex: Int? = nil
) async {
refreshUpdateTime()
guard let filespace = filespaces[fileURL] else { return }
if let editor, !editor.uti.isEmpty {
filespace.suggestionManager?.updateCursorPosition(editor.cursorPosition)
filespaces[fileURL]?.codeMetadata.uti = editor.uti
filespaces[fileURL]?.codeMetadata.tabSize = editor.tabSize
filespaces[fileURL]?.codeMetadata.indentSize = editor.indentSize
filespaces[fileURL]?.codeMetadata.usesTabsForIndentation = editor.usesTabsForIndentation
}
let rejectedSuggestions = await filespace.rejectSuggestion(inGroup: groupIndex)
Task {
await suggestionService?.notifyRejected(
rejectedSuggestions,
workspaceInfo: .init(
workspaceURL: workspaceURL,
projectURL: projectRootURL
)
)
}
}
@WorkspaceActor
func acceptSuggestion(
forFileAt fileURL: URL,
editor: EditorContent?,
groupIndex: Int? = nil
) async -> CodeSuggestion? {
refreshUpdateTime()
guard let filespace = filespaces[fileURL] else { return nil }
if let editor, !editor.uti.isEmpty {
filespace.suggestionManager?.updateCursorPosition(editor.cursorPosition)
filespaces[fileURL]?.codeMetadata.uti = editor.uti
filespaces[fileURL]?.codeMetadata.tabSize = editor.tabSize
filespaces[fileURL]?.codeMetadata.indentSize = editor.indentSize
filespaces[fileURL]?.codeMetadata.usesTabsForIndentation = editor.usesTabsForIndentation
}
guard let suggestion = await filespace.acceptSuggestion(inGroup: groupIndex)
else { return nil }
Task {
await suggestionService?.notifyAccepted(
suggestion,
workspaceInfo: .init(
workspaceURL: workspaceURL,
projectURL: projectRootURL
)
)
}
return suggestion
}
@WorkspaceActor
func dismissSuggestions(forFileAt fileURL: URL) async {
refreshUpdateTime()
guard let filespace = filespaces[fileURL] else { return }
let displayedSuggestions = await filespace.suggestionManager?.displaySuggestions.flatMap {
switch $0 {
case let .action(action):
return [action.suggestion]
case let .group(group):
return group.suggestions
}
} ?? []
filespace.suggestionManager?.invalidateDisplaySuggestions()
Task {
await suggestionService?.notifyDismissed(
displayedSuggestions,
workspaceInfo: .init(
workspaceURL: workspaceURL,
projectURL: projectRootURL
)
)
}
}
}