/
m_import_paths.go
74 lines (65 loc) · 1.56 KB
/
m_import_paths.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
package margo_pkg
import (
"go/ast"
"go/build"
"go/parser"
"gosublime/margo"
"gosublime/margo/meth/importpaths"
"path/filepath"
)
type mImportPaths struct {
Fn string
Src string
Env map[string]string
InstallSuffix string
}
type mImportPathsDecl struct {
Name string `json:"name"`
Path string `json:"path"`
}
func (m *mImportPaths) Call() (interface{}, string) {
imports := []mImportPathsDecl{}
_, af, err := parseAstFile(m.Fn, m.Src, parser.ImportsOnly)
if err != nil {
return M{}, err.Error()
}
if m.Fn != "" || m.Src != "" {
for _, decl := range af.Decls {
if gdecl, ok := decl.(*ast.GenDecl); ok && len(gdecl.Specs) > 0 {
for _, spec := range gdecl.Specs {
if ispec, ok := spec.(*ast.ImportSpec); ok {
sd := mImportPathsDecl{
Path: unquote(ispec.Path.Value),
}
if ispec.Name != nil {
sd.Name = ispec.Name.String()
}
imports = append(imports, sd)
}
}
}
}
}
bctx := build.Default
bctx.GOROOT = orString(m.Env["GOROOT"], bctx.GOROOT)
bctx.GOPATH = orString(m.Env["GOPATH"], bctx.GOPATH)
bctx.InstallSuffix = m.InstallSuffix
srcDir, _ := filepath.Split(m.Fn)
res := M{
"imports": imports,
"paths": margo.Options().ImportPaths(srcDir, &bctx),
}
return res, ""
}
func init() {
margo.Configure(func(o *margo.Opts) {
if o.ImportPaths == nil {
o.ImportPaths = importpaths.MakeImportPathsFunc(importpaths.PathFilter)
}
})
registry.Register("import_paths", func(_ *Broker) Caller {
return &mImportPaths{
Env: map[string]string{},
}
})
}