1// Tomll is a linter for TOML
2//
3// Usage:
4//   cat file.toml | tomll > file_linted.toml
5//   tomll file1.toml file2.toml # lint the two files in place
6package main
7
8import (
9	"flag"
10	"fmt"
11	"io"
12	"io/ioutil"
13	"os"
14
15	"github.com/pelletier/go-toml"
16)
17
18func main() {
19	flag.Usage = func() {
20		fmt.Fprintln(os.Stderr, "tomll 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 | tomll > file.toml")
23		fmt.Fprintln(os.Stderr, "")
24		fmt.Fprintln(os.Stderr, "Reading and updating a list of files:")
25		fmt.Fprintln(os.Stderr, "  tomll a.toml b.toml c.toml")
26		fmt.Fprintln(os.Stderr, "")
27		fmt.Fprintln(os.Stderr, "When given a list of files, tomll will modify all files in place without asking.")
28	}
29	flag.Parse()
30	// read from stdin and print to stdout
31	if flag.NArg() == 0 {
32		s, err := lintReader(os.Stdin)
33		if err != nil {
34			io.WriteString(os.Stderr, err.Error())
35			os.Exit(-1)
36		}
37		io.WriteString(os.Stdout, s)
38	} else {
39		// otherwise modify a list of files
40		for _, filename := range flag.Args() {
41			s, err := lintFile(filename)
42			if err != nil {
43				io.WriteString(os.Stderr, err.Error())
44				os.Exit(-1)
45			}
46			ioutil.WriteFile(filename, []byte(s), 0644)
47		}
48	}
49}
50
51func lintFile(filename string) (string, error) {
52	tree, err := toml.LoadFile(filename)
53	if err != nil {
54		return "", err
55	}
56	return tree.String(), nil
57}
58
59func lintReader(r io.Reader) (string, error) {
60	tree, err := toml.LoadReader(r)
61	if err != nil {
62		return "", err
63	}
64	return tree.String(), nil
65}
66