From 254a9c5c8a194d23f19c42f667bd2b28476cb407 Mon Sep 17 00:00:00 2001 From: AtomicFS Date: Wed, 8 Jan 2025 21:26:44 +0100 Subject: [PATCH] feat(action): add functions to help with passing env vars into container Signed-off-by: AtomicFS --- action/environment/environment.go | 23 ++++++++++ action/environment/environment_test.go | 62 ++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 action/environment/environment.go create mode 100644 action/environment/environment_test.go diff --git a/action/environment/environment.go b/action/environment/environment.go new file mode 100644 index 00000000..61219afe --- /dev/null +++ b/action/environment/environment.go @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT + +// Package environment for is interacting with environment variables +package environment + +import ( + "os" +) + +// FetchEnvVars when provided with list of environment variables is to +// return a map of variables and values for those that exist in the environment +func FetchEnvVars(variables []string) map[string]string { + result := make(map[string]string) + + for _, variable := range variables { + value, exists := os.LookupEnv(variable) + if exists { + result[variable] = value + } + } + + return result +} diff --git a/action/environment/environment_test.go b/action/environment/environment_test.go new file mode 100644 index 00000000..1de2fb1e --- /dev/null +++ b/action/environment/environment_test.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: MIT + +// Package environment +package environment + +import ( + "fmt" + "os" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestValidateConfig(t *testing.T) { + testCases := []struct { + name string + envCreate map[string]string + envSearchFor []string + envExpectedResult map[string]string + }{ + { + name: "no env vars created, no found", + envCreate: map[string]string{}, + envSearchFor: []string{"MY_VAR"}, + envExpectedResult: map[string]string{}, + }, + { + name: "one created, one found", + envCreate: map[string]string{ + "MY_VAR": "my_val", + }, + envSearchFor: []string{"MY_VAR"}, + envExpectedResult: map[string]string{ + "MY_VAR": "my_val", + }, + }, + { + name: "some created, some found", + envCreate: map[string]string{ + "MY_VAR": "my_val", + "MY_VAR2": "my_val2", + }, + envSearchFor: []string{"MY_VAR"}, + envExpectedResult: map[string]string{ + "MY_VAR": "my_val", + }, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + for key, value := range tc.envCreate { + os.Setenv(key, value) + defer os.Unsetenv(key) + fmt.Printf("Setting %s = %s\n", key, value) + } + + result := FetchEnvVars(tc.envSearchFor) + + assert.Equal(t, tc.envExpectedResult, result) + }) + } +}