Skip to content

Commit c5e779a

Browse files
author
Jose Diaz-Gonzalez
committed
feat: add support for exported bash functions
1 parent 79de8ba commit c5e779a

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

basher.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
package basher
33

44
import (
5+
"fmt"
56
"io"
67
"io/ioutil"
78
"log"
@@ -223,6 +224,14 @@ func (c *Context) buildEnvfile() (string, error) {
223224
continue
224225
}
225226

227+
if isBashFunc(pair[0], pair[1]) {
228+
bash_function_name := strings.TrimPrefix(pair[0], "BASH_FUNC_")
229+
bash_function_name = strings.TrimSuffix(bash_function_name, "%%")
230+
file.Write([]byte(fmt.Sprintf("%s%s\n", bash_function_name, pair[1])))
231+
file.Write([]byte(fmt.Sprintf("export -f %s\n", bash_function_name)))
232+
continue
233+
}
234+
226235
file.Write([]byte("export " + strings.Replace(
227236
strings.Replace(kvp, "'", "\\'", -1), "=", "=$'", 1) + "'\n"))
228237
}
@@ -237,6 +246,10 @@ func (c *Context) buildEnvfile() (string, error) {
237246
return file.Name(), nil
238247
}
239248

249+
func isBashFunc(key string, value string) bool {
250+
return strings.HasPrefix(key, "BASH_FUNC_") && strings.HasPrefix(value, "()")
251+
}
252+
240253
// Runs a command in Bash from this Context. With each call, a temporary file
241254
// is generated used as BASH_ENV when calling Bash that includes all variables,
242255
// sourced scripts, and exported functions from the Context. Standard I/O by

basher_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,24 @@ func TestOddArgs(t *testing.T) {
138138
t.Fatal("unexpected stdout:", stdout.String())
139139
}
140140
}
141+
142+
func TestIsBashFunc(t *testing.T) {
143+
if isBashFunc("", "") {
144+
t.Fatal("empty string is not a bash func")
145+
}
146+
147+
if isBashFunc("key", "value") {
148+
t.Fatal("key=value is not a bash func")
149+
}
150+
151+
if isBashFunc("BASH_FUNC_readlinkf", "value") {
152+
t.Fatal("key does not end with %%")
153+
}
154+
155+
if isBashFunc("BASH_FUNC_readlinkf%%", "value") {
156+
t.Fatal("value does not begin with ()")
157+
}
158+
if !isBashFunc("BASH_FUNC_readlinkf%%", "() { true }") {
159+
t.Fatal("bash func should be detected")
160+
}
161+
}

0 commit comments

Comments
 (0)