...
1
16
17 package main
18
19 import (
20 "flag"
21 "fmt"
22 "io"
23 "os"
24
25 "gopkg.in/yaml.v3"
26 )
27
28 func main() {
29 indent := flag.Int("indent", 2, "default indent")
30 flag.Parse()
31 for _, path := range flag.Args() {
32 sourceYaml, err := os.ReadFile(path)
33 if err != nil {
34 fmt.Fprintf(os.Stderr, "%s: %v\n", path, err)
35 continue
36 }
37 rootNode, err := fetchYaml(sourceYaml)
38 if err != nil {
39 fmt.Fprintf(os.Stderr, "%s: %v\n", path, err)
40 continue
41 }
42 writer, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
43 if err != nil {
44 fmt.Fprintf(os.Stderr, "%s: %v\n", path, err)
45 continue
46 }
47 err = streamYaml(writer, indent, rootNode)
48 if err != nil {
49 fmt.Fprintf(os.Stderr, "%s: %v\n", path, err)
50 continue
51 }
52 }
53 }
54
55 func fetchYaml(sourceYaml []byte) (*yaml.Node, error) {
56 rootNode := yaml.Node{}
57 err := yaml.Unmarshal(sourceYaml, &rootNode)
58 if err != nil {
59 return nil, err
60 }
61 return &rootNode, nil
62 }
63
64 func streamYaml(writer io.Writer, indent *int, in *yaml.Node) error {
65 encoder := yaml.NewEncoder(writer)
66 encoder.SetIndent(*indent)
67 err := encoder.Encode(in)
68 if err != nil {
69 return err
70 }
71 return encoder.Close()
72 }
73
View as plain text