-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
70 lines (61 loc) · 1.39 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
package main
import (
"errors"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"os"
"strings"
"github.com/qwsc/go-to-thrift/generator"
)
// Arguments contains command line arguments
type Arguments struct {
InputFile string
OutputFile string
AstFile string
}
var (
Args Arguments
)
func handleArgs() error {
f := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
f.StringVar(&Args.OutputFile, "o", "./output.thrift", "")
f.StringVar(&Args.AstFile, "a", "", "")
if err := f.Parse(os.Args[1:]); err != nil {
return err
}
rest := f.Args()
if len(rest) != 1 {
return errors.New("argument nums error")
}
Args.InputFile = rest[0]
return nil
}
func main() {
if err := handleArgs(); err != nil {
fmt.Println(err)
os.Exit(2)
}
fileSet := token.NewFileSet()
astFile, err := parser.ParseFile(fileSet, Args.InputFile, nil, parser.ParseComments)
if err != nil || astFile == nil {
fmt.Println(err)
os.Exit(2)
}
if Args.AstFile != "" {
builder := strings.Builder{}
_ = ast.Fprint(&builder, fileSet, astFile, ast.NotNilFilter)
if err = ioutil.WriteFile(Args.AstFile, []byte(builder.String()), 0644); err != nil { // ignore_security_alert
fmt.Println(err)
os.Exit(2)
}
}
result := generator.NewGenerator(astFile).Generate()
if err = ioutil.WriteFile(Args.OutputFile, []byte(result), 0644); err != nil { // ignore_security_alert
fmt.Println(err)
os.Exit(2)
}
}