forked from Azure/azure-sdk-for-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
package.go
165 lines (153 loc) · 4.4 KB
/
package.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright 2018 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package exports
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
)
// Package represents a Go package.
type Package struct {
f *token.FileSet
p *ast.Package
files map[string][]byte
}
// LoadPackage loads the package in the specified directory.
// It's required there is only one package in the directory.
func LoadPackage(dir string) (pkg Package, err error) {
pkg.files = map[string][]byte{}
pkg.f = token.NewFileSet()
packages, err := parser.ParseDir(pkg.f, dir, nil, 0)
if err != nil {
return
}
if len(packages) < 1 {
err = fmt.Errorf("didn't find any packages in '%s'", dir)
return
}
if len(packages) > 1 {
err = fmt.Errorf("found more than one package in '%s'", dir)
return
}
for pn := range packages {
p := packages[pn]
// trim any non-exported nodes
if exp := ast.PackageExports(p); !exp {
err = fmt.Errorf("package '%s' doesn't contain any exports", pn)
return
}
pkg.p = p
return
}
// shouldn't ever get here...
panic("failed to return package")
}
// GetExports returns the exported content of the package.
func (pkg Package) GetExports() (c Content) {
c = NewContent()
ast.Inspect(pkg.p, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.TypeSpec:
if t, ok := x.Type.(*ast.StructType); ok {
c.addStruct(pkg, x.Name.Name, t)
} else if t, ok := x.Type.(*ast.InterfaceType); ok {
c.addInterface(pkg, x.Name.Name, t)
}
case *ast.FuncDecl:
c.addFunc(pkg, x)
// return false as we don't care about the function body.
// this is super important as it filters out the majority of
// the package's AST making it WAY easier to find the bits
// of interest (not doing this will break a lot of code).
return false
case *ast.GenDecl:
if x.Tok == token.CONST {
c.addConst(pkg, x)
}
}
return true
})
return
}
// Name returns the package name.
func (pkg Package) Name() string {
return pkg.p.Name
}
// Get loads the package in the specified directory and returns the exported
// content. It's a convenience wrapper around LoadPackage() and GetExports().
func Get(pkgDir string) (Content, error) {
pkg, err := LoadPackage(pkgDir)
if err != nil {
return Content{}, err
}
return pkg.GetExports(), nil
}
// returns the text between [start, end]
func (pkg Package) getText(start token.Pos, end token.Pos) string {
// convert to absolute position within the containing file
p := pkg.f.Position(start)
// check if the file has been loaded, if not then load it
if _, ok := pkg.files[p.Filename]; !ok {
b, err := ioutil.ReadFile(p.Filename)
if err != nil {
panic(err)
}
pkg.files[p.Filename] = b
}
return string(pkg.files[p.Filename][p.Offset : p.Offset+int(end-start)])
}
// iterates over the specified field list, for each field the specified
// callback is invoked with the name of the field and the type name. the field
// name can be nil, e.g. anonymous fields in structs, unnamed return types etc.
func (pkg Package) translateFieldList(fl []*ast.Field, cb func(*string, string)) {
for _, f := range fl {
var name *string
if f.Names != nil {
n := pkg.getText(f.Names[0].Pos(), f.Names[0].End())
name = &n
}
t := pkg.getText(f.Type.Pos(), f.Type.End())
cb(name, t)
}
}
// creates a Func object from the specified ast.FuncType
func (pkg Package) buildFunc(ft *ast.FuncType) (f Func) {
// appends a to s, comma-delimited style, and returns s
appendString := func(s, a string) string {
if s != "" {
s += ","
}
s += a
return s
}
// build the params type list
if ft.Params.List != nil {
p := ""
pkg.translateFieldList(ft.Params.List, func(n *string, t string) {
p = appendString(p, t)
})
f.Params = &p
}
// build the return types list
if ft.Results != nil {
r := ""
pkg.translateFieldList(ft.Results.List, func(n *string, t string) {
r = appendString(r, t)
})
f.Returns = &r
}
return
}