-
Notifications
You must be signed in to change notification settings - Fork 4
/
import.go
88 lines (74 loc) · 1.75 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
88
package generate
import (
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
"github.com/please-build/puku/kinds"
)
// GoFile represents a single Go file in a package
type GoFile struct {
// Name is the name from the package clause of this file
Name, FileName string
// Imports are the imports of this file
Imports []string
}
// ImportDir does _some_ of what the go/build ImportDir does but is more permissive.
func ImportDir(dir string) (map[string]*GoFile, error) {
files, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
ret := make(map[string]*GoFile, len(files))
for _, info := range files {
if !info.Type().IsRegular() {
continue
}
if filepath.Ext(info.Name()) != ".go" {
continue
}
f, err := importFile(dir, info.Name())
if err != nil {
return nil, err
}
ret[info.Name()] = f
}
return ret, nil
}
func importFile(dir, src string) (*GoFile, error) {
f, err := parser.ParseFile(token.NewFileSet(), filepath.Join(dir, src), nil, parser.ImportsOnly|parser.ParseComments)
if err != nil {
return nil, err
}
imports := make([]string, 0, len(f.Imports))
for _, i := range f.Imports {
path := i.Path.Value
path = strings.Trim(path, `"`)
imports = append(imports, path)
}
return &GoFile{
Name: f.Name.Name,
FileName: src,
Imports: imports,
}, nil
}
// IsExternal returns whether the test is external
func (f *GoFile) IsExternal(pkgName string) bool {
return f.Name == filepath.Base(pkgName)+"_test" && f.IsTest()
}
func (f *GoFile) IsTest() bool {
return strings.HasSuffix(f.FileName, "_test.go")
}
func (f *GoFile) IsCmd() bool {
return f.Name == "main"
}
func (f *GoFile) kindType() kinds.Type {
if f.IsTest() {
return kinds.Test
}
if f.IsCmd() {
return kinds.Bin
}
return kinds.Lib
}