Files
helmfile/pkg/yaml/yaml.go
T
dependabot[bot]andyxxhero f0965d6d03 build(deps): bump github.com/goccy/go-yaml from 1.13.9 to 1.14.0 (#1782)
* build(deps): bump github.com/goccy/go-yaml from 1.13.9 to 1.14.0

Bumps [github.com/goccy/go-yaml](https://github.com/goccy/go-yaml) from 1.13.9 to 1.14.0.
- [Release notes](https://github.com/goccy/go-yaml/releases)
- [Changelog](https://github.com/goccy/go-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/goccy/go-yaml/compare/v1.13.9...v1.14.0)

---
updated-dependencies:
- dependency-name: github.com/goccy/go-yaml
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* feat(yaml): allow duplicate keys in strict mode

Signed-off-by: yxxhero <aiopsclub@163.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: yxxhero <aiopsclub@163.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: yxxhero <aiopsclub@163.com>
2024-11-14 08:27:43 +08:00

84 lines
1.7 KiB
Go

package yaml
import (
"bytes"
"io"
"github.com/goccy/go-yaml"
v2 "gopkg.in/yaml.v2"
"github.com/helmfile/helmfile/pkg/runtime"
)
type Encoder interface {
Encode(any) error
Close() error
}
// NewEncoder creates and returns a function that is used to encode a Go object to a YAML document
func NewEncoder(w io.Writer) Encoder {
if runtime.GoccyGoYaml {
return yaml.NewEncoder(w)
}
return v2.NewEncoder(w)
}
func Unmarshal(data []byte, v any) error {
if runtime.GoccyGoYaml {
return yaml.Unmarshal(data, v)
}
return v2.Unmarshal(data, v)
}
// NewDecoder creates and returns a function that is used to decode a YAML document
// contained within the YAML document stream per each call.
// When strict is true, this function ensures that every field found in the YAML document
// to have the corresponding field in the decoded Go struct.
func NewDecoder(data []byte, strict bool) func(any) error {
if runtime.GoccyGoYaml {
var opts []yaml.DecodeOption
if strict {
opts = append(opts, yaml.DisallowUnknownField())
}
// allow duplicate keys
opts = append(opts, yaml.AllowDuplicateMapKey())
decoder := yaml.NewDecoder(
bytes.NewReader(data),
opts...,
)
return func(v any) error {
return decoder.Decode(v)
}
}
decoder := v2.NewDecoder(bytes.NewReader(data))
decoder.SetStrict(strict)
return func(v any) error {
return decoder.Decode(v)
}
}
func Marshal(v any) ([]byte, error) {
if runtime.GoccyGoYaml {
var b bytes.Buffer
yamlEncoder := yaml.NewEncoder(
&b,
yaml.Indent(2),
yaml.UseSingleQuote(true),
yaml.UseLiteralStyleIfMultiline(true),
)
err := yamlEncoder.Encode(v)
defer func() {
_ = yamlEncoder.Close()
}()
return b.Bytes(), err
}
return v2.Marshal(v)
}