diff --git a/docs/docs/experiments/any_variables.mdx b/docs/docs/experiments/any_variables.mdx index 04735070..33b77067 100644 --- a/docs/docs/experiments/any_variables.mdx +++ b/docs/docs/experiments/any_variables.mdx @@ -179,12 +179,12 @@ tasks: - 'echo {{.FOO.b}}' ``` -## Parsing variables by reference +## Variables by reference -Lastly, this proposal adds support for parsing variables by reference. This is -really important now that variables can be types other than a string. -Previously, to send a variable from one task to another, you would have to use -the templating system to pass it: +Lastly, this proposal adds support for defining and passing variables by +reference. This is really important now that variables can be types other than a +string. Previously, to send a variable from one task to another, you would have +to use the templating system to pass it: ```yaml version: 3 @@ -225,7 +225,20 @@ tasks: ``` This means that the type of the variable is maintained when it is passed to -another Task. +another Task. This also works when defining a variable: + +```yaml +version: 3 + +tasks: + foo: + vars: + FOO: [A, B, C] # <-- FOO is defined as an array + BAR: + ref: FOO # <-- BAR is defined as a reference to FOO + cmds: + - 'echo {{index .BAR 0}}' # <-- BAR refers to FOO so the task outputs 'A' +``` diff --git a/internal/compiler/compiler.go b/internal/compiler/compiler.go index 7dcb725e..04558a5c 100644 --- a/internal/compiler/compiler.go +++ b/internal/compiler/compiler.go @@ -71,6 +71,10 @@ func (c *Compiler) getVariables(t *ast.Task, call *ast.Call, evaluateShVars bool newVar.Json = tr.Replace(v.Json) newVar.Yaml = tr.Replace(v.Yaml) newVar.Dir = v.Dir + // If the variable is a reference, we can resolve it + if newVar.Ref != "" { + newVar.Value = result.Get(newVar.Ref).Value + } // If the variable should not be evaluated, but is nil, set it to an empty string // This stops empty interface errors when using the templater to replace values later if !evaluateShVars && newVar.Value == nil { diff --git a/testdata/vars/any2/Taskfile.yml b/testdata/vars/any2/Taskfile.yml index bc6fd10c..394555b5 100644 --- a/testdata/vars/any2/Taskfile.yml +++ b/testdata/vars/any2/Taskfile.yml @@ -16,6 +16,32 @@ tasks: VAR: ref: MAP + map-ref: + vars: + MAP: + map: {"name":"Alice","age":30,"children":[{"name":"Bob","age":5},{"name":"Charlie","age":3},{"name":"Diane","age":1}]} + MAP_REF: + ref: MAP + cmds: + - task: print-var + vars: + VAR: + ref: MAP_REF + + map-ref-sh: + vars: + JSON_STRING: + sh: echo '{"name":"Alice","age":30,"children":[{"name":"Bob","age":5},{"name":"Charlie","age":3},{"name":"Diane","age":1}]}' + JSON: + json: "{{.JSON_STRING}}" + MAP_REF: + ref: JSON + cmds: + - task: print-var + vars: + VAR: + ref: MAP_REF + json: vars: JSON_STRING: