-
Notifications
You must be signed in to change notification settings - Fork 124
/
yaml.go
39 lines (34 loc) · 1.41 KB
/
yaml.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
package util
import (
"bytes"
"github.com/pkg/errors"
yaml2 "gopkg.in/yaml.v2"
"gopkg.in/yaml.v3"
)
const UnmarshalStrictError = "error unmarshalling yaml strict"
// UnmarshalYAMLWithFallback attempts to use yaml v3 to unmarshal, but on failure attempts yaml v2. If this
// succeeds then we can assume in is outdated yaml and requires v2, otherwise we only return the error relevant to the
// current yaml version. This should only be used for cases where we expect v3 to fail for legacy cases.
func UnmarshalYAMLWithFallback(in []byte, out interface{}) error {
err := yaml.Unmarshal(in, out)
if err != nil {
// try the older version of yaml before erroring, in case it's just an outdated yaml
if err2 := yaml2.Unmarshal(in, out); err2 != nil {
return err
}
}
return nil
}
// UnmarshalYAMLStrictWithFallback attempts to use yaml v3 to unmarshal strict, but on failure attempts yaml v2. If this
// succeeds then we can assume in is outdated yaml and requires v2, otherwise we only return the error relevant to the
// current yaml version. This should only be used for cases where we expect v3 to fail for legacy cases.
func UnmarshalYAMLStrictWithFallback(in []byte, out interface{}) error {
d := yaml.NewDecoder(bytes.NewReader(in))
d.KnownFields(true)
if err := d.Decode(out); err != nil {
if err2 := yaml2.UnmarshalStrict(in, out); err2 != nil {
return errors.Wrap(err, UnmarshalStrictError)
}
}
return nil
}