From ef0ef6e215e860a8303087299bcc002b40d111c5 Mon Sep 17 00:00:00 2001 From: Erik Brakkee Date: Fri, 10 Jan 2025 19:38:43 +0100 Subject: [PATCH] preserving ordering in arrays. --- cmd/yamltool/diff.go | 13 ++++++++++--- cmd/yamltool/merge.go | 6 +++++- cmd/yamltool/parse.go | 6 +++--- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/cmd/yamltool/diff.go b/cmd/yamltool/diff.go index 58e8cea..499603e 100644 --- a/cmd/yamltool/diff.go +++ b/cmd/yamltool/diff.go @@ -45,7 +45,8 @@ func subtract(yaml2 yaml.MapSlice, yaml1 yaml.MapSlice) yaml.MapSlice { v1set[strval(v)] = true } s := make([]any, 0) - for k2, _ := range v2set { + for _, v2value := range v2.([]any) { + k2 := strval(v2value) if v1set[k2] { if VERBOSITY == 2 { s = append(s, "") @@ -77,8 +78,14 @@ func diff(cmd *cobra.Command, args []string) error { file1 := args[0] file2 := args[1] - yaml1 := parse(read(file1)) - yaml2 := parse(read(file2)) + yaml1, err := parse(read(file1)) + if err != nil { + panic(fmt.Errorf("%s: %w", file1, err)) + } + yaml2, err := parse(read(file2)) + if err != nil { + panic(fmt.Errorf("%s: %w", file2, err)) + } diff1 := subtract(yaml2, yaml1) diff2 := make(yaml.MapSlice, 0) diff --git a/cmd/yamltool/merge.go b/cmd/yamltool/merge.go index 2ceba7f..5211077 100644 --- a/cmd/yamltool/merge.go +++ b/cmd/yamltool/merge.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "github.com/goccy/go-yaml" "github.com/spf13/cobra" "os" @@ -53,7 +54,10 @@ func mergeMap(yaml1 yaml.MapSlice, yaml2 yaml.MapSlice) yaml.MapSlice { func merge(cmd *cobra.Command, args []string) error { res := make(yaml.MapSlice, 0) for _, arg := range args { - config := parse(read(arg)) + config, err := parse(read(arg)) + if err != nil { + return fmt.Errorf("%s: %w", arg, err) + } res = mergeMap(res, config) } encode(os.Stdout, res) diff --git a/cmd/yamltool/parse.go b/cmd/yamltool/parse.go index 08d8309..7c68331 100644 --- a/cmd/yamltool/parse.go +++ b/cmd/yamltool/parse.go @@ -14,13 +14,13 @@ func read(file string) []byte { return data } -func parse(data []byte) yaml.MapSlice { +func parse(data []byte) (yaml.MapSlice, error) { var result yaml.MapSlice decoder := yaml.NewDecoder(bytes.NewReader(data), yaml.UseOrderedMap()) err := decoder.Decode(&result) if err != nil { - panic(err) + return nil, err } - return result + return result, nil }