-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspector.go
260 lines (202 loc) · 5.72 KB
/
inspector.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package lib
import (
"fmt"
"go/ast"
"go/doc"
"go/parser"
"go/token"
"io/ioutil"
"log"
"path"
"strings"
"golang.org/x/tools/imports"
)
// FormatCode formats the code
func FormatCode(code string) ([]byte, error) {
opts := &imports.Options{
TabIndent: true,
TabWidth: 2,
Fragment: true,
Comments: true,
}
return imports.Process("", []byte(code), opts)
}
type ParsedStruct struct {
Docs []string
Name string
Fields map[string]string
}
// Reflection: https://stackoverflow.com/questions/20170275/how-to-find-the-type-of-an-object-in-go
//
func ParseStruct2(filePath string) (*ParsedStruct, error) {
p := &ParsedStruct{
Docs: []string{},
Fields: map[string]string{},
}
fileBytes, _ := ioutil.ReadFile(filePath)
src := string(fileBytes)
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, path.Base(filePath), src, 0)
if err != nil {
return nil, err
}
fieldNo := 0
for _, node := range f.Decls {
switch node.(type) {
case *ast.GenDecl:
decl := node.(*ast.GenDecl)
for _, spec := range decl.Specs {
switch spec.(type) {
case *ast.TypeSpec:
typeSpec := spec.(*ast.TypeSpec)
if decl.Doc != nil {
for _, d := range decl.Doc.List {
p.Docs = append(p.Docs, string(src[d.Pos()-1:d.End()-1]))
}
}
p.Name = typeSpec.Name.Name
switch typeSpec.Type.(type) {
case *ast.StructType:
structType := typeSpec.Type.(*ast.StructType)
for _, field := range structType.Fields.List {
fieldType := ""
// switch field.Type.(type) {
// case *ast.ArrayType:
// fmt.Println(structType.Fields)
// at := field.Type.(*ast.ArrayType)
// fieldType = "[]" + fmt.Sprint(at.Elt)
typeExpr := field.Type
// Fetch Type from scource code
typeInSource := src[typeExpr.Pos()-1 : typeExpr.End()-1]
fmt.Println(typeExpr.Pos()-1, typeExpr.End()-1, typeInSource)
fieldType = typeInSource
// fmt.Println("ArrayType: ", at.Elt)
// case *ast.Ident:
// i := field.Type.(*ast.Ident)
// fieldType = i.Name
// }
if len(field.Names) > 0 {
for _, name := range field.Names {
fmt.Printf("\tField: name=%s type=%s\n", name.Name, fieldType)
p.Fields[name.Name] = fieldType
}
} else {
p.Fields[fmt.Sprintf("#embedded%d", fieldNo)] = fieldType
}
}
}
}
}
}
}
return p, nil
}
// ParseStruct parses a struct
func ParseStruct(src []byte, structName string, copyDocuments bool, copyTypeDocuments bool, pkgName string) (methods []Method, imports []string, typeDoc string) {
var file *ast.File
var e error
fset := token.NewFileSet()
if file, e = parser.ParseFile(fset, "", src, parser.ParseComments); e != nil {
log.Fatal(e.Error())
}
for _, i := range file.Imports {
if i.Name != nil {
imports = append(imports, fmt.Sprintf("%s %s", i.Name.String(), i.Path.Value))
} else {
imports = append(imports, fmt.Sprintf("%s", i.Path.Value))
}
}
for _, d := range file.Decls {
if a, decl := GetReceiverTypeName(src, d); a == structName {
if !decl.Name.IsExported() {
continue
}
params := FormatFieldList(src, decl.Type.Params, pkgName)
ret := FormatFieldList(src, decl.Type.Results, pkgName)
method := fmt.Sprintf("%s(%s) (%s)", decl.Name.String(), strings.Join(params, ", "), strings.Join(ret, ", "))
var Documents []string
if decl.Doc != nil && copyDocuments {
for _, d := range decl.Doc.List {
Documents = append(Documents, string(src[d.Pos()-1:d.End()-1]))
}
}
methods = append(methods, Method{
Code: method,
Documents: Documents,
LineNo: int(decl.Recv.Pos()),
})
}
}
if copyTypeDocuments {
pkg := &ast.Package{Files: map[string]*ast.File{"": file}}
doc := doc.New(pkg, "", doc.AllDecls)
for _, t := range doc.Types {
if t.Name == structName {
typeDoc = strings.TrimSuffix(t.Doc, "\n")
}
}
}
return
}
// Method describes code and Documents for a method
type Method struct {
Code string
Documents []string
LineNo int
}
// Lines return a a slice of documentation and code
func (m *Method) Lines() []string {
var lines []string
lines = append(lines, m.Documents...)
lines = append(lines, m.Code)
return lines
}
// FormatFieldList returns a list of formatted list of fields
func FormatFieldList(src []byte, fieldList *ast.FieldList, pkgName string) (fields []string) {
if fieldList == nil {
return
}
// Loop through the list of fields in the field list
for _, l := range fieldList.List {
names := make([]string, len(l.Names))
for i, n := range l.Names {
names[i] = n.Name
}
t := string(src[l.Type.Pos()-1 : l.Type.End()-1])
t = strings.Replace(t, pkgName+".", "", -1)
if len(names) > 0 {
typeSharingArgs := strings.Join(names, ", ")
fields = append(fields, fmt.Sprintf("%s %s", typeSharingArgs, t))
} else {
fields = append(fields, t)
}
}
return fields
}
// GetFuncDeclarationReceiverType returns the receiver type of a function declaration
func GetFuncDeclarationReceiverType(fd *ast.FuncDecl) (expr ast.Expr, e error) {
if fd.Recv == nil {
e = fmt.Errorf("fd is a function, not a method")
return
}
expr = fd.Recv.List[0].Type
return
}
// GetReceiverTypeName returns the name of the receiver type and the declaration
func GetReceiverTypeName(src []byte, fl interface{}) (name string, funcDef *ast.FuncDecl) {
var ok bool
var expr ast.Expr
var e error
if funcDef, ok = fl.(*ast.FuncDecl); !ok {
return
}
if expr, e = GetFuncDeclarationReceiverType(funcDef); e != nil {
return
}
name = string(src[expr.Pos()-1 : expr.End()-1])
if len(name) > 0 && name[0] == '*' {
name = name[1:]
}
return
}