-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathanalyzer.go
83 lines (68 loc) · 1.73 KB
/
analyzer.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
package analyzer
import (
"encoding/json"
"go.uber.org/zap"
"os"
)
var goRoot string
// PackageIndex is Go packages index
type PackageIndex struct {
// Packages is list of packages
Packages []*Package
nameMap map[string]*Package
charMap map[string][]*CompletionItem
}
// PackageByName returns package by name
func (pi PackageIndex) PackageByName(name string) (*Package, bool) {
pkg, ok := pi.nameMap[name]
return pkg, ok
}
// Match returns code completion suggestions by character
func (pi PackageIndex) Match(char string) []*CompletionItem {
return pi.charMap[char]
}
// Len returns index length
func (pi PackageIndex) Len() int {
return len(pi.Packages)
}
// BuildPackageIndex builds package index from set of packages
func BuildPackageIndex(pkgs []*Package) PackageIndex {
idx := PackageIndex{
Packages: pkgs,
nameMap: make(map[string]*Package, len(pkgs)),
charMap: make(map[string][]*CompletionItem),
}
for _, pkg := range pkgs {
addPackageToIndex(pkg, &idx)
}
return idx
}
func addPackageToIndex(pkg *Package, idx *PackageIndex) {
firstChar := pkg.Name[:1]
idx.nameMap[pkg.Name] = pkg
idx.charMap[firstChar] = append(idx.charMap[firstChar], pkg.GetCompletionItem())
if len(pkg.Children) > 0 {
for _, child := range pkg.Children {
addPackageToIndex(child, idx)
}
}
}
// SetRoot sets GOROOT
func SetRoot(root string) {
goRoot = root
}
// SetLogger sets logger
func SetLogger(l *zap.Logger) {
log = l.Named("analyzer").Sugar()
}
// ReadPackagesFile reads and loads packages list from packages.json file
func ReadPackagesFile(f string) ([]*Package, error) {
r, err := os.Open(f)
if err != nil {
return nil, err
}
defer r.Close()
var pkgs []*Package
err = json.NewDecoder(r).Decode(&pkgs)
return pkgs, err
}