Skip to content

Commit

Permalink
Add splitArgs template function (#1059)
Browse files Browse the repository at this point in the history
  • Loading branch information
dhanusaputra authored Mar 17, 2023
1 parent e0fcb04 commit 9c3ee23
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
4 changes: 4 additions & 0 deletions internal/templater/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"text/template"

sprig "github.com/go-task/slim-sprig"
"mvdan.cc/sh/v3/shell"
"mvdan.cc/sh/v3/syntax"
)

Expand Down Expand Up @@ -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 },
}
Expand Down
18 changes: 18 additions & 0 deletions task_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 changes: 6 additions & 0 deletions testdata/split_args/Taskfile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: '3'

tasks:
default:
cmds:
- cmd: echo '{{splitArgs .CLI_ARGS | len}}'

0 comments on commit 9c3ee23

Please sign in to comment.