Skip to content

Commit 03aa9fa

Browse files
authored
fix: update env var to allow empty string (#1260)
Update configuration file capability of reading from environment variable: * allow default empty string * fix if statement to check if `parts[2]` is empty instead since it will always have a length of 4. * add unit tests.
1 parent 1a6dfe8 commit 03aa9fa

File tree

2 files changed

+68
-2
lines changed

2 files changed

+68
-2
lines changed

cmd/root.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ type ToolsFile struct {
267267
// parseEnv replaces environment variables ${ENV_NAME} with their values.
268268
// also support ${ENV_NAME:default_value}.
269269
func parseEnv(input string) (string, error) {
270-
re := regexp.MustCompile(`\$\{(\w+)(:(\w+))?\}`)
270+
re := regexp.MustCompile(`\$\{(\w+)(:(\w*))?\}`)
271271

272272
var err error
273273
output := re.ReplaceAllStringFunc(input, func(match string) string {
@@ -278,7 +278,7 @@ func parseEnv(input string) (string, error) {
278278
if value, found := os.LookupEnv(variableName); found {
279279
return value
280280
}
281-
if len(parts) == 4 {
281+
if parts[2] != "" {
282282
return parts[3]
283283
}
284284
err = fmt.Errorf("environment variable not found: %q", variableName)

cmd/root_test.go

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,72 @@ func TestServerConfigFlags(t *testing.T) {
206206
}
207207
}
208208

209+
func TestParseEnv(t *testing.T) {
210+
tcs := []struct {
211+
desc string
212+
env map[string]string
213+
in string
214+
want string
215+
err bool
216+
errString string
217+
}{
218+
{
219+
desc: "without default without env",
220+
in: "${FOO}",
221+
want: "",
222+
err: true,
223+
errString: `environment variable not found: "FOO"`,
224+
},
225+
{
226+
desc: "without default with env",
227+
env: map[string]string{
228+
"FOO": "bar",
229+
},
230+
in: "${FOO}",
231+
want: "bar",
232+
},
233+
{
234+
desc: "with empty default",
235+
in: "${FOO:}",
236+
want: "",
237+
},
238+
{
239+
desc: "with default",
240+
in: "${FOO:bar}",
241+
want: "bar",
242+
},
243+
{
244+
desc: "with default with env",
245+
env: map[string]string{
246+
"FOO": "hello",
247+
},
248+
in: "${FOO:bar}",
249+
want: "hello",
250+
},
251+
}
252+
for _, tc := range tcs {
253+
t.Run(tc.desc, func(t *testing.T) {
254+
if tc.env != nil {
255+
for k, v := range tc.env {
256+
t.Setenv(k, v)
257+
}
258+
}
259+
got, err := parseEnv(tc.in)
260+
if tc.err {
261+
if err == nil {
262+
t.Fatalf("expected error not found")
263+
}
264+
if tc.errString != err.Error() {
265+
t.Fatalf("incorrect error string: got %s, want %s", err, tc.errString)
266+
}
267+
}
268+
if tc.want != got {
269+
t.Fatalf("unexpected want: got %s, want %s", got, tc.want)
270+
}
271+
})
272+
}
273+
}
274+
209275
func TestToolFileFlag(t *testing.T) {
210276
tcs := []struct {
211277
desc string

0 commit comments

Comments
 (0)