jsontoml: port to v2 (#726)

Fixes #719
This commit is contained in:
Thomas Pelletier
2021-12-31 14:40:20 -05:00
committed by GitHub
parent 82f8dad811
commit d8ddc00c61
7 changed files with 254 additions and 175 deletions
+12 -45
View File
@@ -1,67 +1,29 @@
// Tomljson reads TOML and converts to JSON.
// Package tomljson is a program that converts TOML to JSON.
//
// Usage:
// cat file.toml | tomljson > file.json
// tomljson file1.toml > file.json
// tomljson file.toml > file.json
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"github.com/pelletier/go-toml/v2"
"github.com/pelletier/go-toml/v2/internal/cli"
)
func usage() {
fmt.Fprint(os.Stderr, `tomljson can be used in two ways:
func main() {
usage := `tomljson can be used in two ways:
Reading from stdin:
cat file.toml | tomljson > file.json
Reading from a file:
tomljson file.toml > file.json
`)
}
func init() {
flag.Usage = usage
}
func main() {
flag.Parse()
os.Exit(processMain(flag.Args(), os.Stdin, os.Stdout, os.Stderr))
}
func processMain(files []string, input io.Reader, output, error io.Writer) int {
err := run(files, input, output)
if err != nil {
var derr *toml.DecodeError
if errors.As(err, &derr) {
fmt.Fprintln(error, derr.String())
row, col := derr.Position()
fmt.Fprintln(error, "error occurred at row", row, "column", col)
} else {
fmt.Fprintln(error, err.Error())
}
return -1
}
return 0
}
func run(files []string, input io.Reader, output io.Writer) error {
if len(files) > 0 {
f, err := os.Open(files[0])
if err != nil {
return err
}
defer f.Close()
input = f
}
return convert(input, output)
`
cli.Execute(usage, convert)
}
func convert(r io.Reader, w io.Writer) error {
@@ -70,6 +32,11 @@ func convert(r io.Reader, w io.Writer) error {
d := toml.NewDecoder(r)
err := d.Decode(&v)
if err != nil {
var derr *toml.DecodeError
if errors.As(err, &derr) {
row, col := derr.Position()
return fmt.Errorf("%s\nerror occurred at row %d column %d", derr.String(), row, col)
}
return err
}