-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (58 loc) · 1.59 KB
/
main.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
package main
import (
"fmt"
"go/ast"
"go/printer"
"go/token"
"log"
"os"
"path"
"path/filepath"
"reflect"
"github.com/ivzhh/go-ast-transform/rewriter"
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
pkgname := reflect.TypeOf(struct{}{}).PkgPath()
tmpdir := filepath.Join(os.TempDir(), pkgname)
if err := os.MkdirAll(tmpdir, 0644); err != nil {
log.Fatalf("create output dir fail: %s", err.Error())
}
inputfile := path.Join("testdata", "example1.go")
args := os.Args[1:]
if len(args) > 1 {
log.Fatalf("please run command: %s path_to_go_file.go", pkgname)
} else if len(args) == 1 {
inputfile = args[0]
}
if _, err := os.Stat(inputfile); os.IsNotExist(err) {
log.Fatalf("input go file doesn't exist: %s", inputfile)
}
fset := token.NewFileSet()
var err error
r := rewriter.NewRewritter(fset)
fr := r.NewFileRewritter(inputfile)
rewritten := fr.RewriteforTranspiler()
{
var f *os.File
fmtfile := filepath.Join(tmpdir, fmt.Sprintf("fmt-%s", filepath.Base(inputfile)))
if f, err = os.Create(fmtfile); err != nil {
log.Fatalf("create file: %+v", err)
}
printer.Fprint(f, fset, rewritten)
log.Printf("output to %s", fmtfile)
defer func() { f.Close() }()
}
{
var f *os.File
outputfile := filepath.Join(tmpdir, fmt.Sprintf("ast-%s", filepath.Base(inputfile)))
if f, err = os.Create(outputfile); err != nil {
log.Fatalf("create file: %+v", err)
}
log.Printf("output to %s", outputfile)
if err = ast.Fprint(f, fset, rewritten, nil); err != nil {
log.Fatalf("output ast to file: %+v", err)
}
defer func() { f.Close() }()
}
}