-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
78 lines (63 loc) · 1.82 KB
/
parser.go
File metadata and controls
78 lines (63 loc) · 1.82 KB
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
package main
import (
"fmt"
"go/ast"
"golang.org/x/tools/go/packages"
)
func parseDir(config *Config) (*StructInfo, error) {
cfg := &packages.Config{
Mode: packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedName,
Tests: false,
Dir: config.dir,
}
// Load all packages in the module or a specific subset
// You can specify patterns like "./..." for the current module recursively or specific paths.
pkgs, err := packages.Load(cfg, "./...")
if err != nil {
return nil, err
}
for _, pkg := range pkgs {
// Iterate over each file in the package
for _, syn := range pkg.Syntax {
structInfo := parseFileDeclarations(syn, config.structName)
if structInfo != nil {
structInfo.OutputPackageName = config.outputPkg
structInfo.ImportPath = pkg.PkgPath
structInfo.OutputTypeName = fmt.Sprintf("%s.%s", pkg.Name, config.structName)
return structInfo, nil
}
}
}
return nil, fmt.Errorf("struct %s not found in directory %s", config.structName, config.dir)
}
func parseFileDeclarations(file *ast.File, structName string) *StructInfo {
for _, decl := range file.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok {
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
structType, ok := typeSpec.Type.(*ast.StructType)
if !ok {
continue
}
if typeSpec.Name.Name != structName {
continue
}
var fields []StructField
for _, field := range structType.Fields.List {
for _, name := range field.Names {
// do we care if the field is Uppercased or not?
fields = append(fields, StructField{Name: name.Name, Type: fmt.Sprint(field.Type)})
}
}
return &StructInfo{
BuilderTypeName: structName,
Fields: fields,
}
}
}
}
return nil
}