preserving ordering in arrays.

This commit is contained in:
Erik Brakkee 2025-01-10 19:38:43 +01:00
parent 56844a3c24
commit ef0ef6e215
3 changed files with 18 additions and 7 deletions

View File

@ -45,7 +45,8 @@ func subtract(yaml2 yaml.MapSlice, yaml1 yaml.MapSlice) yaml.MapSlice {
v1set[strval(v)] = true v1set[strval(v)] = true
} }
s := make([]any, 0) s := make([]any, 0)
for k2, _ := range v2set { for _, v2value := range v2.([]any) {
k2 := strval(v2value)
if v1set[k2] { if v1set[k2] {
if VERBOSITY == 2 { if VERBOSITY == 2 {
s = append(s, "<UNMODIFIED>") s = append(s, "<UNMODIFIED>")
@ -77,8 +78,14 @@ func diff(cmd *cobra.Command, args []string) error {
file1 := args[0] file1 := args[0]
file2 := args[1] file2 := args[1]
yaml1 := parse(read(file1)) yaml1, err := parse(read(file1))
yaml2 := parse(read(file2)) 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) diff1 := subtract(yaml2, yaml1)
diff2 := make(yaml.MapSlice, 0) diff2 := make(yaml.MapSlice, 0)

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"fmt"
"github.com/goccy/go-yaml" "github.com/goccy/go-yaml"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"os" "os"
@ -53,7 +54,10 @@ func mergeMap(yaml1 yaml.MapSlice, yaml2 yaml.MapSlice) yaml.MapSlice {
func merge(cmd *cobra.Command, args []string) error { func merge(cmd *cobra.Command, args []string) error {
res := make(yaml.MapSlice, 0) res := make(yaml.MapSlice, 0)
for _, arg := range args { 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) res = mergeMap(res, config)
} }
encode(os.Stdout, res) encode(os.Stdout, res)

View File

@ -14,13 +14,13 @@ func read(file string) []byte {
return data return data
} }
func parse(data []byte) yaml.MapSlice { func parse(data []byte) (yaml.MapSlice, error) {
var result yaml.MapSlice var result yaml.MapSlice
decoder := yaml.NewDecoder(bytes.NewReader(data), decoder := yaml.NewDecoder(bytes.NewReader(data),
yaml.UseOrderedMap()) yaml.UseOrderedMap())
err := decoder.Decode(&result) err := decoder.Decode(&result)
if err != nil { if err != nil {
panic(err) return nil, err
} }
return result return result, nil
} }