forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopilotPromptToCodeAPI.swift
More file actions
102 lines (91 loc) · 3.09 KB
/
CopilotPromptToCodeAPI.swift
File metadata and controls
102 lines (91 loc) · 3.09 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
import Foundation
import GitHubCopilotService
import OpenAIService
import SuggestionModel
final class CopilotPromptToCodeAPI: PromptToCodeAPI {
var task: Task<Void, Never>?
func stopResponding() {
task?.cancel()
}
func modifyCode(
code: String,
language: CodeLanguage,
indentSize: Int,
usesTabsForIndentation: Bool,
requirement: String,
projectRootURL: URL,
fileURL: URL,
allCode: String,
extraSystemPrompt: String?,
generateDescriptionRequirement: Bool?
) async throws -> AsyncThrowingStream<(code: String, description: String), Error> {
let copilotService = try GitHubCopilotSuggestionService(projectRootURL: projectRootURL)
let _ = {
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
}()
func convertToComment(_ s: String) -> String {
s.split(separator: "\n").map { "// \($0)" }.joined(separator: "\n")
}
let comment = """
// A file to refactor the following code
//
// Code:
// ```
\(convertToComment(code))
// ```
//
// Requirements:
\(convertToComment((extraSystemPrompt ?? "\n") + requirement))
//
// end of file
"""
let lineCount = comment.breakLines().count
return .init { continuation in
self.task = Task {
do {
let result = try await copilotService.getCompletions(
fileURL: fileURL,
content: comment,
cursorPosition: .init(line: lineCount - 3, character: 0),
tabSize: indentSize,
indentSize: indentSize,
usesTabsForIndentation: usesTabsForIndentation,
ignoreSpaceOnlySuggestions: true
)
try Task.checkCancellation()
guard let first = result.first else { throw CancellationError() }
continuation.yield((first.text, ""))
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
}
}
}
extension String {
/// Break a string into lines.
func breakLines() -> [String] {
let lines = split(separator: "\n", omittingEmptySubsequences: false)
var all = [String]()
for (index, line) in lines.enumerated() {
if index == lines.endIndex - 1 {
all.append(String(line))
} else {
all.append(String(line) + "\n")
}
}
return all
}
}