-
Notifications
You must be signed in to change notification settings - Fork 5
/
hints.go
65 lines (50 loc) · 1.37 KB
/
hints.go
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
package errorhandling
import (
"fmt"
"strings"
levenshtein "github.com/ka-weihe/fast-levenshtein"
"github.com/teamkeel/keel/formatting"
)
type Hint interface {
ToString() string
}
type CorrectionHint struct {
Hint
Query string
Results []string
}
func NewCorrectionHint(referenceCollection []string, query string) *CorrectionHint {
matches := make([]string, 0)
attributeNames := make([]string, 0)
for _, item := range referenceCollection {
attributeNames = append(attributeNames, item)
if levenshtein.Distance(query, item) < 2 || strings.HasPrefix(item, query) {
matches = append(matches, item)
}
}
if len(matches) < 1 {
matches = append(matches, attributeNames...)
}
return &CorrectionHint{Results: matches, Query: query}
}
func (hint *CorrectionHint) ToString() string {
message := ""
if len(hint.Results) == 1 {
message = fmt.Sprintf("Did you mean %s?", hint.Results[0])
} else if len(hint.Results) <= 2 {
message = fmt.Sprintf("Did you mean %s?", formatting.HumanizeList(hint.Results, formatting.DelimiterOr))
} else {
message = fmt.Sprintf("Did you mean one of %s?", formatting.HumanizeList(hint.Results, formatting.DelimiterOr))
}
return message
}
type NormalHint struct {
Hint
Message string
}
func NewHint(message string) *NormalHint {
return &NormalHint{Message: message}
}
func (hint *NormalHint) ToString() string {
return hint.Message
}