-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
finder.go
93 lines (81 loc) · 2.15 KB
/
finder.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
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
package generate
import (
"fmt"
"strings"
"github.com/ktr0731/go-fuzzyfinder"
)
type FuzzyFinder interface {
Find(pkgs []*FindingPackage) ([]int, error)
}
type fuzzyFinder struct{}
func NewFuzzyFinder() FuzzyFinder {
return &fuzzyFinder{}
}
func NewMockFuzzyFinder(idxs []int, err error) FuzzyFinder {
return &mockFuzzyFinder{
idxs: idxs,
err: err,
}
}
type mockFuzzyFinder struct {
idxs []int
err error
}
func (finder *mockFuzzyFinder) Find(pkgs []*FindingPackage) ([]int, error) {
return finder.idxs, finder.err
}
func (finder *fuzzyFinder) Find(pkgs []*FindingPackage) ([]int, error) {
return fuzzyfinder.FindMulti(pkgs, func(i int) string { //nolint:wrapcheck
return find(pkgs[i])
},
fuzzyfinder.WithPreviewWindow(func(i, w, h int) string {
return getPreview(pkgs[i], i, w)
}))
}
func find(pkg *FindingPackage) string {
files := pkg.PackageInfo.GetFiles()
fileNames := make([]string, len(files))
for i, file := range files {
fileNames[i] = file.Name
}
fileNamesStr := strings.Join(fileNames, ", ")
pkgName := pkg.PackageInfo.GetName()
aliases := make([]string, len(pkg.PackageInfo.Aliases))
for i, alias := range pkg.PackageInfo.Aliases {
aliases[i] = alias.Name
}
item := pkgName
if len(aliases) != 0 {
item += " (" + strings.Join(aliases, ", ") + ")"
}
item += " (" + pkg.RegistryName + ")"
if strings.HasSuffix(pkgName, "/"+fileNamesStr) || pkgName == fileNamesStr {
return item
}
return item + " (" + fileNamesStr + ")"
}
func getPreview(pkg *FindingPackage, i, w int) string {
if i < 0 {
return ""
}
return fmt.Sprintf("%s\n\n%s\n%s",
pkg.PackageInfo.GetName(),
pkg.PackageInfo.GetLink(),
formatDescription(pkg.PackageInfo.GetDescription(), w/2-8)) //nolint:gomnd
}
func formatDescription(desc string, w int) string {
descRune := []rune(desc)
lenDescRune := len(descRune)
lineWidth := w - len([]rune("\n"))
numOfLines := (lenDescRune / lineWidth) + 1
descArr := make([]string, numOfLines)
for i := 0; i < numOfLines; i++ {
start := i * lineWidth
end := start + lineWidth
if i == numOfLines-1 {
end = lenDescRune
}
descArr[i] = string(descRune[start:end])
}
return strings.Join(descArr, "\n")
}