Skip to content

Commit

Permalink
skip name (#85)
Browse files Browse the repository at this point in the history
Signed-off-by: Oleg Kovalov <[email protected]>
  • Loading branch information
cristaloleg committed May 26, 2021
1 parent 0e82ea0 commit 3c6d2c0
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
12 changes: 12 additions & 0 deletions aconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ func (l *Loader) init() {
if !l.config.SkipFlags {
for _, field := range l.fields {
flagName := l.fullTag(l.config.FlagPrefix, field, flagNameTag)
if flagName == "" {
continue
}
l.flagSet.String(flagName, field.Tag(defaultValueTag), field.Tag(usageTag))
}
}
Expand Down Expand Up @@ -298,6 +301,9 @@ func (l *Loader) loadFile(file string) error {

for _, field := range l.fields {
name := l.fullTag("", field, tag)
if name == "" {
continue
}
value, ok := actualFields[name]
if !ok {
actualFields = find(actualFields, name)
Expand Down Expand Up @@ -346,6 +352,9 @@ func (l *Loader) loadEnvironment() error {

for _, field := range l.fields {
envName := l.fullTag(l.config.EnvPrefix, field, envNameTag)
if envName == "" {
continue
}

if err := l.setField(field, envName, actualEnvs); err != nil {
return err
Expand All @@ -367,6 +376,9 @@ func (l *Loader) loadFlags() error {

for _, field := range l.fields {
flagName := l.fullTag(l.config.FlagPrefix, field, flagNameTag)
if flagName == "" {
continue
}

if err := l.setField(field, flagName, actualFlags); err != nil {
return err
Expand Down
34 changes: 34 additions & 0 deletions aconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,40 @@ func TestExactName(t *testing.T) {
}
}

func TestSkipName(t *testing.T) {
setEnv(t, "STR", "str-env")
setEnv(t, "BAR", "bar-env")
defer os.Clearenv()

type Foo struct {
String string `env:"STR"`
}
type ExactConfig struct {
Foo Foo `env:"-"`
Bar string `default:"def" env:"-"`
}
var cfg ExactConfig

loader := LoaderFor(&cfg, Config{
SkipFiles: true,
SkipFlags: true,
})
if err := loader.Load(); err != nil {
t.Fatal(err)
}

want := ExactConfig{
Foo: Foo{
String: "str-env",
},
Bar: "def",
}

if got := cfg; !reflect.DeepEqual(want, got) {
t.Fatalf("want %v, got %v", want, got)
}
}

func TestUsage(t *testing.T) {
loader := LoaderFor(&EmbeddedConfig{}, Config{})

Expand Down
7 changes: 6 additions & 1 deletion reflection.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,16 @@ func (l *Loader) fullTag(prefix string, f *fieldData, tag string) string {
sep = l.config.envDelimiter
}
res := f.Tag(tag)
if res == "-" {
return ""
}
if before, _, ok := cut(res, ",exact"); ok {
return before
}
for p := f.parent; p != nil; p = p.parent {
res = p.Tag(tag) + sep + res
if p.Tag(tag) != "-" {
res = p.Tag(tag) + sep + res
}
}
return prefix + res
}
Expand Down

0 comments on commit 3c6d2c0

Please sign in to comment.