/
loader.go
58 lines (48 loc) · 1.14 KB
/
loader.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 loader
import (
"errors"
"go/build"
"go/types"
"log"
"os"
"path/filepath"
"golang.org/x/tools/go/loader"
)
var ErrTagsNotApplicable = errors.New("build tags only apply to directories, not when files are specified")
func LoadPackage(buildTags []string, args []string) (pkg *types.Package, dir string, err error) {
if len(args) == 0 {
args = []string{"."}
}
conf := loader.Config{
Build: buildContext(buildTags),
TypeCheckFuncBodies: func(string) bool { return false },
}
if len(args) == 1 && isDirectory(args[0]) {
dir = args[0]
conf.Import(dir)
} else {
if len(buildTags) != 0 {
return nil, "", ErrTagsNotApplicable
}
dir = filepath.Dir(args[0])
conf.CreateFromFilenames("", args...)
}
lprog, err := conf.Load()
if err != nil {
return nil, "", err
}
return lprog.InitialPackages()[0].Pkg, dir, nil
}
func buildContext(tags []string) *build.Context {
ctx := build.Default
ctx.BuildTags = tags
return &ctx
}
// isDirectory reports whether the named file is a directory.
func isDirectory(name string) bool {
info, err := os.Stat(name)
if err != nil {
log.Fatal(err)
}
return info.IsDir()
}