diff --git a/task.go b/task.go index 54cda92762..2c7eb06d5c 100644 --- a/task.go +++ b/task.go @@ -526,10 +526,47 @@ func (e *Executor) GetTask(call *Call) (*ast.Task, error) { } if len(matchingTasks) > 0 { - if call.Vars == nil { - call.Vars = ast.NewVars() + match := matchingTasks[0].Wildcards + if match == nil { + match = []string{} + } + + var ( + includeMatch ast.Var + hasMatchVar bool + ) + + if call.Vars != nil { + includeMatch, hasMatchVar = call.Vars.Get("MATCH") + if hasMatchVar { + if existingMatch, ok := includeMatch.Value.([]string); ok && existingMatch == nil { + includeMatch = ast.Var{Value: []string{}} + call.Vars.Set("MATCH", includeMatch) + } + } } - call.Vars.Set("MATCH", ast.Var{Value: matchingTasks[0].Wildcards}) + + if len(match) > 0 || !hasMatchVar { + if call.Vars == nil { + call.Vars = ast.NewVars() + } + includeMatch = ast.Var{Value: match} + hasMatchVar = true + call.Vars.Set("MATCH", includeMatch) + } + + if hasMatchVar { + taskCopy := matchingTasks[0].Task.DeepCopy() + matchFirstIncludeVars := ast.NewVars() + matchFirstIncludeVars.Set("MATCH", includeMatch) + if taskCopy.IncludeVars != nil { + matchFirstIncludeVars.Merge(taskCopy.IncludeVars, nil) + } + matchFirstIncludeVars.Set("MATCH", includeMatch) + taskCopy.IncludeVars = matchFirstIncludeVars + return taskCopy, nil + } + return matchingTasks[0].Task, nil } diff --git a/task_test.go b/task_test.go index 9d54af9740..43b6dc4d53 100644 --- a/task_test.go +++ b/task_test.go @@ -1271,6 +1271,23 @@ func TestIncludesInterpolation(t *testing.T) { // nolint:paralleltest // cannot } } +func TestIncludeWildcardVarsExposeMatch(t *testing.T) { + t.Parallel() + + var buff bytes.Buffer + e := task.NewExecutor( + task.WithDir("testdata/includes_wildcard_vars"), + task.WithSilent(true), + task.WithStdout(&buff), + task.WithStderr(&buff), + ) + require.NoError(t, e.Setup()) + + err := e.Run(t.Context(), &task.Call{Task: "stack:prod:show"}) + require.NoError(t, err) + assert.Equal(t, "prod\n", buff.String()) +} + func TestIncludesWithExclude(t *testing.T) { t.Parallel() diff --git a/testdata/includes_wildcard_vars/Taskfile.stack.yml b/testdata/includes_wildcard_vars/Taskfile.stack.yml new file mode 100644 index 0000000000..19994814c5 --- /dev/null +++ b/testdata/includes_wildcard_vars/Taskfile.stack.yml @@ -0,0 +1,6 @@ +version: '3' + +tasks: + show: + cmds: + - echo '{{.ENV}}' diff --git a/testdata/includes_wildcard_vars/Taskfile.yml b/testdata/includes_wildcard_vars/Taskfile.yml new file mode 100644 index 0000000000..5ed3e073f5 --- /dev/null +++ b/testdata/includes_wildcard_vars/Taskfile.yml @@ -0,0 +1,7 @@ +version: '3' + +includes: + 'stack:*': + taskfile: ./Taskfile.stack.yml + vars: + ENV: '{{index .MATCH 0}}'