forked from LS6-Events/astra
/
loadPackage.go
68 lines (57 loc) · 1.72 KB
/
loadPackage.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
package astTraversal
import (
"fmt"
"golang.org/x/tools/go/packages"
)
var cachedPackages = make(map[string]*packages.Package)
// LoadPackage loads a package from a path.
// Because of the way the packages.Load function works, we cache the packages to avoid loading the same package multiple times.
func LoadPackage(pkgPath string, workDir string) (*packages.Package, error) {
if pkg, ok := cachedPackages[pkgPath]; ok {
return pkg, nil
}
pkg, err := LoadPackageNoCache(pkgPath, workDir)
if err != nil {
return nil, err
}
cachedPackages[pkgPath] = pkg
return pkg, nil
}
// LoadPackageNoCache loads a package from a path.
// This function will not use the cache when loading the package.
func LoadPackageNoCache(pkgPath string, workDir string) (*packages.Package, error) {
pkgs, err := packages.Load(&packages.Config{
Mode: packages.NeedName |
packages.NeedFiles |
packages.NeedImports |
packages.NeedDeps |
packages.NeedExportFile |
packages.NeedTypes |
packages.NeedSyntax |
packages.NeedTypesInfo |
packages.NeedTypesSizes |
packages.NeedModule,
Dir: workDir,
}, pkgPath)
if err != nil {
return nil, err
}
for _, pkg := range pkgs {
for _, pkgErr := range pkg.Errors {
switch pkgErr.Kind {
case packages.ListError:
return nil, fmt.Errorf("package %s has list errors", pkgPath)
case packages.TypeError:
return nil, fmt.Errorf("package %s has type errors", pkgPath)
case packages.ParseError:
return nil, fmt.Errorf("package %s has parse errors", pkgPath)
case packages.UnknownError:
return nil, fmt.Errorf("package %s has unknown errors", pkgPath)
}
}
}
if len(pkgs) == 0 {
return nil, fmt.Errorf("package %s not found", pkgPath)
}
return pkgs[0], nil
}