From 9837240b6a5a7b6a68935374e330a9048c921f4e Mon Sep 17 00:00:00 2001 From: Laurent Demailly Date: Mon, 20 Nov 2023 21:14:42 -0800 Subject: [PATCH] Make the export line optional (will use in log help) --- env.go | 13 ++++++++----- env_test.go | 12 +++++++++--- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/env.go b/env.go index 3b568cc..f49295f 100644 --- a/env.go +++ b/env.go @@ -121,11 +121,12 @@ func (kv KeyValue) ToShell() string { } func ToShell(kvl []KeyValue) string { - return ToShellWithPrefix("", kvl) + return ToShellWithPrefix("", kvl, false /*don't skip export last line*/) } // This convert the key value pairs to bourne shell syntax (vs newer bash export FOO=bar). -func ToShellWithPrefix(prefix string, kvl []KeyValue) string { +// If skipExport is true the last line export VAR1 VAR2... is omitted. +func ToShellWithPrefix(prefix string, kvl []KeyValue, skipExport bool) string { var sb strings.Builder keys := make([]string, 0, len(kvl)) for _, kv := range kvl { @@ -134,9 +135,11 @@ func ToShellWithPrefix(prefix string, kvl []KeyValue) string { sb.WriteRune('\n') keys = append(keys, prefix+kv.Key) } - sb.WriteString("export ") - sb.WriteString(strings.Join(keys, " ")) - sb.WriteRune('\n') + if !skipExport { + sb.WriteString("export ") + sb.WriteString(strings.Join(keys, " ")) + sb.WriteRune('\n') + } return sb.String() } diff --git a/env_test.go b/env_test.go index 4727711..df41a40 100644 --- a/env_test.go +++ b/env_test.go @@ -158,8 +158,7 @@ func TestStructToEnvVars(t *testing.T) { if len(envVars) != 14 { t.Errorf("expected 14 env vars, got %d: %+v", len(envVars), envVars) } - str := ToShellWithPrefix("TST_", envVars) - //nolint:lll + str := ToShellWithPrefix("TST_", envVars, true) expected := `TST_FOO='a newline: foo with $X, ` + "`backticks`" + `, " quotes and \ and '\'' in middle and end '\''' TST_BAR='42str' @@ -175,8 +174,15 @@ TST_RECURSE_HERE_INNER_B='rec b' TST_SOME_BINARY='AAEC' TST_DUR=3600.1 TST_TS='1998-11-05T14:30:00Z' -export TST_FOO TST_BAR TST_A_SPECIAL_BLAH TST_A_BOOL TST_HTTP_SERVER TST_INT_POINTER TST_FLOAT_POINTER TST_INNER_A TST_INNER_B TST_RECURSE_HERE_INNER_A TST_RECURSE_HERE_INNER_B TST_SOME_BINARY TST_DUR TST_TS ` + if str != expected { + t.Errorf("\n---expected:---\n%s\n---got:---\n%s", expected, str) + } + // Again with export: + //nolint:lll + expected += `export TST_FOO TST_BAR TST_A_SPECIAL_BLAH TST_A_BOOL TST_HTTP_SERVER TST_INT_POINTER TST_FLOAT_POINTER TST_INNER_A TST_INNER_B TST_RECURSE_HERE_INNER_A TST_RECURSE_HERE_INNER_B TST_SOME_BINARY TST_DUR TST_TS +` + str = ToShellWithPrefix("TST_", envVars, false) if str != expected { t.Errorf("\n---expected:---\n%s\n---got:---\n%s", expected, str) }