Skip to content

Commit

Permalink
Add Expression Function to Read File (#166)
Browse files Browse the repository at this point in the history
* add function

* add unit tests
  • Loading branch information
mfleader authored Mar 19, 2024
1 parent 48a46fc commit cdcbb0f
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions fixtures/test-readFile/hello-world.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
hello: world
35 changes: 35 additions & 0 deletions internal/builtinfunctions/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"go.flow.arcalot.io/pluginsdk/schema"
"math"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -32,6 +34,7 @@ func GetFunctions() map[string]schema.CallableFunction {
toLowerFunction := getToLowerFunction()
toUpperFunction := getToUpperFunction()
splitStringFunction := getSplitStringFunction()
loadFileFunction := getReadFileFunction()

// Combine in a map
allFunctions := map[string]schema.CallableFunction{
Expand All @@ -51,6 +54,7 @@ func GetFunctions() map[string]schema.CallableFunction {
toLowerFunction.ID(): toLowerFunction,
toUpperFunction.ID(): toUpperFunction,
splitStringFunction.ID(): splitStringFunction,
loadFileFunction.ID(): loadFileFunction,
}

return allFunctions
Expand Down Expand Up @@ -490,3 +494,34 @@ func getSplitStringFunction() schema.CallableFunction {
}
return funcSchema
}

func getReadFileFunction() schema.CallableFunction {
funcSchema, err := schema.NewCallableFunction(
"readFile",
[]schema.Type{schema.NewStringSchema(nil, nil, nil)},
schema.NewStringSchema(nil, nil, nil),
true,
schema.NewDisplayValue(
schema.PointerTo("readFile"),
schema.PointerTo(
"Return a file as a string.\n"+
"Param 1: The filepath to read into memory."),
nil,
),
func(filePath string) (string, error) {
absPath, err := filepath.Abs(filePath)
if err != nil {
return "", err
}
fileData, err := os.ReadFile(absPath) //nolint:gosec // potential file inclusion is handled because filepath.Abs() calls filepath.Clean()
if err != nil {
return "", err
}
return string(fileData), nil
},
)
if err != nil {
panic(err)
}
return funcSchema
}
12 changes: 12 additions & 0 deletions internal/builtinfunctions/functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,18 @@ var testData = map[string]struct {
false,
[]string{"1", "", "2", ""},
},
"readFile": {
"readFile",
[]any{"../../fixtures/test-readFile/hello-world.yaml"},
false,
"hello: world\n",
},
"readFile_nonexistent-file": {
"readFile",
[]any{"../../fixtures/test-readFile/nonexistent-file.yaml"},
true,
nil,
},
}

func TestFunctionsBulk(t *testing.T) {
Expand Down

0 comments on commit cdcbb0f

Please sign in to comment.