Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: UseFieldNameByDefault when uppercased word in name #297

Merged
merged 1 commit into from
Mar 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,16 @@ 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 len(output) > 0 && unicode.IsUpper(c) {
if len(input) > i+1 {
peek := rune(input[i+1])
if unicode.IsLower(peek) || unicode.IsLower(rune(input[i-1])) {
output = append(output, underscore)
}
}
}
output = append(output, unicode.ToUpper(c))
}
Expand Down
33 changes: 22 additions & 11 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1742,32 +1742,43 @@ 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",
"_PortHTTP": "PORT_HTTP",
} {
isEqual(t, out, toEnvName(in))
t.Run(in, func(t *testing.T) {
isEqual(t, out, toEnvName(in))
})
}
}

Expand Down
Loading