...

Source file src/github.com/pelletier/go-toml/cmd/jsontoml/main.go

Documentation: github.com/pelletier/go-toml/cmd/jsontoml

     1  // Jsontoml reads JSON and converts to TOML.
     2  //
     3  // Usage:
     4  //   cat file.toml | jsontoml > file.json
     5  //   jsontoml file1.toml > file.json
     6  package main
     7  
     8  import (
     9  	"encoding/json"
    10  	"flag"
    11  	"fmt"
    12  	"io"
    13  	"io/ioutil"
    14  	"os"
    15  
    16  	"github.com/pelletier/go-toml"
    17  )
    18  
    19  func main() {
    20  	flag.Usage = func() {
    21  		fmt.Fprintln(os.Stderr, "jsontoml can be used in two ways:")
    22  		fmt.Fprintln(os.Stderr, "Writing to STDIN and reading from STDOUT:")
    23  		fmt.Fprintln(os.Stderr, "")
    24  		fmt.Fprintln(os.Stderr, "")
    25  		fmt.Fprintln(os.Stderr, "Reading from a file name:")
    26  		fmt.Fprintln(os.Stderr, " tomljson file.toml")
    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  		file, err := os.Open(files[0])
    38  		if err != nil {
    39  			printError(err, errorOutput)
    40  			return -1
    41  		}
    42  		inputReader = file
    43  		defer file.Close()
    44  	}
    45  	s, err := reader(inputReader)
    46  	if err != nil {
    47  		printError(err, errorOutput)
    48  		return -1
    49  	}
    50  	io.WriteString(output, s)
    51  	return 0
    52  }
    53  
    54  func printError(err error, output io.Writer) {
    55  	io.WriteString(output, err.Error()+"\n")
    56  }
    57  
    58  func reader(r io.Reader) (string, error) {
    59  	jsonMap := make(map[string]interface{})
    60  	jsonBytes, err := ioutil.ReadAll(r)
    61  	if err != nil {
    62  		return "", err
    63  	}
    64  	err = json.Unmarshal(jsonBytes, &jsonMap)
    65  	if err != nil {
    66  		return "", err
    67  	}
    68  
    69  	tree, err := toml.TreeFromMap(jsonMap)
    70  	if err != nil {
    71  		return "", err
    72  	}
    73  	return mapToTOML(tree)
    74  }
    75  
    76  func mapToTOML(t *toml.Tree) (string, error) {
    77  	tomlBytes, err := t.ToTomlString()
    78  	if err != nil {
    79  		return "", err
    80  	}
    81  	return string(tomlBytes[:]), nil
    82  }
    83  

View as plain text