-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4024619
commit 4a4174a
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, "$")) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |