-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
95 lines (79 loc) · 2.31 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
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/maxwelbm/gojson/pkg/gojson"
)
var (
name = flag.String("name", "AutoGenerated", "the name of the struct")
pkg = flag.String("pkg", "", "the name of the package for the generated code")
inputName = flag.String("input", "", "the name of the input file containing JSON (if input not provided via STDIN)")
outputName = flag.String("o", "", "the name of the file to write the output to (outputs to STDOUT by default)")
format = flag.String("fmt", "json", "the format of the input data (json or yaml, defaults to json)")
tags = flag.String("tags", "fmt", "comma separated list of the tags to put on the struct, default is the same as fmt")
// forceFloats = flag.Bool("forcefloats", false, "[experimental] force float64 type for integral values")
subStruct = flag.Bool("subStruct", false, "create types for sub-structs (default is false)")
)
func main() {
flag.Parse()
if *format != "json" && *format != "yaml" {
flag.Usage()
fmt.Fprintln(os.Stderr, "fmt must be json or yaml")
os.Exit(1)
}
tagList := make([]string, 0)
if tags == nil || *tags == "" || *tags == "fmt" {
tagList = append(tagList, *format)
} else {
tagList = strings.Split(*tags, ",")
}
if isInteractive() && *inputName == "" {
flag.Usage()
fmt.Fprintln(os.Stderr, "Expects input on stdin")
os.Exit(1)
}
var input io.Reader
input = os.Stdin
if *inputName != "" {
f, err := os.Open(*inputName)
if err != nil {
log.Fatalf("reading input file: %s", err)
}
defer f.Close()
input = f
}
var convertFloats bool
var parser gojson.Parser
switch *format {
case "json":
parser = gojson.ParseJSON
convertFloats = true
case "yaml":
parser = gojson.ParseYaml
}
if output, err := gojson.Generate(input, parser, *name, *pkg, tagList, *subStruct, convertFloats); err != nil {
fmt.Fprintln(os.Stderr, "error parsing", err)
os.Exit(1)
} else {
if *outputName != "" {
err := os.WriteFile(*outputName, output, 0644)
if err != nil {
log.Fatalf("writing output: %s", err)
}
} else {
fmt.Print(string(output))
}
}
}
// Return true if os.Stdin appears to be interactive
func isInteractive() bool {
fileInfo, err := os.Stdin.Stat()
if err != nil {
return false
}
return fileInfo.Mode()&(os.ModeCharDevice) != 0
}