This repository has been archived by the owner on Jul 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.go
87 lines (78 loc) · 1.61 KB
/
import.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
84
85
86
87
package humanize
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
)
// Import is a single import entity
type Import struct {
Name string
Path string
Docs Docs
}
type importWalker struct {
pkgName string
}
func (fv *importWalker) Visit(node ast.Node) ast.Visitor {
if node != nil {
switch t := node.(type) {
case *ast.File:
fv.pkgName = nameFromIdent(t.Name)
default:
}
}
return fv
}
// LoadPackage is the function to load import package
func (i Import) LoadPackage() *Package {
// XXX : Watch this.
pkg, _ := ParsePackage(i.Path)
return pkg
}
func peekPackageName(pkg string) (xx string) {
_, name := filepath.Split(pkg)
folder, err := translateToFullPath(pkg)
if err != nil {
return name
}
fv := &importWalker{}
err = filepath.Walk(
folder,
func(path string, f os.FileInfo, err error) error {
data, err := getGoFileContent(path, folder, f)
if err != nil || data == "" {
return err
}
fset := token.NewFileSet()
fle, err := parser.ParseFile(fset, "", data, parser.PackageClauseOnly)
if err != nil {
return nil // try another file?
}
ast.Walk(fv, fle)
// no need to continue
return filepath.SkipDir
},
)
if fv.pkgName != "" {
name = fv.pkgName
}
// can not parse it, use the folder name
return name
}
// NewImport extract a new import entry
func NewImport(i *ast.ImportSpec, c *ast.CommentGroup) *Import {
res := &Import{
Name: "",
Path: strings.Trim(i.Path.Value, `"`),
Docs: docsFromNodeDoc(c, i.Doc),
}
if i.Name != nil {
res.Name = i.Name.String()
} else {
res.Name = peekPackageName(res.Path)
}
return res
}