1
0
mirror of https://github.com/go-task/task.git synced 2024-12-04 10:24:45 +02:00

Add splitArgs template function (#1059)

This commit is contained in:
Dhanu Saputra 2023-03-17 07:38:24 +07:00 committed by GitHub
parent e0fcb040ee
commit 9c3ee234f1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 35 additions and 0 deletions

View File

@ -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

View File

@ -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:

View File

@ -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 },
}

View File

@ -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())
}

6
testdata/split_args/Taskfile.yml vendored Normal file
View File

@ -0,0 +1,6 @@
version: '3'
tasks:
default:
cmds:
- cmd: echo '{{splitArgs .CLI_ARGS | len}}'