...
1
2
3
4
5
6 package main
7
8 import (
9 "bytes"
10 "flag"
11 "fmt"
12 "io"
13 "io/ioutil"
14 "os"
15
16 "github.com/pelletier/go-toml"
17 )
18
19 func main() {
20 multiLineArray := flag.Bool("multiLineArray", false, "sets up the linter to encode arrays with more than one element on multiple lines instead of one.")
21 flag.Usage = func() {
22 fmt.Fprintln(os.Stderr, "tomll can be used in two ways:")
23 fmt.Fprintln(os.Stderr, "Writing to STDIN and reading from STDOUT:")
24 fmt.Fprintln(os.Stderr, " cat file.toml | tomll > file.toml")
25 fmt.Fprintln(os.Stderr, "")
26 fmt.Fprintln(os.Stderr, "Reading and updating a list of files:")
27 fmt.Fprintln(os.Stderr, " tomll a.toml b.toml c.toml")
28 fmt.Fprintln(os.Stderr, "")
29 fmt.Fprintln(os.Stderr, "When given a list of files, tomll will modify all files in place without asking.")
30 fmt.Fprintln(os.Stderr, "When given a list of files, tomll will modify all files in place without asking.")
31 fmt.Fprintln(os.Stderr, "")
32 fmt.Fprintln(os.Stderr, "Flags:")
33 fmt.Fprintln(os.Stderr, "-multiLineArray sets up the linter to encode arrays with more than one element on multiple lines instead of one.")
34 }
35 flag.Parse()
36
37
38 if flag.NArg() == 0 {
39 s, err := lintReader(os.Stdin, *multiLineArray)
40 if err != nil {
41 io.WriteString(os.Stderr, err.Error())
42 os.Exit(-1)
43 }
44 io.WriteString(os.Stdout, s)
45 } else {
46
47 for _, filename := range flag.Args() {
48 s, err := lintFile(filename, *multiLineArray)
49 if err != nil {
50 io.WriteString(os.Stderr, err.Error())
51 os.Exit(-1)
52 }
53 ioutil.WriteFile(filename, []byte(s), 0644)
54 }
55 }
56 }
57
58 func lintFile(filename string, multiLineArray bool) (string, error) {
59 tree, err := toml.LoadFile(filename)
60 if err != nil {
61 return "", err
62 }
63
64 buf := new(bytes.Buffer)
65 if err := toml.NewEncoder(buf).ArraysWithOneElementPerLine(multiLineArray).Encode(tree); err != nil {
66 panic(err)
67 }
68
69 return buf.String(), nil
70 }
71
72 func lintReader(r io.Reader, multiLineArray bool) (string, error) {
73 tree, err := toml.LoadReader(r)
74 if err != nil {
75 return "", err
76 }
77
78 buf := new(bytes.Buffer)
79 if err := toml.NewEncoder(buf).ArraysWithOneElementPerLine(multiLineArray).Encode(tree); err != nil {
80 panic(err)
81 }
82 return buf.String(), nil
83 }
84
View as plain text