cleanenv icon indicating copy to clipboard operation
cleanenv copied to clipboard

Default Values on Nested Structs

Open hundredwatt opened this issue 4 years ago • 6 comments

I am attempting to use cleanenv with a nested struct and the env-default tag is not being applied on the child struct.

Is this something cleanenv could support?

Here's a test case replicating the issue:

func TestNestedStructsParseFileEnv(t *testing.T) {
	type child struct {
		Number        int64 `yaml:"number"`
		DefaultNumber int64 `yaml:"default_number" env-defult:"-1"`
	}

	type parent struct {
		Children map[string]child `yaml:"children"`
	}

	children := make(map[string]child)
	children["first"] = child{1, -1}
	wantConfig := parent{children}

	tests := []struct {
		name    string
		file    string
		ext     string
		want    *parent
		wantErr bool
	}{
		{
			name: "yaml",
			file: `
children: 
  first:
    number: 1`,
			ext:     "yaml",
			want:    &wantConfig,
			wantErr: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tmpFile, err := ioutil.TempFile(os.TempDir(), fmt.Sprintf("*.%s", tt.ext))
			if err != nil {
				t.Fatal("cannot create temporary file:", err)
			}
			defer os.Remove(tmpFile.Name())

			text := []byte(tt.file)
			if _, err = tmpFile.Write(text); err != nil {
				t.Fatal("failed to write to temporary file:", err)
			}

			var prnt parent
			if err = ReadConfig(tmpFile.Name(), &prnt); (err != nil) != tt.wantErr {
				t.Errorf("wrong error behavior %v, wantErr %v", err, tt.wantErr)
			}
			if err == nil && !reflect.DeepEqual(&prnt, tt.want) {
				t.Errorf("wrong data %v, want %v", &prnt, tt.want)
			}
		})
	}

}

hundredwatt avatar Jun 12 '20 15:06 hundredwatt

It seems that the default processing logic for nested maps has not yet been implemented. Thank you for finding this error.

ilyakaznacheev avatar Jun 15 '20 06:06 ilyakaznacheev

@ilyakaznacheev do u have time to implement this or you can assign me

abakermi avatar Jul 24 '20 13:07 abakermi

@abakermi go ahead, if you have ideas how to fix that, please send a PR :)

ilyakaznacheev avatar Jul 24 '20 15:07 ilyakaznacheev

sure, thanks !

abakermi avatar Jul 24 '20 15:07 abakermi

Unassigned due to inactivity

ilyakaznacheev avatar Oct 19 '20 09:10 ilyakaznacheev

This applies for all tags as far as I can tell, for example env-required does not validate on nested structs either. Logical but worth pointing out I felt, love the library by the way.

Dombo avatar Jan 25 '21 20:01 Dombo