From 3db11f27bcd3a2ee25da0e0f443e74dce1ad8e2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Miri=C4=87?= Date: Tue, 13 Dec 2022 17:39:22 +0100 Subject: [PATCH] Move some env helpers to lib We need these to be accessible from cmd/state as well. --- cmd/root.go | 16 ---------------- cmd/runtime_options.go | 2 +- lib/env.go | 22 ++++++++++++++++++++++ 3 files changed, 23 insertions(+), 17 deletions(-) create mode 100644 lib/env.go diff --git a/cmd/root.go b/cmd/root.go index 8a0738737567..1adda132ab70 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -150,22 +150,6 @@ func getFlags(defaultFlags globalFlags, env map[string]string) globalFlags { return result } -func parseEnvKeyValue(kv string) (string, string) { - if idx := strings.IndexRune(kv, '='); idx != -1 { - return kv[:idx], kv[idx+1:] - } - return kv, "" -} - -func buildEnvMap(environ []string) map[string]string { - env := make(map[string]string, len(environ)) - for _, kv := range environ { - k, v := parseEnvKeyValue(kv) - env[k] = v - } - return env -} - // This is to keep all fields needed for the main/root k6 command type rootCommand struct { globalState *globalState diff --git a/cmd/runtime_options.go b/cmd/runtime_options.go index 2a62afc80303..933d0dec5614 100644 --- a/cmd/runtime_options.go +++ b/cmd/runtime_options.go @@ -113,7 +113,7 @@ func getRuntimeOptions(flags *pflag.FlagSet, environment map[string]string) (lib return opts, err } for _, kv := range envVars { - k, v := parseEnvKeyValue(kv) + k, v := lib.ParseEnvKeyValue(kv) // Allow only alphanumeric ASCII variable names for now if !userEnvVarName.MatchString(k) { return opts, fmt.Errorf("invalid environment variable name '%s'", k) diff --git a/lib/env.go b/lib/env.go new file mode 100644 index 000000000000..a5484d7ae21d --- /dev/null +++ b/lib/env.go @@ -0,0 +1,22 @@ +package lib + +import "strings" + +// ParseEnvKeyValue splits an environment variable string into key and value. +func ParseEnvKeyValue(kv string) (string, string) { + if idx := strings.IndexRune(kv, '='); idx != -1 { + return kv[:idx], kv[idx+1:] + } + return kv, "" +} + +// BuildEnvMap returns a map from raw environment values, such as returned from +// os.Environ(). +func BuildEnvMap(environ []string) map[string]string { + env := make(map[string]string, len(environ)) + for _, kv := range environ { + k, v := ParseEnvKeyValue(kv) + env[k] = v + } + return env +}