Skip to content

Commit

Permalink
Handle comparisons of boolean values correctly
Browse files Browse the repository at this point in the history
Add special logic to ensure that the various supported boolean value
representations are treated the same. Closes #334
  • Loading branch information
nresare authored and HeavyWombat committed Jan 14, 2024
1 parent 880c050 commit b52929f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/dyff/compare_test.go
Expand Up @@ -88,6 +88,16 @@ some:
Expect(result[0]).To(BeSameDiffAs(singleDiff("/some/yaml/structure/name", dyff.MODIFICATION, 1, 2)))
})

It("should return that different representations of true are treated as the same", func() {
from := yml("---\nkey: true")

to := yml("---\nkey: True")

result, err := compare(from, to)
Expect(err).To(BeNil())
Expect(result).To(BeNil())
})

It("should return that a float was modified", func() {
from := yml(`---
some:
Expand Down
45 changes: 45 additions & 0 deletions pkg/dyff/core.go
Expand Up @@ -212,6 +212,9 @@ func (compare *compare) nonNilSameKindNodes(path ytbx.Path, from *yamlv3.Node, t
case "!!null":
// Ignore different ways to define a null value

case "!!bool":
diffs, err = compare.boolValues(path, from, to)

default:
if from.Value != to.Value {
diffs, err = []Diff{{
Expand Down Expand Up @@ -607,6 +610,48 @@ func (compare *compare) nodeValues(path ytbx.Path, from *yamlv3.Node, to *yamlv3
return result, nil
}

func (compare *compare) boolValues(path ytbx.Path, from *yamlv3.Node, to *yamlv3.Node) ([]Diff, error) {
boolFrom, err := toBool(from.Value)
if err != nil {
return nil, err
}
boolTo, err := toBool(to.Value)
if err != nil {
return nil, err
}
result := make([]Diff, 0)
if boolFrom != boolTo {
result = append(result, Diff{
&path,
[]Detail{{
Kind: MODIFICATION,
From: from,
To: to,
}},
})
}

return result, nil
}

// this uses the various values mentioned in https://yaml.org/type/bool.html
var trueValues = [...]string{"y", "Y", "yes", "Yes", "YES", "true", "True", "TRUE", "on", "On", "ON"}
var falseValues = [...]string{"n", "N", "no", "No", "NO", "false", "False", "FALSE", "off", "Off", "OFF"}

func toBool(input string) (bool, error) {
for _, t := range trueValues {
if input == t {
return true, nil
}
}
for _, f := range falseValues {
if input == f {
return false, nil
}
}
return false, fmt.Errorf("not a valid boolean value: '%s'", input)
}

func (compare *compare) findOrderChangesInSimpleList(fromCommon, toCommon []*yamlv3.Node) []Detail {
// Try to find order changes ...
if len(fromCommon) == len(toCommon) {
Expand Down

0 comments on commit b52929f

Please sign in to comment.