diff --git a/internal/templater/glob_test.go b/internal/templater/glob_test.go new file mode 100644 index 0000000000..f29a53b631 --- /dev/null +++ b/internal/templater/glob_test.go @@ -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) +} diff --git a/internal/templater/templater.go b/internal/templater/templater.go index eb4579be72..7d036300a8 100644 --- a/internal/templater/templater.go +++ b/internal/templater/templater.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "maps" + "regexp" "strings" "github.com/go-task/template" @@ -111,6 +112,27 @@ 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 @@ -118,8 +140,12 @@ func ReplaceGlobs(globs []*ast.Glob, cache *Cache) []*ast.Glob { 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, } }