Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Add option (e.g. ZeroAsNull) to treat zero values equal to missing property (similiar to EmptyAsNull) #30

Closed
dionysius opened this issue Nov 23, 2022 · 1 comment

Comments

@dionysius
Copy link
Contributor

Test case:

package main

import (
	"testing"

	"github.com/sters/yaml-diff/yamldiff"
	"gopkg.in/yaml.v3"
)

var yaml1 = `
intA: 2
intB: 0
intC: 0
strA: foo
strB: ""
strC: ""
`

type MyType struct {
	IntA int    `yaml:"intA"`
	IntB int    `yaml:"intB"`
	IntC int    `yaml:"intC,omitempty"`
	StrA string `yaml:"strA"`
	StrB string `yaml:"strB"`
	StrC string `yaml:"strC,omitempty"`
}

func Test_YamlDiff_Omitempty(t *testing.T) {
	t.Parallel()

	yaml1Source, err := yamldiff.Load(yaml1)
	if err != nil {
		t.Error(err)
	}

	mytype := &MyType{}

	err = yaml.Unmarshal([]byte(yaml1), mytype)
	if err != nil {
		t.Error(err)
	}

	bYaml2, err := yaml.Marshal(mytype)
	if err != nil {
		t.Error(err)
	}

	yaml2 := string(bYaml2)

	yaml2Source, err := yamldiff.Load(yaml2)
	if err != nil {
		t.Error(err)
	}

	diffs := yamldiff.Do(yaml1Source, yaml2Source, yamldiff.EmptyAsNull())
	if len(diffs) > 0 {
		for _, diff := range diffs {
			if diff.Status() != yamldiff.DiffStatusSame {
				t.Log("diff detected\n" + diff.Dump())
				t.Fail()
			}
		}
	}
}

Test Result:

--- FAIL: Test_YamlDiff_Omitempty (0.00s)
    .../main_test.go:59: diff detected
          intA: 2
          intB: 0
        - intC: 0
          strA: "foo"
          strB: ""
        - strC: ""

If one of the diff sources contains a zero value for a property and the other has this property missing a diff will be found. This makes sense by default.

Kubernetes generates optional fields with omitempty tag (just looked up a random string property). So once a yaml is produced by kubernetes (e.g. kubectl), such output will have those properties missing. It's sometimes intentional by (because $reason) , that the other diff source has this property always set, even if set to zero.

@dionysius
Copy link
Contributor Author

Offered you a PR #31 for this issue. Please have a look and review

@sters sters closed this as completed in f440c3a Jan 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant