Skip to content

Commit

Permalink
fix: UseFieldNameByDefault when uppercased word in name
Browse files Browse the repository at this point in the history
closes #295

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
  • Loading branch information
caarlos0 committed Mar 16, 2024
1 parent 222a9ff commit 82542bd
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 13 deletions.
14 changes: 12 additions & 2 deletions env.go
Expand Up @@ -301,8 +301,18 @@ const underscore rune = '_'
func toEnvName(input string) string {
var output []rune
for i, c := range input {
if i > 0 && output[i-1] != underscore && c != underscore && unicode.ToUpper(c) == c {
output = append(output, underscore)
if c == underscore {
continue
}
if i > 0 && unicode.IsUpper(c) {
if len(input) > i+1 {
peek := rune(input[i+1])
if unicode.IsLower(peek) {
output = append(output, underscore)
}
} else {
output = append(output, underscore)

Check warning on line 314 in env.go

View check run for this annotation

Codecov / codecov/patch

env.go#L313-L314

Added lines #L313 - L314 were not covered by tests
}
}
output = append(output, unicode.ToUpper(c))
}
Expand Down
32 changes: 21 additions & 11 deletions env_test.go
Expand Up @@ -1742,32 +1742,42 @@ func TestComplePrefix(t *testing.T) {

func TestNoEnvKey(t *testing.T) {
type Config struct {
Foo string
FooBar string
bar string
Foo string
FooBar string
HTTPPort int
bar string
}
var cfg Config
isNoErr(t, ParseWithOptions(&cfg, Options{
UseFieldNameByDefault: true,
Environment: map[string]string{
"FOO": "fooval",
"FOO_BAR": "foobarval",
"FOO": "fooval",
"FOO_BAR": "foobarval",
"HTTP_PORT": "10",
},
}))
isEqual(t, "fooval", cfg.Foo)
isEqual(t, "foobarval", cfg.FooBar)
isEqual(t, 10, cfg.HTTPPort)
isEqual(t, "", cfg.bar)
}

func TestToEnv(t *testing.T) {
for in, out := range map[string]string{
"Foo": "FOO",
"FooBar": "FOO_BAR",
"fooBar": "FOO_BAR",
"Foo_Bar": "FOO_BAR",
"Foo__Bar": "FOO__BAR",
"Foo": "FOO",
"FooBar": "FOO_BAR",
"FOOBar": "FOO_BAR",
"Foo____Bar": "FOO_BAR",
"fooBar": "FOO_BAR",
"Foo_Bar": "FOO_BAR",
"Foo__Bar": "FOO_BAR",
"HTTPPort": "HTTP_PORT",
"SSHPort": "SSH_PORT",
"_SSH___Port_": "SSH_PORT",
} {
isEqual(t, out, toEnvName(in))
t.Run(in, func(t *testing.T) {
isEqual(t, out, toEnvName(in))
})
}
}

Expand Down

0 comments on commit 82542bd

Please sign in to comment.