kong icon indicating copy to clipboard operation
kong copied to clipboard

kong.JSON doesn't load camelCase values in embedded structs

Open jraby opened this issue 11 months ago • 0 comments

Hi,

I haven't dug into this much, but I was seeing some strange behavior when trying to load values from a json file when using embedded structs.

for some reason, camelCase keys in the json file do not get picked up when they are used in embedded structs.

The following testcase shows the problem:


func TestConfigReallyLoadsValues(t *testing.T) {
	type Level struct {
		Flag      string `json:"flag" required:""`
		WithSnake string `json:"with_snake,omitempty" required:""`
		WithCamel string `json:"withCamel,omitempty" required:""`
	}
	var cli struct {
		TopSnake string `json:"top_snake" required:""`
		TopCamel string `json:"topCamel" required:""`
		Level    `json:"level" prefix:"level." embed:""`
	}

	cli.TopCamel = "filled"
	cli.TopSnake = "filled"
	cli.Level.WithCamel = "filled"
	cli.Level.WithSnake = "filled"
	cli.Level.Flag = "filled"
	conf, cleanConf := makeConfig(t, &cli)
	defer cleanConf()

	b, err := os.ReadFile(conf)
	assert.NoError(t, err)
	log.Printf("data: %s", b)

	p := mustNew(t, &cli, kong.Configuration(kong.JSON, conf))
	_, err = p.Parse(nil)
	assert.NoError(t, err)
}
=== RUN   TestConfigFlag
--- PASS: TestConfigFlag (0.00s)
=== RUN   TestConfigValidation
--- PASS: TestConfigValidation (0.00s)
=== RUN   TestConfigReallyLoadsValues
2025/01/21 22:51:11 data: {"top_snake":"filled","topCamel":"filled","level":{"flag":"filled","with_snake":"filled","withCamel":"filled"}}
    config_test.go:72: Did not expect an error but got:
        missing flags: --level.with-camel=STRING
--- FAIL: TestConfigReallyLoadsValues (0.00s)
FAIL
FAIL    github.com/alecthomas/kong      0.003s
FAIL

Top level keys expressed as snake or camel are properly parsed, but for the embedded struct, only the snake case version is picked up.

jraby avatar Jan 22 '25 03:01 jraby