Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions internal/templater/glob_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package templater

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/go-task/task/v3/taskfile/ast"
)

func TestReplaceGlobsKeepsUnresolvedDynamicVariables(t *testing.T) {
t.Parallel()

dynamic := "echo parent"
vars := ast.NewVars()
vars.Set("PARENT", ast.Var{Sh: &dynamic})
vars.Set("STATIC", ast.Var{Value: "parent"})

globs := ReplaceGlobs([]*ast.Glob{
{Glob: "{{.PARENT}}/**/*"},
{Glob: "{{.STATIC}}/**/*"},
}, &Cache{Vars: vars})

require.Len(t, globs, 2)
// An unevaluated shell variable must keep its placeholder. Replacing it with
// an empty string produces "/**/*", which makes the globber traverse the
// filesystem root and can hang on symlink cycles.
require.Equal(t, "{{.PARENT}}/**/*", globs[0].Glob)
require.Equal(t, "parent/**/*", globs[1].Glob)
}
28 changes: 27 additions & 1 deletion internal/templater/templater.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"maps"
"regexp"
"strings"

"github.com/go-task/template"
Expand Down Expand Up @@ -111,15 +112,40 @@ func ReplaceWithExtra[T any](v T, cache *Cache, extra map[string]any) T {
return copy
}

// globVarPattern matches direct variable lookups in a glob pattern.
var globVarPattern = regexp.MustCompile(`\{\{\s*\.([a-zA-Z_][a-zA-Z0-9_.]*)\s*\}\}`)

// hasUnresolvedDynamicVar reports whether a glob references a shell-derived
// variable that has not been evaluated yet. FastGetVariables leaves such
// variables with an empty value so templates can still be parsed, which would
// turn "{{.DIR}}/**/*" into "/**/*" and make the globber scan from the
// filesystem root (and follow symlink cycles until it hangs).
func hasUnresolvedDynamicVar(glob string, cache *Cache) bool {
for _, match := range globVarPattern.FindAllStringSubmatch(glob, -1) {
v, ok := cache.Vars.Get(match[1])
if !ok {
return true
}
if v.Sh != nil && (v.Value == nil || v.Value == "") {
return true
}
}
return false
}

func ReplaceGlobs(globs []*ast.Glob, cache *Cache) []*ast.Glob {
if cache.err != nil || len(globs) == 0 {
return nil
}

new := make([]*ast.Glob, len(globs))
for i, g := range globs {
replaced := g.Glob
if !hasUnresolvedDynamicVar(g.Glob, cache) {
replaced = Replace(g.Glob, cache)
}
new[i] = &ast.Glob{
Glob: Replace(g.Glob, cache),
Glob: replaced,
Negate: g.Negate,
}
}
Expand Down