Skip to content

Commit

Permalink
Auto-skip: improved shell expression parsing (#3514)
Browse files Browse the repository at this point in the history
A minor improvement over the previous string contents check.
  • Loading branch information
mikejholly authored Nov 21, 2023
1 parent ae42b03 commit 50b4a20
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
24 changes: 23 additions & 1 deletion inputgraph/loader.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package inputgraph

import (
"bufio"
"context"
"fmt"
"os"
Expand Down Expand Up @@ -145,7 +146,28 @@ func (l *loader) handleCopy(ctx context.Context, cmd spec.Command) error {
}

func containsShellExpr(s string) bool {
return strings.Contains(s, "$(") && strings.Contains(s, ")")
var (
last string
depth int
hasExpr bool
)
scan := bufio.NewScanner(strings.NewReader(s))
scan.Split(bufio.ScanRunes)
for scan.Scan() {
c := scan.Text()
switch {
case c == "(" && last == "$":
hasExpr = true
depth++
case c == ")":
depth--
}
if depth < 0 {
return false
}
last = c
}
return depth == 0 && hasExpr
}

func (l *loader) handleCopySrc(ctx context.Context, src string, mustExist bool) error {
Expand Down
43 changes: 43 additions & 0 deletions inputgraph/loader_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package inputgraph

import (
"testing"

"github.com/stretchr/testify/require"
)

func Test_containsShellExpr(t *testing.T) {
cases := []struct {
desc string
val string
want bool
}{
{
desc: "single",
val: "$(echo 'hello')",
want: true,
},
{
desc: "nested",
val: "$(echo -n $(cat /tmp/x))",
want: true,
},
{
desc: "invalid 1",
val: "$($()",
want: false,
},
{
desc: "invalid 2",
val: ")$(",
want: false,
},
}

for _, c := range cases {
t.Run(c.desc, func(t *testing.T) {
got := containsShellExpr(c.val)
require.Equal(t, c.want, got)
})
}
}

0 comments on commit 50b4a20

Please sign in to comment.