Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/util/compare_yaml.go
4093 views
1
package util
2
3
import (
4
"bytes"
5
"io"
6
7
"gopkg.in/yaml.v2"
8
)
9
10
// CompareYAML marshals a and b to YAML and ensures that their contents are
11
// equal. If either Marshal fails, CompareYAML returns false.
12
func CompareYAML(a, b interface{}) bool {
13
aBytes, err := yaml.Marshal(a)
14
if err != nil {
15
return false
16
}
17
bBytes, err := yaml.Marshal(b)
18
if err != nil {
19
return false
20
}
21
return bytes.Equal(aBytes, bBytes)
22
}
23
24
// CompareYAMLWithHook marshals both a and b to YAML and checks the results
25
// for equality, allowing for a hook to define custom marshaling behavior.
26
// If either Marshal fails, CompareYAMLWithHook returns false.
27
func CompareYAMLWithHook(a, b interface{}, hook func(in interface{}) (ok bool, out interface{}, err error)) bool {
28
aBytes, err := marshalWithHook(a, hook)
29
if err != nil {
30
return false
31
}
32
bBytes, err := marshalWithHook(b, hook)
33
if err != nil {
34
return false
35
}
36
return bytes.Equal(aBytes, bBytes)
37
}
38
39
func marshalWithHook(i interface{}, hook func(in interface{}) (ok bool, out interface{}, err error)) ([]byte, error) {
40
var buf bytes.Buffer
41
err := marshalToWriterWithHook(i, &buf, hook)
42
return buf.Bytes(), err
43
}
44
45
func marshalToWriterWithHook(i interface{}, w io.Writer, hook func(in interface{}) (ok bool, out interface{}, err error)) error {
46
enc := yaml.NewEncoder(w)
47
defer enc.Close()
48
enc.SetHook(hook)
49
return enc.Encode(i)
50
}
51
52