version: '3'

tasks:
  default:
    - task: map
    - task: nested-map
    - task: slice
    - task: ref
    - task: ref-sh
    - task: ref-dep
    - task: ref-resolver
    - task: json

  map:
    vars:
      MAP:
        map: {"name":"Alice","age":30,"children":[{"name":"Bob","age":5},{"name":"Charlie","age":3},{"name":"Diane","age":1}]}
    cmds:
      - task: print-story
        vars:
          VAR:
            ref: .MAP

  nested-map:
    vars:
      FOO: "foo"
      nested:
        map:
          variables:
            work: "{{.FOO}}"
    cmds:
      - echo {{.nested.variables.work}}

  slice:
    vars:
      FOO: "foo"
      BAR: "bar"
      slice_variables_work: ["{{.FOO}}","{{.BAR}}"]
    cmds:
      - echo {{index .slice_variables_work 0}} {{index .slice_variables_work 1}}

  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-story
        vars:
          VAR:
            ref: .MAP_REF

  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: "fromJson {{.JSON_STRING}}"
      MAP_REF:
        ref: .JSON
    cmds:
      - task: print-story
        vars:
          VAR:
            ref: .MAP_REF

  ref-dep:
    vars:
      MAP:
        map: {"name":"Alice","age":30,"children":[{"name":"Bob","age":5},{"name":"Charlie","age":3},{"name":"Diane","age":1}]}
    deps:
      - task: print-story
        vars:
          VAR:
            ref: .MAP

  ref-resolver:
    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: (index .MAP_REF.children 0).name

  json:
    vars:
      JSON_STRING:
        sh: cat example.json
      JSON:
        ref: "fromJson .JSON_STRING"
    cmds:
      - task: print-story
        vars:
          VAR:
            ref: .JSON

  print-var:
    cmds:
      - echo "{{.VAR}}"

  print-story:
    cmds:
      - >-
        echo "{{.VAR.name}} has {{len .VAR.children}} children called
        {{- $children := .VAR.children -}}
        {{- range $i, $child := $children -}}
          {{- if lt $i (sub (len $children) 1)}} {{$child.name -}},
          {{- else}} and {{$child.name -}}
          {{- end -}}
        {{- end -}}"
