-
Notifications
You must be signed in to change notification settings - Fork 0
/
xast_example_test.go
84 lines (72 loc) · 1.49 KB
/
xast_example_test.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
package xast_test
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"strings"
"github.com/OneOfOne/xast"
)
func ExampleWalk() {
src := `
package main
// Foo is a foo!
type Foo struct{}
// NotFoo is not a foo!
type NotFoo struct{}
// DeleteMe needs to be deleted with this comment.
func DeleteMe() {}
// DeleteMeToo says hi.
func DeleteMeToo() {}
// GoodBoy is a good boy, yes he is!
func GoodBoy() {
var nf NotFoo
_ = nf
}
`
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "foo.go", src, parser.ParseComments)
if err != nil {
panic(err)
}
rewriteFn := func(n *xast.Node) *xast.Node {
switch x := n.Node().(type) {
case *ast.TypeSpec:
if x.Name.Name == "Foo" {
x.Name.Name = "Bar"
// remove Foo's comment.
n.Parent().Node().(*ast.GenDecl).Doc.List = nil
}
case *ast.CommentGroup:
if strings.Contains(x.Text(), "NotFoo") {
x.List[0].Text = "// NotFoo got pwned."
}
return n.Break() // won't delete the node but Walk won't go down its children list.
case *ast.FuncDecl:
switch x.Name.Name {
case "DeleteMe", "DeleteMeToo":
return n.Delete()
case "GoodBoy":
x.Doc.List = nil // remove the goodboy's comment :-/
}
}
return n
}
var buf bytes.Buffer
printer.Fprint(&buf, fset, xast.Walk(file, rewriteFn))
fmt.Println(buf.String())
// Output:
// package main
//
// type Bar struct{}
//
// // NotFoo got pwned.
// type NotFoo struct{}
//
// func GoodBoy() {
// var nf NotFoo
// _ = nf
// }
}