forked from haya14busa/gopkgs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopkgs.go
97 lines (85 loc) · 2.27 KB
/
gopkgs.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
89
90
91
92
93
94
95
96
97
package gopkgs
import (
"fmt"
"go/parser"
"go/token"
"os"
"strings"
"github.com/3Xpl0it3r/gopkgs/x/tools/imports"
)
// Pkg represents exported go packages.
// It's based on x/tools/imports.Pkg.
type Pkg struct {
Dir string // absolute file path to Pkg directory ("/usr/lib/go/src/net/http")
ImportPath string // full Pkg import path ("net/http", "foo/bar/vendor/a/b")
ImportPathShort string // vendorless import path ("net/http", "a/b")
// It can be empty. It's filled only when Option.IncludeName is true.
Name string // package name ("http")
}
type Option struct {
// Fill package name in Pkg struct if it's true. Note that it needs to parse
// package directory to get package name and it takes some costs.
IncludeName bool
PrintLog bool
EnableGoRoot bool
Filter []string
ExecludeMod []string
}
func DefaultOption() *Option {
return &Option{
IncludeName: false,
PrintLog: false,
EnableGoRoot: false,
Filter: []string{},
ExecludeMod: []string{},
}
}
// Config [#TODO](should add some comments)
func (o *Option) Config() imports.ScanConfig {
return imports.ScanConfig{
ScanRoot: o.EnableGoRoot,
PrintLog: o.PrintLog,
Filter: o.Filter,
ExecludeMod: o.ExecludeMod,
}
}
// Packages returns all importable Go packages.
// Packages uses [golang.org/x/tools/cmd/goimports](https://godoc.org/golang.org/x/tools/cmd/goimports) implementation internally, so it's fast.
// e.g. it cares .goimportsignore
func Packages(opt *Option) []*Pkg {
gp := imports.GoPath(opt.Config())
pkgs := make([]*Pkg, len(gp))
i := 0
for _, p := range gp {
pkgs[i] = copyPkg(p)
if opt.IncludeName {
name, _ := packageName(p.Dir)
if name != "" {
pkgs[i].Name = name
}
}
i++
}
return pkgs
}
func copyPkg(p *imports.Pkg) *Pkg {
return &Pkg{
Dir: p.Dir,
ImportPath: p.ImportPath,
ImportPathShort: p.ImportPathShort,
}
}
func packageName(dir string) (string, error) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, dir, notGoTestFile, parser.PackageClauseOnly)
if err != nil {
return "", err
}
for name := range pkgs {
return name, nil
}
return "", fmt.Errorf("package not found in %s", dir)
}
func notGoTestFile(f os.FileInfo) bool {
return !strings.HasSuffix(f.Name(), "_test.go")
}