...
1
2
3
4
5
6 package main
7
8 import (
9 "encoding/json"
10 "flag"
11 "fmt"
12 "io"
13 "os"
14
15 "github.com/pelletier/go-toml"
16 )
17
18 func main() {
19 flag.Usage = func() {
20 fmt.Fprintln(os.Stderr, "tomljson can be used in two ways:")
21 fmt.Fprintln(os.Stderr, "Writing to STDIN and reading from STDOUT:")
22 fmt.Fprintln(os.Stderr, " cat file.toml | tomljson > file.json")
23 fmt.Fprintln(os.Stderr, "")
24 fmt.Fprintln(os.Stderr, "Reading from a file name:")
25 fmt.Fprintln(os.Stderr, " tomljson file.toml")
26 }
27 flag.Parse()
28 os.Exit(processMain(flag.Args(), os.Stdin, os.Stdout, os.Stderr))
29 }
30
31 func processMain(files []string, defaultInput io.Reader, output io.Writer, errorOutput io.Writer) int {
32
33 inputReader := defaultInput
34
35 if len(files) > 0 {
36 var err error
37 inputReader, err = os.Open(files[0])
38 if err != nil {
39 printError(err, errorOutput)
40 return -1
41 }
42 }
43 s, err := reader(inputReader)
44 if err != nil {
45 printError(err, errorOutput)
46 return -1
47 }
48 io.WriteString(output, s+"\n")
49 return 0
50 }
51
52 func printError(err error, output io.Writer) {
53 io.WriteString(output, err.Error()+"\n")
54 }
55
56 func reader(r io.Reader) (string, error) {
57 tree, err := toml.LoadReader(r)
58 if err != nil {
59 return "", err
60 }
61 return mapToJSON(tree)
62 }
63
64 func mapToJSON(tree *toml.Tree) (string, error) {
65 treeMap := tree.ToMap()
66 bytes, err := json.MarshalIndent(treeMap, "", " ")
67 if err != nil {
68 return "", err
69 }
70 return string(bytes[:]), nil
71 }
72
View as plain text