/
generator.go
111 lines (94 loc) · 2.09 KB
/
generator.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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"path"
"strings"
)
type byCommentGenerator struct {
commonGenerator
}
type byCommentGeneratorVisitorFn = func(
pkgName, path string,
spec *ast.TypeSpec,
imports map[string]string,
) error
func newByCommentGenerator(
markerComment string,
visitor byCommentGeneratorVisitorFn,
) byCommentGenerator {
return byCommentGenerator{
commonGenerator: commonGenerator{
visitor: func(
pkgName, path string,
decl *ast.GenDecl,
imports map[string]string,
) error {
if !strings.Contains(decl.Doc.Text(), markerComment) {
return nil
}
for _, s := range decl.Specs {
spec, ok := s.(*ast.TypeSpec)
if !ok {
continue
}
if err := visitor(pkgName, path, spec, imports); err != nil {
return err
}
}
return nil
},
},
}
}
type commonGenerator struct {
visitor func(
pkgName, path string,
decl *ast.GenDecl,
imports map[string]string,
) error
}
func (g commonGenerator) Generate(path string) error {
pkgName, dd, err := g.parseFile(path)
if err != nil {
return fmt.Errorf("faile to parse file: %w", err)
}
if err := g.generate(pkgName, path, dd); err != nil {
return fmt.Errorf("failed to find target types: %w", err)
}
return nil
}
func (commonGenerator) parseFile(p string) (pkgName string, dd []ast.Decl, err error) {
const flags = parser.ParseComments | parser.AllErrors
f, err := parser.ParseFile(token.NewFileSet(), p, nil, flags)
if err != nil {
return "", nil, err
}
return f.Name.Name, f.Decls, nil
}
func (g commonGenerator) generate(pkgName, filePath string, dd []ast.Decl) error {
imports := map[string]string{}
for _, d := range dd {
decl, ok := d.(*ast.GenDecl)
if !ok {
return nil
}
if _, ok := decl.Specs[0].(*ast.ImportSpec); ok {
for _, s := range decl.Specs {
spec, ok := s.(*ast.ImportSpec)
if !ok {
continue
}
p := strings.Trim(spec.Path.Value, `"`)
imports[path.Base(p)] = p
}
continue
}
if err := g.visitor(pkgName, filePath, decl, imports); err != nil {
return err
}
}
return nil
}