Skip to content

Commit

Permalink
feat: support ignored value "-" for env tag (#338)
Browse files Browse the repository at this point in the history
* feat: support ignored value "-" for env tag

* fix test
  • Loading branch information
sv-kozlov authored Oct 11, 2024
1 parent 1cb1967 commit 4ab8b37
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
8 changes: 8 additions & 0 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,10 @@ func doParseField(
return err
}

if params.Ignored {
return nil
}

if err := processField(refField, refTypeField, opts, params); err != nil {
return err
}
Expand Down Expand Up @@ -533,6 +537,7 @@ type FieldParams struct {
NotEmpty bool
Expand bool
Init bool
Ignored bool
}

func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, error) {
Expand All @@ -549,6 +554,7 @@ func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, err
Required: opts.RequiredIfNoDef,
DefaultValue: defaultValue,
HasDefaultValue: hasDefaultValue,
Ignored: ownKey == "-",
}

for _, tag := range tags {
Expand All @@ -567,6 +573,8 @@ func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, err
result.Expand = true
case "init":
result.Init = true
case "-":
result.Ignored = true
default:
return FieldParams{}, newNoSupportedTagOptionError(tag)
}
Expand Down
40 changes: 40 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2214,3 +2214,43 @@ func TestParseWithOptionsRenamedPrefix(t *testing.T) {
isNoErr(t, Parse(cfg))
isEqual(t, "101", cfg.Foo.Str)
}

func TestFieldIgnored(t *testing.T) {
type Test struct {
Foo string `env:"FOO"`
Bar string `env:"BAR,-"`
}
type ComplexConfig struct {
Str string `env:"STR"`
Foo Test `env:"FOO" envPrefix:"FOO_"`
Bar Test `env:"-" envPrefix:"BAR_"`
}
t.Setenv("STR", "101")
t.Setenv("FOO_FOO", "202")
t.Setenv("FOO_BAR", "303")
t.Setenv("BAR_FOO", "404")
t.Setenv("BAR_BAR", "505")

var cfg ComplexConfig
isNoErr(t, Parse(&cfg))
isEqual(t, "101", cfg.Str)
isEqual(t, "202", cfg.Foo.Foo)
isEqual(t, "", cfg.Foo.Bar)
isEqual(t, "", cfg.Bar.Foo)
isEqual(t, "", cfg.Bar.Bar)
}

func TestNoEnvKeyIgnored(t *testing.T) {
type Config struct {
Foo string `env:"-"`
FooBar string
}

t.Setenv("FOO", "101")
t.Setenv("FOO_BAR", "202")

var cfg Config
isNoErr(t, ParseWithOptions(&cfg, Options{UseFieldNameByDefault: true}))
isEqual(t, "", cfg.Foo)
isEqual(t, "202", cfg.FooBar)
}

0 comments on commit 4ab8b37

Please sign in to comment.