json2go/cmd/json2go/main.go (view raw)
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "flag" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "os" |
| 8 | |
| 9 | "olexsmir.xyz/json2go" |
| 10 | ) |
| 11 | |
| 12 | func main() { |
| 13 | typeName := flag.String("type", "AutoGenerated", "a name for generated type") |
| 14 | showHelp := flag.Bool("help", false, "show help") |
| 15 | flag.Parse() |
| 16 | |
| 17 | if *showHelp { |
| 18 | printHelp() |
| 19 | os.Exit(0) |
| 20 | } |
| 21 | |
| 22 | // get input |
| 23 | args := flag.Args() |
| 24 | |
| 25 | stat, err := os.Stdin.Stat() |
| 26 | if err != nil { |
| 27 | fmt.Printf("Failed to get stdin stat: %v\n", err) |
| 28 | os.Exit(1) |
| 29 | } |
| 30 | |
| 31 | isPiped := (stat.Mode() & os.ModeCharDevice) == 0 |
| 32 | |
| 33 | var input string |
| 34 | switch { |
| 35 | case len(args) > 0: |
| 36 | input = args[0] |
| 37 | case isPiped: |
| 38 | data, rerr := io.ReadAll(os.Stdin) |
| 39 | if rerr != nil { |
| 40 | fmt.Printf("Failed to read piped input: %v\n", rerr) |
| 41 | os.Exit(1) |
| 42 | } |
| 43 | input = string(data) |
| 44 | default: |
| 45 | printHelp() |
| 46 | os.Exit(1) |
| 47 | } |
| 48 | |
| 49 | transformer := json2go.NewTransformer() |
| 50 | type_, err := transformer.Transform(*typeName, input) |
| 51 | if err != nil { |
| 52 | fmt.Printf("Failed to transform json to type annotation: %v\n", err) |
| 53 | os.Exit(1) |
| 54 | } |
| 55 | |
| 56 | fmt.Println(type_) |
| 57 | } |
| 58 | |
| 59 | func printHelp() { |
| 60 | fmt.Println(` |
| 61 | Convert json to Go type annotations. |
| 62 | |
| 63 | Usage: |
| 64 | echo '{"json": "here"}' | json2go |
| 65 | echo '{"json": "here"}' | json2go -type=MyTypeName |
| 66 | json2go -type=MyTypeName '{"json": "here"}'`[1:]) |
| 67 | } |