Skip to content

Commit

Permalink
fix: invalid environment variable (#271)
Browse files Browse the repository at this point in the history
* fix: invalid environment variable

Check the validity of environment variables when splitting variables by `=`. Ignore environment variables that don't include an `=` sign.

Signed-off-by: Ayman Bagabas <ayman.bagabas@gmail.com>

* Update env_tomap_windows.go

* Update env_tomap_windows_test.go

---------

Signed-off-by: Ayman Bagabas <ayman.bagabas@gmail.com>
  • Loading branch information
aymanbagabas committed Jun 28, 2023
1 parent 7a25c17 commit 0f07b7f
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 4 deletions.
4 changes: 3 additions & 1 deletion env_tomap.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ func toMap(env []string) map[string]string {
r := map[string]string{}
for _, e := range env {
p := strings.SplitN(e, "=", 2)
r[p[0]] = p[1]
if len(p) == 2 {
r[p[0]] = p[1]
}
}
return r
}
3 changes: 2 additions & 1 deletion env_tomap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ package env
import "testing"

func TestUnix(t *testing.T) {
envVars := []string{":=/test/unix", "PATH=:/test_val1:/test_val2", "VAR=REGULARVAR"}
envVars := []string{":=/test/unix", "PATH=:/test_val1:/test_val2", "VAR=REGULARVAR", "FOO=", "BAR"}
result := toMap(envVars)
isEqual(t, map[string]string{
":": "/test/unix",
"PATH": ":/test_val1:/test_val2",
"VAR": "REGULARVAR",
"FOO": "",
}, result)
}
4 changes: 3 additions & 1 deletion env_tomap_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ func toMap(env []string) map[string]string {
p[0] = "=" + p[0]
}

r[p[0]] = p[1]
if len(p) == 2 {
r[p[0]] = p[1]
}
}
return r
}
3 changes: 2 additions & 1 deletion env_tomap_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import "testing"
// On Windows, environment variables can start with '='. This test verifies this behavior without relying on a Windows environment.
// See env_windows.go in the Go source: https://github.com/golang/go/blob/master/src/syscall/env_windows.go#L58
func TestToMapWindows(t *testing.T) {
envVars := []string{"=::=::\\", "=C:=C:\\test", "VAR=REGULARVAR"}
envVars := []string{"=::=::\\", "=C:=C:\\test", "VAR=REGULARVAR", "FOO=", "BAR"}
result := toMap(envVars)
isEqual(t, map[string]string{
"=::": "::\\",
"=C:": "C:\\test",
"VAR": "REGULARVAR",
"FOO": "",
}, result)
}

0 comments on commit 0f07b7f

Please sign in to comment.