forked from miekg/yamlfmt
-
Notifications
You must be signed in to change notification settings - Fork 2
/
yamlfmt.go
76 lines (64 loc) · 1.33 KB
/
yamlfmt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"gopkg.in/yaml.v3"
)
func main() {
overwrite := flag.Bool("w", false, "overwrite the input file")
indent := flag.Int("indent", 2, "default indent")
flag.Parse()
if flag.NArg() > 0 {
for _, f := range flag.Args() {
formatFile(f, *indent, *overwrite)
}
} else {
formatStream(os.Stdin, os.Stdout, *indent)
}
}
func formatFile(f string, indent int, overwrite bool) {
r, err := os.Open(f)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
if e := formatStream(r, &out, indent); e != nil {
log.Fatalf("Failed formatting YAML stream: %v", e)
}
r.Close()
if e := dumpStream(&out, f, overwrite); e != nil {
log.Fatalf("Cannot overwrite: %v", e)
}
}
func formatStream(r io.Reader, out io.Writer, indent int) error {
d := yaml.NewDecoder(r)
in := yaml.Node{}
err := d.Decode(&in)
for err == nil {
e := yaml.NewEncoder(out)
e.SetIndent(indent)
if err := e.Encode(&in); err != nil {
log.Fatal(err)
}
e.Close()
if err = d.Decode(&in); err == nil {
fmt.Fprintln(out, "---")
}
}
if err != nil && err != io.EOF {
return err
}
return nil
}
func dumpStream(out *bytes.Buffer, f string, overwrite bool) error {
if overwrite {
return ioutil.WriteFile(f, out.Bytes(), 0744)
}
_, err := io.Copy(os.Stdout, out)
return err
}