-
Notifications
You must be signed in to change notification settings - Fork 1
/
format.go
44 lines (40 loc) · 870 Bytes
/
format.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
package yamlfmt
import (
"bytes"
"fmt"
"io"
"gopkg.in/yaml.v3"
)
const indent = 2
// Format reads in a yaml document and outputs the yaml in a standard format.
// If sort is true than dictionary keys are sorted lexicographically
// Indents are set to 2
// Lists are not indented
func Format(r io.Reader, sort bool) ([]byte, error) {
dec := yaml.NewDecoder(r)
out := bytes.NewBuffer(nil)
for {
enc := yaml.NewEncoder(out)
enc.SetIndent(indent)
defer enc.Close()
var doc yaml.Node
err := dec.Decode(&doc)
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("failed decoding: %s", err)
}
out.WriteString("---\n")
if sort {
err = enc.Encode(sortYAML(&doc))
} else {
err = enc.Encode(&doc)
}
if err != nil {
return nil, fmt.Errorf("failed encoding: %s", err)
}
enc.Close()
}
return out.Bytes(), nil
}