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

Tag rename missing is encoding #318

Open
jsumners opened this issue Dec 23, 2022 · 0 comments
Open

Tag rename missing is encoding #318

jsumners opened this issue Dec 23, 2022 · 0 comments

Comments

@jsumners
Copy link

If I'm not mistaken, the main.go below should output:

sub_config:
    first_children:
        - name: parent
          grand_children:
            - name: foo
            - name: bar

Instead, it is outputting:

sub_config:
    first_children:
        - name: parent
          children:
            - name: foo
            - name: bar

Notice that the second slice is intended to be named grand_children but is really being named children as it is actually named in the struct.

If I step through the mapstructure.Decode function, I can see the tag get read and build an appropriate fieldName as sub_config.first_children[0].grand_children, but that at some point gets shuffled back to children.

We can see in this screenshot the result of the Decode prior to rendering the yaml:
image

main.go
package main

import (
	"fmt"
	"os"

	"github.com/mitchellh/mapstructure"
	"gopkg.in/yaml.v3"
)

type Config struct {
	Subconfig SubSection `mapstructure:"sub_config"`
}

type SubSection struct {
	Children []Child `mapstructure:"first_children"`
}

type Child struct {
	Name     string
	Children []Grandchild `mapstructure:"grand_children"`
}

type Grandchild struct {
	Name string
}

func main() {
	config := &Config{
		Subconfig: SubSection{
			Children: []Child{
				{Name: "parent", Children: []Grandchild{
					{Name: "foo"},
					{Name: "bar"},
				}},
			},
		},
	}

	encodedData := map[string]interface{}{}
	err := mapstructure.Decode(config, &encodedData)
	if err != nil {
		err = fmt.Errorf("unable to encode configuration: %w", err)
		fmt.Println(err)
		os.Exit(1)
	}

	data, err := yaml.Marshal(encodedData)
	if err != nil {
		err = fmt.Errorf("unable to marshal to yaml: %w", err)
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(string(data))
}
go.mod
module foo

go 1.19

require (
	github.com/mitchellh/mapstructure v1.5.0 // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
)
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