diff --git a/CHANGELOG.md b/CHANGELOG.md index ae158ecc..ce4015e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## Unreleased + +- Added new `splitArgs` to the template system + (`{{splitArgs "foo bar 'foo bar baz'"}}`) to ensure string is splitted as arguments not whitespaces + ## v3.22.0 - 2023-03-10 - Add a brand new `--global` (`-g`) flag that will run a Taskfile from your diff --git a/docs/docs/usage.md b/docs/docs/usage.md index cf8cb1f6..77d32591 100644 --- a/docs/docs/usage.md +++ b/docs/docs/usage.md @@ -1046,6 +1046,8 @@ Task also adds the following functions: - `shellQuote`: Quotes a string to make it safe for use in shell scripts. Task uses [this Go function](https://pkg.go.dev/mvdan.cc/sh/v3@v3.4.0/syntax#Quote) for this. The Bash dialect is assumed. +- `splitArgs`: Splits a string as if it were a command's arguments. + Task uses [this Go function](https://pkg.go.dev/mvdan.cc/sh/v3@v3.4.0/shell#Fields) Example: diff --git a/internal/templater/funcs.go b/internal/templater/funcs.go index 8cbe96bb..82f7badc 100644 --- a/internal/templater/funcs.go +++ b/internal/templater/funcs.go @@ -7,6 +7,7 @@ import ( "text/template" sprig "github.com/go-task/slim-sprig" + "mvdan.cc/sh/v3/shell" "mvdan.cc/sh/v3/syntax" ) @@ -41,6 +42,9 @@ func init() { "shellQuote": func(str string) (string, error) { return syntax.Quote(str, syntax.LangBash) }, + "splitArgs": func(s string) ([]string, error) { + return shell.Fields(s, nil) + }, // IsSH is deprecated. "IsSH": func() bool { return true }, } diff --git a/task_test.go b/task_test.go index beebdc5b..e348f758 100644 --- a/task_test.go +++ b/task_test.go @@ -1832,3 +1832,21 @@ func TestBashShellOptsCommandLevel(t *testing.T) { assert.NoError(t, err) assert.Equal(t, "globstar\ton\n", buff.String()) } + +func TestSplitArgs(t *testing.T) { + var buff bytes.Buffer + e := task.Executor{ + Dir: "testdata/split_args", + Stdout: &buff, + Stderr: &buff, + Silent: true, + } + assert.NoError(t, e.Setup()) + + vars := &taskfile.Vars{} + vars.Set("CLI_ARGS", taskfile.Var{Static: "foo bar 'foo bar baz'"}) + + err := e.Run(context.Background(), taskfile.Call{Task: "default", Vars: vars}) + assert.NoError(t, err) + assert.Equal(t, "3\n", buff.String()) +} diff --git a/testdata/split_args/Taskfile.yml b/testdata/split_args/Taskfile.yml new file mode 100644 index 00000000..29c13d3b --- /dev/null +++ b/testdata/split_args/Taskfile.yml @@ -0,0 +1,6 @@ +version: '3' + +tasks: + default: + cmds: + - cmd: echo '{{splitArgs .CLI_ARGS | len}}'