-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsers.go
92 lines (81 loc) · 1.96 KB
/
parsers.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
package go_parser
import (
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"os"
)
type (
// Parser is an interface to parse Go files
Parser interface {
ParseFile(filePath string) (*token.FileSet, *ast.File, error)
WriteFile(filePath string, fileSet *token.FileSet, node *ast.File) error
TraverseAST(node *ast.File, fn func(ast.Node) bool) error
}
// DefaultParser is the struct for the default Go parser
DefaultParser struct{}
)
// NewDefaultParser creates a new default Go parser
func NewDefaultParser() *DefaultParser {
return &DefaultParser{}
}
// ParseFile parse the given Go file and return the file set and the AST node
func (d *DefaultParser) ParseFile(filePath string) (
*token.FileSet,
*ast.File,
error,
) {
// Parse the Go file
fileSet := token.NewFileSet()
node, err := parser.ParseFile(fileSet, filePath, nil, parser.ParseComments)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse file: %w", err)
}
return fileSet, node, nil
}
// WriteFile write the given AST node to the given file path
func (d *DefaultParser) WriteFile(
filePath string,
fileSet *token.FileSet,
node *ast.File,
) error {
// Check the file set and the AST node
if fileSet == nil {
return ErrNilFileSet
}
if node == nil {
return ErrNilASTNode
}
// Write the modified AST back to the file
file, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
panic(err)
}
}(file)
if err := printer.Fprint(file, fileSet, node); err != nil {
return fmt.Errorf("failed to write file: %w", err)
}
return nil
}
// TraverseAST traverse the given AST node and call the given function for each node
func (d *DefaultParser) TraverseAST(
node *ast.File,
fn func(ast.Node) bool,
) error {
// Check if the node is nil
if node == nil {
return ErrNilFileSet
}
// Traverse the AST to find the struct and field
ast.Inspect(
node, fn,
)
return nil
}