-
Notifications
You must be signed in to change notification settings - Fork 4
/
walkngo.go
131 lines (104 loc) · 2.28 KB
/
walkngo.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
//
// This is the main program for a Go AST printer
//
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/raff/walkngo/printer"
"github.com/raff/walkngo/walker"
)
type Walker struct {
*walkngo.GoWalker
outdir string
prefix string
ext string
}
func fatal(err error) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
func (w Walker) Walk(path string, info os.FileInfo, err error) error {
if err != nil {
fatal(err)
}
var outpath string
if len(w.outdir) > 0 {
outpath = filepath.Join(w.outdir, path[len(w.prefix):])
}
if info.IsDir() {
if strings.HasPrefix(info.Name(), ".") && info.Name() != "." { // assume we want to skip hidden folders
return filepath.SkipDir
}
if len(outpath) > 0 {
if err := os.MkdirAll(outpath, 0755); err != nil {
fatal(err)
}
}
} else if strings.HasSuffix(path, ".go") {
if len(outpath) > 0 {
outpath = outpath[:len(outpath)-2] + w.ext
f, err := os.Create(outpath)
if err != nil {
fatal(err)
} else {
w.SetWriter(f)
defer f.Close()
}
}
if err := w.WalkFile(path); err != nil {
fatal(err)
}
}
return nil
}
func main() {
debug := flag.Bool("debug", false, "print AST nodes")
pdebug := flag.Bool("debug-printer", false, "print Printer calls")
outd := flag.String("outdir", "", "create converted files in outdir")
lang := flag.String("lang", "go", "convert to specified language (go, c, rust, swift, python)")
flag.Parse()
var p printer.Printer
switch *lang {
case "c", "cc":
p = &printer.CPrinter{}
*lang = "cc"
case "zig":
p = &printer.ZigPrinter{}
*lang = "zig"
case "go":
p = &printer.GoPrinter{}
*lang = "go"
/*
case "js":
p = &printer.JsPrinter{}
*lang = "js"
*/
case "java":
p = &printer.JavaPrinter{}
*lang = "java"
case "rust", "rs":
p = &printer.RustPrinter{}
*lang = "rs"
case "swift":
p = &printer.SwiftPrinter{}
*lang = "swift"
case "python":
p = &printer.PythonPrinter{}
*lang = "py"
default:
fmt.Println("unsupported language", *lang, "use c, go, js, java, rust, swift, python")
return
}
if *pdebug {
p = &printer.DebugPrinter{p}
}
walker := Walker{walkngo.NewWalker(p, os.Stdout, *debug), *outd, "", *lang}
for _, f := range flag.Args() {
walker.prefix = f
filepath.Walk(f, walker.Walk)
}
}