-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfinder.go
More file actions
90 lines (72 loc) · 1.46 KB
/
finder.go
File metadata and controls
90 lines (72 loc) · 1.46 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
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"go/ast"
"go/token"
"strings"
"io"
"os"
)
type structFinder struct {
name string
filename string
found []*ast.TypeSpec
}
func newStructFinder(name string, filename string) *structFinder {
return &structFinder{name: name, filename: filename}
}
func (s *structFinder) find(n ast.Node) bool {
var ts *ast.TypeSpec
var ok bool
if ts, ok = n.(*ast.TypeSpec); !ok {
return true
}
if ts.Name == nil {
return true
}
if !strings.Contains(ts.Name.Name, s.name) {
return false
}
s.found = append(s.found, ts)
return false
}
func (s *structFinder) matches() []*ast.TypeSpec {
return s.found
}
func generate(
set *token.FileSet,
currentFile *ast.File,
allFiles []*ast.File,
dirname string,
pkgName string,
fileName string,
structToFind string,
write bool,
customWriter io.Writer,
) error {
sf := newStructFinder(structToFind, fileName)
ast.Inspect(currentFile, sf.find)
// structure not found
if len(sf.matches()) == 0 {
return nil
}
var writer io.Writer
if !write {
if customWriter != nil {
writer = customWriter
} else {
writer = os.Stdout
}
} else {
resetFile := strings.Replace(fileName, ".go", "_reset.go", 1)
// delete if needed
_ = os.Remove(resetFile)
// writeType to a file
var err error
writer, err = os.OpenFile(resetFile, os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
}
g := newGenerator(sf.matches(), dirname, allFiles, set, pkgName, writer)
return g.do()
}