Skip to content

Instantly share code, notes, and snippets.

@aucampia
Last active July 5, 2023 14:48
Show Gist options
  • Save aucampia/c4c17608dd919c7c466cdedd923135d9 to your computer and use it in GitHub Desktop.
Save aucampia/c4c17608dd919c7c466cdedd923135d9 to your computer and use it in GitHub Desktop.
Doing a loop with a Taskfile and go-task
# https://taskfile.dev
# Run with no files
# task demo:emtpy
# Run with some files
# task demo:non-empty
version: '3'
vars:
GREETING: Hello, World!
ITEMS: '[ 1, 2, 3, 4, 8 ]'
tasks:
_loop_end: {}
_loop_tasks:
desc: |
Loop over tasks in the `_loop_tasks` variable.
`_loop_tasks` should be a JSON string with objects that have
`name` and `args` attributes, e.g.
```
[
{ "name": "task1", "args": { "a": 1 } },
{ "name": "task2", "args": { "b": 2 } }
]
```
The name is the name of the task to run, and the args attribute
will be passed to the task in a variable called `_loop_task_args`.
cmds:
- echo 'loop_tasks={{._loop_tasks}}'
- echo 'loop_task={{._loop_task}}'
- task: '{{(._loop_task | mustFromJson).name}}'
vars:
_loop_task_args: '{{(._loop_task | mustFromJson).args | mustToJson}}'
- task: '{{if gt (._loop_tasks| mustFromJson | len) 1}}_loop_tasks{{else}}_loop_end{{end}}'
vars:
_loop_tasks: "{{._loop_tasks | mustFromJson | rest | mustToJson}}"
vars:
_loop_task: '{{((._loop_tasks | mustFromJson | first | default (dict "name" "_loop_end" )) | mustToJson)}}'
demo:non-empty:
cmds:
- task: clean
- task: files:generate
- task: files:cksum
demo:empty:
cmds:
- task: clean
- task: files:cksum
default:
cmds:
- task: _loop_tasks
vars:
_loop_tasks: |
[
{ "name": "_do_a", "args": {"a":1} },
{ "name": "_do_b", "args": {"b":2} },
{ "name": "_do_c", "args": {"c":3} }
]
_do_a:
cmds:
- echo doing a 'args={{._loop_task_args}}}' 'arg={{(mustFromJson ._loop_task_args).a}}'
_do_b:
cmds:
- echo doing b 'args={{._loop_task_args}}}' 'arg={{(mustFromJson ._loop_task_args).b}}'
_do_c:
cmds:
- echo doing c 'args={{._loop_task_args}}}' 'arg={{(mustFromJson ._loop_task_args).c}}'
# ...
dynamic:
- task: files:generate
- task: files:cksum
files:generate:
cmds:
# generate files ...
- |
mkdir -vp tmp/files
for i in {0..2}; do
echo "file $i" > "tmp/files/file$i.txt"
done
files:cksum:
cmds:
- cmd: |
echo '_loop_tasks={{._loop_tasks}}'
echo 'TXT_FILES={{.TXT_FILES}}'
- task: _loop_tasks
vars:
_loop_tasks: |
[
{{if .TXT_FILES}}
{{range $index, $file := (.TXT_FILES | splitList "\n" | sortAlpha)}}
{{- if gt $index 0}},{{end -}}
{
"name": "_cksum_file",
"args": {
"FILE_NAME": {{$file | mustToJson}},
"INDEX": {{$index | mustToJson}}
}
}
{{end}}
{{end}}
]
vars:
TXT_FILES:
sh: shopt -s globstar nullglob; printf "%s\n" ./tmp/files/**/*.txt
_cksum_file:
cmds:
- cksum {{.FILE_NAME}}
vars:
FILE_NAME: '{{ .FILE_NAME | default (._loop_task_args | mustFromJson).FILE_NAME }}'
clean:
cmds:
- rm -vrf tmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment