From 56844a3c249ae6400ec54cfdb5a3457ff05c0051 Mon Sep 17 00:00:00 2001 From: Erik Brakkee Date: Tue, 7 Jan 2025 22:07:31 +0100 Subject: [PATCH] can now also merge resources and do a symmetric diff. --- cmd/yamltool/merge.go | 49 ++++++++++++++++++++++++++++++++-------- cmd/yamltool/yamltool.go | 2 +- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/cmd/yamltool/merge.go b/cmd/yamltool/merge.go index 49c415c..2ceba7f 100644 --- a/cmd/yamltool/merge.go +++ b/cmd/yamltool/merge.go @@ -4,19 +4,50 @@ import ( "github.com/goccy/go-yaml" "github.com/spf13/cobra" "os" + "reflect" ) +type MyMap yaml.MapSlice + +func (m *MyMap) Set(key any, value any) { + for i := range len(*m) { + if (*m)[i].Key == key { + (*m)[i].Value = value + return + } + } + *m = append(*m, yaml.MapItem{Key: key, Value: value}) +} + +func (m MyMap) Get(key any) any { + for _, item := range m { + if item.Key == key { + return item.Value + } + } + return nil +} + func mergeMap(yaml1 yaml.MapSlice, yaml2 yaml.MapSlice) yaml.MapSlice { - res := yaml1 + res := MyMap(yaml1) - //for key, item := range yaml2 { - // switch { - // case res.ToMap()[key] != nil && type - // - // } - //} - - return res + for _, item := range yaml2 { + initialValue := res.Get(item.Key) + value := item.Value + switch { + case initialValue != nil: + if reflect.TypeOf(initialValue) == reflect.TypeOf(yaml.MapSlice{}) && + reflect.TypeOf(value) == reflect.TypeOf(yaml.MapSlice{}) { + mergedMap := mergeMap(initialValue.(yaml.MapSlice), value.(yaml.MapSlice)) + res.Set(item.Key, mergedMap) + } else { + res.Set(item.Key, item.Value) + } + default: + res.Set(item.Key, item.Value) + } + } + return yaml.MapSlice(res) } func merge(cmd *cobra.Command, args []string) error { diff --git a/cmd/yamltool/yamltool.go b/cmd/yamltool/yamltool.go index 0aeb324..81d4950 100644 --- a/cmd/yamltool/yamltool.go +++ b/cmd/yamltool/yamltool.go @@ -57,7 +57,7 @@ Shows the additions and modifications in compared to `, } cmd.AddCommand(merge) - cmd.PersistentFlags().IntVarP(&VERBOSITY, "array-output-level", + diff.PersistentFlags().IntVarP(&VERBOSITY, "array-output-level", "v", 3, `Array output level: , 0: no output, only exit status, 1: only show changed/added values,