From c7d257b3820f9689f03a7adc1eeb411d99acb49d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Otto=20Kr=C3=B6pke?= Date: Thu, 18 May 2023 15:08:31 +0200 Subject: [PATCH] Support for multiple yaml documents in stdin/file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jan-Otto Kröpke --- pkg/cli/values/options.go | 25 +++++++++++++++++-------- pkg/cli/values/options_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/pkg/cli/values/options.go b/pkg/cli/values/options.go index 06631cd33..31d20dc25 100644 --- a/pkg/cli/values/options.go +++ b/pkg/cli/values/options.go @@ -17,13 +17,14 @@ limitations under the License. package values import ( + "bytes" "io" "net/url" "os" "strings" "github.com/pkg/errors" - "sigs.k8s.io/yaml" + "k8s.io/apimachinery/pkg/util/yaml" "helm.sh/helm/v3/pkg/getter" "helm.sh/helm/v3/pkg/strvals" @@ -46,18 +47,26 @@ func (opts *Options) MergeValues(p getter.Providers) (map[string]interface{}, er // User specified a values files via -f/--values for _, filePath := range opts.ValueFiles { - currentMap := map[string]interface{}{} - - bytes, err := readFile(filePath, p) + data, err := readFile(filePath, p) if err != nil { return nil, err } - if err := yaml.Unmarshal(bytes, ¤tMap); err != nil { - return nil, errors.Wrapf(err, "failed to parse %s", filePath) + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + + for { + currentMap := map[string]interface{}{} + err := decoder.Decode(¤tMap) + + if err == io.EOF { + break + } else if err != nil { + return nil, errors.Wrapf(err, "failed to parse %s", filePath) + } + + // Merge with the previous map + base = mergeMaps(base, currentMap) } - // Merge with the previous map - base = mergeMaps(base, currentMap) } // User specified a value via --set-json diff --git a/pkg/cli/values/options_test.go b/pkg/cli/values/options_test.go index 54124c0fa..0aeb96d3e 100644 --- a/pkg/cli/values/options_test.go +++ b/pkg/cli/values/options_test.go @@ -17,6 +17,7 @@ limitations under the License. package values import ( + "os" "reflect" "testing" @@ -86,3 +87,31 @@ func TestReadFile(t *testing.T) { t.Errorf("Expected error when has special strings") } } + +func TestMergeYaml(t *testing.T) { + var p getter.Providers + valuesFile, err := os.CreateTemp("", "values.yaml") + if err != nil { + t.Error(err) + } + + _, err = valuesFile.WriteString("---\nkey1: value1\n---\nkey2: value2") + if err != nil { + t.Error(err) + } + + options := Options{ValueFiles: []string{valuesFile.Name()}} + testMap, err := options.MergeValues(p) + if err != nil { + t.Error(err) + } + + expectedMap := map[string]interface{}{ + "key1": "value1", + "key2": "value2", + } + equal := reflect.DeepEqual(testMap, expectedMap) + if !equal { + t.Errorf("Expected a map with different keys to merge properly with another map. Expected: %v, got %v", expectedMap, testMap) + } +}