lang: core, funcs, types: Add ctx to simple func

Plumb through the standard context.Context so that a function can be
cancelled if someone requests this. It makes it less awkward to write
simple functions that might depend on io or network access.
This commit is contained in:
James Shubin
2024-05-09 19:25:46 -04:00
parent 3b754d5324
commit 415e22abe2
51 changed files with 166 additions and 108 deletions

View File

@@ -30,6 +30,7 @@
package corestrings
import (
"context"
"strings"
"github.com/purpleidea/mgmt/lang/funcs/simple"
@@ -45,7 +46,7 @@ func init() {
// Split splits the input string using the separator and returns the segments as
// a list.
func Split(input []types.Value) (types.Value, error) {
func Split(ctx context.Context, input []types.Value) (types.Value, error) {
str, sep := input[0].Str(), input[1].Str()
segments := strings.Split(str, sep)

View File

@@ -30,6 +30,7 @@
package corestrings
import (
"context"
"fmt"
"testing"
@@ -40,7 +41,7 @@ import (
func testSplit(input, sep string, output []string) error {
inputVal, sepVal := &types.StrValue{V: input}, &types.StrValue{V: sep}
val, err := Split([]types.Value{inputVal, sepVal})
val, err := Split(context.Background(), []types.Value{inputVal, sepVal})
if err != nil {
return err
}

View File

@@ -30,6 +30,7 @@
package corestrings
import (
"context"
"strings"
"github.com/purpleidea/mgmt/lang/funcs/simple"
@@ -44,7 +45,7 @@ func init() {
}
// ToLower turns a string to lowercase.
func ToLower(input []types.Value) (types.Value, error) {
func ToLower(ctx context.Context, input []types.Value) (types.Value, error) {
return &types.StrValue{
V: strings.ToLower(input[0].Str()),
}, nil

View File

@@ -30,6 +30,7 @@
package corestrings
import (
"context"
"testing"
"github.com/purpleidea/mgmt/lang/types"
@@ -37,7 +38,7 @@ import (
func testToLower(t *testing.T, input, expected string) {
inputStr := &types.StrValue{V: input}
value, err := ToLower([]types.Value{inputStr})
value, err := ToLower(context.Background(), []types.Value{inputStr})
if err != nil {
t.Error(err)
return