goccy / go-yaml

YAML support for the Go language
MIT License
1.12k stars 129 forks source link

DisallowDuplicateKey doesn't fail if a child has duplicate keys #454

Open wjam opened 2 months ago

wjam commented 2 months ago

Describe the bug The yaml.DisallowDuplicateKey option only fails if a root element is duplicated. If a child of the root element is duplicated, then no error is returned when using yaml.DisallowDuplicateKey.

To Reproduce

Note the lack of an error returned by the second yaml.UnmarshalWithOptions call.

// You can edit this code!
// Click here and start typing.
package main

import (
    "fmt"

    "github.com/goccy/go-yaml"
)

func main() {
    var m map[string]any

    fmt.Println("Duplicate at root")
    err := yaml.UnmarshalWithOptions([]byte(`
top:
  child: 6
top:
  second: 2
`), &m, yaml.DisallowDuplicateKey())

    // err is returned here
    fmt.Println(err)
    fmt.Println(m)

    fmt.Println("Duplicate at child")
    err = yaml.UnmarshalWithOptions([]byte(`
top:
  child:
    value: 6
  child:
    second: 2
`), &m, yaml.DisallowDuplicateKey())

    // err is not returned here
    fmt.Println(err)
    fmt.Println(m)
}

https://go.dev/play/p/PK7-ExOkjBk

Expected behavior An error should be returned when using yaml.DisallowDuplicateKey when a key is duplicated regardless of whether the key is at the root or somewhere buried within the YAML document.

Screenshots Output from the program above

Duplicate at root
[4:1] duplicate key "top"
       2 | top:
       3 |   child: 6
    >  4 | top:
           ^
       5 |   second: 2
map[]
Duplicate at child
<nil>
map[top:map[child:map[second:2]]]

Program exited.

Version Variables

Additional context N/A