@@ -4,17 +4,85 @@ import Foundation
44import OpenAIService
55
66final class CopilotPromptToCodeAPI : PromptToCodeAPI {
7+ var task : Task < Void , Never > ?
8+
79 func stopResponding( ) {
8- fatalError ( )
10+ task ? . cancel ( )
911 }
1012
1113 func modifyCode(
1214 code: String ,
1315 language: CopilotLanguage ,
1416 indentSize: Int ,
1517 usesTabsForIndentation: Bool ,
16- requirement: String
18+ requirement: String ,
19+ projectRootURL: URL ,
20+ fileURL: URL ,
21+ allCode: String
1722 ) async throws -> AsyncThrowingStream < ( code: String , description: String ) , Error > {
18- fatalError ( )
23+ let copilotService = CopilotSuggestionService ( projectRootURL: projectRootURL)
24+ let relativePath = {
25+ let filePath = fileURL. path
26+ let rootPath = projectRootURL. path
27+ if let range = filePath. range ( of: rootPath) ,
28+ range. lowerBound == filePath. startIndex
29+ {
30+ let relativePath = filePath. replacingCharacters (
31+ in: filePath. startIndex..< range. upperBound,
32+ with: " "
33+ )
34+ return relativePath
35+ }
36+ return filePath
37+ } ( )
38+
39+ let comment = """
40+ // update the following code, \( requirement. split ( separator: " \n " ) . joined ( separator: " " ) ) .
41+ \( code. split ( separator: " \n " ) . map { " // \( $0) " } . joined ( separator: " \n " ) )
42+
43+
44+
45+ // Path: \( relativePath)
46+
47+ """
48+ let lineCount = comment. breakLines ( ) . count
49+
50+ return . init { continuation in
51+ self . task = Task {
52+ do {
53+ let result = try await copilotService. getCompletions (
54+ fileURL: fileURL,
55+ content: comment,
56+ cursorPosition: . init( line: lineCount - 4 , character: 0 ) ,
57+ tabSize: indentSize,
58+ indentSize: indentSize,
59+ usesTabsForIndentation: usesTabsForIndentation,
60+ ignoreSpaceOnlySuggestions: true
61+ )
62+ try Task . checkCancellation ( )
63+ guard let first = result. first else { throw CancellationError ( ) }
64+ continuation. yield ( ( first. text, " " ) )
65+ continuation. finish ( )
66+ } catch {
67+ continuation. finish ( throwing: error)
68+ }
69+ }
70+ }
71+ }
72+ }
73+
74+ extension String {
75+ /// Break a string into lines.
76+ func breakLines( ) -> [ String ] {
77+ let lines = split ( separator: " \n " , omittingEmptySubsequences: false )
78+ var all = [ String] ( )
79+ for (index, line) in lines. enumerated ( ) {
80+ if index == lines. endIndex - 1 {
81+ all. append ( String ( line) )
82+ } else {
83+ all. append ( String ( line) + " \n " )
84+ }
85+ }
86+ return all
1987 }
2088}
0 commit comments