-
Notifications
You must be signed in to change notification settings - Fork 308
/
Copy pathgenerate.go
88 lines (75 loc) · 2.36 KB
/
generate.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
package internal
import (
"flag"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"os"
"path"
)
var (
useFloat = flag.Bool("use-float", false, "By default, FIX float fields are represented as arbitrary-precision fixed-point decimal numbers. Set to 'true' to instead generate FIX float fields as float64 values.")
useUDecimal = flag.Bool("use-udecimal", false, "By default, FIX uses the shopspring/decimal library for fixed-point decimal numbers. Set to 'true' to instead use the quagmt/udecimal library.")
pkgRoot = flag.String("pkg-root", "github.com/quickfixgo", "Set a string here to provide a custom import path for generated packages.")
tabWidth = 8
printerMode = printer.UseSpaces | printer.TabIndent
)
// ParseError indicates generated go source is invalid
type ParseError struct {
path string
err error
}
func (e ParseError) Error() string {
return fmt.Sprintf("Error parsing %v: %v", e.path, e.err)
}
// ErrorHandler is a convenience struct for interpretting generation Errors
type ErrorHandler struct {
ReturnCode int
}
// Handle interprets the generation error. Proceeds with setting returnCode, or panics depending on error type
func (h *ErrorHandler) Handle(err error) {
switch err := err.(type) {
case nil:
//do nothing
case ParseError:
fmt.Println(err)
h.ReturnCode = 1
default:
panic(err)
}
}
func write(filePath string, fset *token.FileSet, f *ast.File) error {
if parentdir := path.Dir(filePath); parentdir != "." {
if err := os.MkdirAll(parentdir, os.ModePerm); err != nil {
return err
}
}
file, err := os.Create(filePath)
if err != nil {
return err
}
ast.SortImports(fset, f)
err = (&printer.Config{Mode: printerMode, Tabwidth: tabWidth}).Fprint(file, fset, f)
_ = file.Close()
return err
}
// WriteFile parses the generated code in fileOut and writes the code out to filePath.
// Function performs some import clean up and gofmts the code before writing
// Returns ParseError if the generated source is invalid but is written to filePath
func WriteFile(filePath, fileOut string) error {
fset := token.NewFileSet()
f, pErr := parser.ParseFile(fset, "", fileOut, parser.ParseComments)
if f == nil {
return pErr
}
//write out the file regardless of parseFile errors
if err := write(filePath, fset, f); err != nil {
return err
}
if pErr != nil {
return ParseError{path: filePath, err: pErr}
}
return nil
}