/
package.go
58 lines (45 loc) · 1.16 KB
/
package.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
package pkg
import (
"errors"
"go/ast"
"go/parser"
"go/token"
"path/filepath"
"golang.org/x/tools/go/packages"
)
var errPackageNotFound = errors.New("package not found")
// Load loads package by its import path
func Load(path string) (*packages.Package, error) {
cfg := &packages.Config{Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles}
pkgs, err := packages.Load(cfg, path)
if err != nil {
return nil, err
}
if len(pkgs) < 1 {
return nil, errPackageNotFound
}
if len(pkgs[0].Errors) > 0 {
return nil, pkgs[0].Errors[0]
}
return pkgs[0], nil
}
// AST returns package's abstract syntax tree
func AST(fs *token.FileSet, p *packages.Package) (*ast.Package, error) {
dir := Dir(p)
pkgs, err := parser.ParseDir(fs, dir, nil, parser.DeclarationErrors|parser.ParseComments)
if err != nil {
return nil, err
}
if ap, ok := pkgs[p.Name]; ok {
return ap, nil
}
return &ast.Package{Name: p.Name}, nil
}
// Dir returns absolute path of the package in a filesystem
func Dir(p *packages.Package) string {
files := append(p.GoFiles, p.OtherFiles...)
if len(files) < 1 {
return p.PkgPath
}
return filepath.Dir(files[0])
}