/
transformation.go
61 lines (52 loc) · 1.24 KB
/
transformation.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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"os"
"strings"
)
func main() {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "simple.go", nil, 0)
if err != nil {
// Whoops!
}
ast.Walk(new(FuncVisitor), file)
printer.Fprint(os.Stdout, fset, file)
fmt.Println("-------------------------------------")
ast.Walk(new(ImportVisitor), file)
printer.Fprint(os.Stdout, fset, file)
f, _ := os.Create("/tmp/new_simple.go")
printer.Fprint(f, fset, file)
}
type FuncVisitor struct {
}
func (v *FuncVisitor) Visit(node ast.Node) (w ast.Visitor) {
switch t := node.(type) {
case *ast.FuncDecl:
t.Name = ast.NewIdent(strings.Title(t.Name.Name))
}
return v
}
type ImportVisitor struct{}
func (i *ImportVisitor) Visit(node ast.Node) (w ast.Visitor) {
switch t := node.(type) {
case *ast.GenDecl:
if t.Tok == token.IMPORT {
fmt.Println(len(t.Specs))
newSpecs := []ast.Spec{}
for _, spec := range t.Specs {
newSpecs = append(newSpecs, spec)
fmt.Printf(">>>:% #v\n", spec.(*ast.ImportSpec).Path)
}
newPackage := &ast.BasicLit{token.NoPos, token.STRING, `"strings"`}
newSpecs = append(newSpecs, &ast.ImportSpec{Path: newPackage})
t.Specs = newSpecs
}
return nil
}
return i
}