Skip to content

Commit

Permalink
Make the export line optional (will use in log help)
Browse files Browse the repository at this point in the history
  • Loading branch information
ldemailly committed Nov 21, 2023
1 parent 2ec9f37 commit 9837240
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
13 changes: 8 additions & 5 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -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*/)

Check warning on line 124 in env.go

View check run for this annotation

Codecov / codecov/patch

env.go#L124

Added line #L124 was not covered by tests
}

// 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 {
Expand All @@ -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()
}

Expand Down
12 changes: 9 additions & 3 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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)
}
Expand Down

0 comments on commit 9837240

Please sign in to comment.