forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostProcessingSuggestionServiceMiddleware.swift
More file actions
71 lines (62 loc) · 2.54 KB
/
PostProcessingSuggestionServiceMiddleware.swift
File metadata and controls
71 lines (62 loc) · 2.54 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
import Foundation
import SuggestionBasic
public struct PostProcessingSuggestionServiceMiddleware: SuggestionServiceMiddleware {
public init() {}
public func getSuggestion(
_ request: SuggestionRequest,
configuration: SuggestionServiceConfiguration,
next: Next
) async throws -> [CodeSuggestion] {
let suggestions = try await next(request)
return suggestions.compactMap {
var suggestion = $0
if suggestion.text.allSatisfy({ $0.isWhitespace || $0.isNewline }) { return nil }
Self.removeTrailingWhitespacesAndNewlines(&suggestion)
if !Self.checkIfSuggestionHasNoEffect(suggestion, request: request) { return nil }
return suggestion
}
}
static func removeTrailingWhitespacesAndNewlines(_ suggestion: inout CodeSuggestion) {
var text = suggestion.text[...]
while let last = text.last, last.isNewline || last.isWhitespace {
text = text.dropLast(1)
}
suggestion.text = String(text)
}
static func checkIfSuggestionHasNoEffect(
_ suggestion: CodeSuggestion,
request: SuggestionRequest
) -> Bool {
// We only check suggestions that are on a single line.
if suggestion.range.isOneLine {
let line = suggestion.range.start.line
if line >= 0, line < request.lines.count {
let replacingText = request.lines[line]
let start = suggestion.range.start.character
let end = suggestion.range.end.character
if let endIndex = replacingText.utf16.index(
replacingText.startIndex,
offsetBy: end,
limitedBy: replacingText.endIndex
),
let startIndex = replacingText.utf16.index(
replacingText.startIndex,
offsetBy: start,
limitedBy: endIndex
),
startIndex < endIndex
{
let replacingRange = startIndex..<endIndex
// Build up the replaced text.
let replacedText = replacingText.replacingCharacters(
in: replacingRange,
with: suggestion.text
)
// If it's identical to the original text, ignore the suggestion.
if replacedText == replacingText { return false }
}
}
}
return true
}
}