Skip to content

Commit

Permalink
add UpdateWithEnv func
Browse files Browse the repository at this point in the history
  • Loading branch information
dogancanbakir committed Aug 15, 2023
1 parent 4024619 commit 4a4174a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
15 changes: 15 additions & 0 deletions os/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package osutils

import (
"os"
"strings"
)

// UpdateWithEnv replaces a string variable with its corresponding environment variable value.
// If the environment variable does not exist, it remains unchanged.
func UpdateWithEnv(variable *string) {
if variable == nil {
return
}
*variable = os.Getenv(strings.TrimPrefix(*variable, "$"))
}
44 changes: 44 additions & 0 deletions os/env_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package osutils

import (
"os"
"testing"
)

func TestUpdateWithEnv(t *testing.T) {
testEnvVar := "TEST_VAR"
testEnvValue := "TestValue"
os.Setenv(testEnvVar, testEnvValue)
defer os.Unsetenv(testEnvVar)

tests := []struct {
input string
expected string
name string
}{
{"$" + testEnvVar, testEnvValue, "Existing env variable"},
{"$NON_EXISTENT_VAR", "", "Non-existent env variable"},
{"NOT_AN_ENV_VAR", "", "Not prefixed with $"},
{"", "", "Empty string"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
UpdateWithEnv(&tt.input)
if tt.input != tt.expected {
t.Errorf("got %q, want %q", tt.input, tt.expected)
}
})
}
}

func TestUpdateWithEnvNilInput(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Errorf("The code panicked with %v", r)
}
}()

var nilVar *string = nil
UpdateWithEnv(nilVar)
}

0 comments on commit 4a4174a

Please sign in to comment.