diff options
-rw-r--r-- | src/os/env.go | 5 | ||||
-rw-r--r-- | src/os/env_test.go | 28 | ||||
-rw-r--r-- | src/syscall/syscall_libc.go | 11 | ||||
-rw-r--r-- | src/syscall/syscall_nonhosted.go | 5 |
4 files changed, 49 insertions, 0 deletions
diff --git a/src/os/env.go b/src/os/env.go index f232e1b45..3698e07ea 100644 --- a/src/os/env.go +++ b/src/os/env.go @@ -25,6 +25,11 @@ func Unsetenv(key string) error { return nil } +// Clearenv deletes all environment variables. +func Clearenv() { + syscall.Clearenv() +} + func LookupEnv(key string) (string, bool) { return syscall.Getenv(key) } diff --git a/src/os/env_test.go b/src/os/env_test.go index d2879c34f..feec0c873 100644 --- a/src/os/env_test.go +++ b/src/os/env_test.go @@ -46,6 +46,34 @@ func TestUnsetenv(t *testing.T) { } } +func TestClearenv(t *testing.T) { + const testKey = "GO_TEST_CLEARENV" + const testValue = "1" + + // reset env + defer func(origEnv []string) { + for _, pair := range origEnv { + // Environment variables on Windows can begin with = + // https://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx + i := strings.Index(pair[1:], "=") + 1 + if err := Setenv(pair[:i], pair[i+1:]); err != nil { + t.Errorf("Setenv(%q, %q) failed during reset: %v", pair[:i], pair[i+1:], err) + } + } + }(Environ()) + + if err := Setenv(testKey, testValue); err != nil { + t.Fatalf("Setenv(%q, %q) failed: %v", testKey, testValue, err) + } + if _, ok := LookupEnv(testKey); !ok { + t.Errorf("Setenv(%q, %q) didn't set $%s", testKey, testValue, testKey) + } + Clearenv() + if val, ok := LookupEnv(testKey); ok { + t.Errorf("Clearenv() didn't clear $%s, remained with value %q", testKey, val) + } +} + func TestLookupEnv(t *testing.T) { const smallpox = "SMALLPOX" // No one has smallpox. value, ok := LookupEnv(smallpox) // Should not exist. diff --git a/src/syscall/syscall_libc.go b/src/syscall/syscall_libc.go index 05df16fd7..25c778650 100644 --- a/src/syscall/syscall_libc.go +++ b/src/syscall/syscall_libc.go @@ -151,6 +151,17 @@ func Unsetenv(key string) (err error) { return } +func Clearenv() { + for _, s := range Environ() { + for j := 0; j < len(s); j++ { + if s[j] == '=' { + Unsetenv(s[0:j]) + break + } + } + } +} + func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { addr := libc_mmap(nil, uintptr(length), int32(prot), int32(flags), int32(fd), uintptr(offset)) if addr == unsafe.Pointer(^uintptr(0)) { diff --git a/src/syscall/syscall_nonhosted.go b/src/syscall/syscall_nonhosted.go index 9e5b70fdc..be1b32c7b 100644 --- a/src/syscall/syscall_nonhosted.go +++ b/src/syscall/syscall_nonhosted.go @@ -77,6 +77,11 @@ func Unsetenv(key string) (err error) { return ENOSYS } +func Clearenv() (err error) { + // stub for now + return ENOSYS +} + func Environ() []string { env := runtime_envs() envCopy := make([]string, len(env)) |