OSDN Git Service

Hulk did something
[bytom/vapor.git] / vendor / github.com / pelletier / go-toml / cmd / tomljson / main.go
1 // Tomljson reads TOML and converts to JSON.
2 //
3 // Usage:
4 //   cat file.toml | tomljson > file.json
5 //   tomljson file1.toml > file.json
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 Writing to STDIN and reading from STDOUT:
22   cat file.toml | tomljson > file.json
23
24 Reading from a file name:
25   tomljson file.toml
26 `)
27         }
28         flag.Parse()
29         os.Exit(processMain(flag.Args(), os.Stdin, os.Stdout, os.Stderr))
30 }
31
32 func processMain(files []string, defaultInput io.Reader, output io.Writer, errorOutput io.Writer) int {
33         // read from stdin and print to stdout
34         inputReader := defaultInput
35
36         if len(files) > 0 {
37                 var err error
38                 inputReader, err = os.Open(files[0])
39                 if err != nil {
40                         printError(err, errorOutput)
41                         return -1
42                 }
43         }
44         s, err := reader(inputReader)
45         if err != nil {
46                 printError(err, errorOutput)
47                 return -1
48         }
49         io.WriteString(output, s+"\n")
50         return 0
51 }
52
53 func printError(err error, output io.Writer) {
54         io.WriteString(output, err.Error()+"\n")
55 }
56
57 func reader(r io.Reader) (string, error) {
58         tree, err := toml.LoadReader(r)
59         if err != nil {
60                 return "", err
61         }
62         return mapToJSON(tree)
63 }
64
65 func mapToJSON(tree *toml.Tree) (string, error) {
66         treeMap := tree.ToMap()
67         bytes, err := json.MarshalIndent(treeMap, "", "  ")
68         if err != nil {
69                 return "", err
70         }
71         return string(bytes[:]), nil
72 }