1
0
mirror of https://github.com/go-task/task.git synced 2025-03-17 21:08:01 +02:00

feat: add sh and map (value) support

This commit is contained in:
Pete Davison 2023-12-23 04:59:10 +00:00
parent d87e7981fb
commit 2ccf80713d
3 changed files with 65 additions and 10 deletions

View File

@ -32,7 +32,7 @@ func init() {
readDotEnv()
GentleForce = New("GENTLE_FORCE")
RemoteTaskfiles = New("REMOTE_TASKFILES")
AnyVariables = New("ANY_VARIABLES")
AnyVariables = New("ANY_VARIABLES", "1", "2")
}
func New(xName string, enabledValues ...string) Experiment {

View File

@ -81,19 +81,53 @@ type Var struct {
func (v *Var) UnmarshalYAML(node *yaml.Node) error {
if experiments.AnyVariables.Enabled {
var value any
if err := node.Decode(&value); err != nil {
return err
// This implementation is not backwards-compatible and replaces the 'sh' key with map variables
if experiments.AnyVariables.Value == "1" {
var value any
if err := node.Decode(&value); err != nil {
return err
}
// If the value is a string and it starts with $, then it's a shell command
if str, ok := value.(string); ok {
if str, ok = strings.CutPrefix(str, "$"); ok {
v.Sh = str
return nil
}
}
v.Value = value
return nil
}
// If the value is a string and it starts with $, then it's a shell command
if str, ok := value.(string); ok {
if str, ok = strings.CutPrefix(str, "$"); ok {
v.Sh = str
// This implementation IS backwards-compatible and keeps the 'sh' key and allows map variables to be added under the `map` key
if experiments.AnyVariables.Value == "2" {
switch node.Kind {
case yaml.MappingNode:
key := node.Content[0].Value
switch key {
case "sh", "map":
var m struct {
Sh string
Map any
}
if err := node.Decode(&m); err != nil {
return err
}
v.Sh = m.Sh
v.Value = m.Map
return nil
default:
return fmt.Errorf(`yaml: line %d: %q is not a valid variable type. Try "sh", "map" or using a scalar value`, node.Line, key)
}
default:
var value any
if err := node.Decode(&value); err != nil {
return err
}
v.Value = value
return nil
}
}
v.Value = value
return nil
}
switch node.Kind {

21
testdata/vars/any2/Taskfile.yml vendored Normal file
View File

@ -0,0 +1,21 @@
version: '3'
tasks:
default:
- task: map
- task: json
- task: yaml
map:
vars:
MAP:
map: {"name":"Alice","age":30,"children":[{"name":"Bob","age":5},{"name":"Charlie","age":3},{"name":"Diane","age":1}]}
cmds:
- >-
echo "{{.MAP.name}} has {{len .MAP.children}} children called
{{- $children := .MAP.children -}}
{{- range $i, $child := $children -}}
{{- if lt $i (sub (len $children) 1)}} {{$child.name -}},
{{- else}} and {{$child.name -}}
{{- end -}}
{{- end -}}"