Skip to content

Commit

Permalink
chore: add support for native sha256() function (#881)
Browse files Browse the repository at this point in the history
* chore: add support for native `sha256()` function

* Add documentation
  • Loading branch information
grafanalf committed Jun 16, 2023
1 parent 1974184 commit e264b4d
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
26 changes: 26 additions & 0 deletions docs/docs/jsonnet/native-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,32 @@ To use them in your code, you need to access them using `std.native` from the st

`std.native` takes the native function's name as a `string` argument and returns a `function`, which is called using the second set of parentheses.

## sha256

### Signature

```ts
sha256(string str) string
```

`sha256` computes the SHA256 sum of the given string.

### Examples

```jsonnet
{
sum: std.native('sha256')('Hello, World!'),
}
```

Evaluating with Tanka results in the JSON:

```json
{
"sum": "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"
}
```

## parseJson

### Signature
Expand Down
17 changes: 17 additions & 0 deletions pkg/jsonnet/native/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package native

import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"regexp"
"strings"
Expand Down Expand Up @@ -32,6 +34,9 @@ func Funcs() []*jsonnet.NativeFunction {
regexMatch(),
regexSubst(),

// Hash functions
hashSha256(),

helm.NativeFunc(helm.ExecHelm{}),
kustomize.NativeFunc(kustomize.ExecKustomize{}),
}
Expand All @@ -50,6 +55,18 @@ func parseJSON() *jsonnet.NativeFunction {
}
}

func hashSha256() *jsonnet.NativeFunction {
return &jsonnet.NativeFunction{
Name: "sha256",
Params: ast.Identifiers{"str"},
Func: func(dataString []interface{}) (interface{}, error) {
h := sha256.New()
h.Write([]byte(dataString[0].(string)))
return fmt.Sprintf("%x", h.Sum(nil)), nil
},
}
}

// parseYAML wraps `yaml.Unmarshal` to convert a string of yaml document(s) into a (set of) dicts
func parseYAML() *jsonnet.NativeFunction {
return &jsonnet.NativeFunction{
Expand Down
8 changes: 8 additions & 0 deletions pkg/jsonnet/native/funcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ func callNative(name string, data []interface{}) (res interface{}, err error, ca
return nil, nil, fmt.Errorf("could not find native function %s", name)
}

func TestSha256(t *testing.T) {
ret, err, callerr := callNative("sha256", []interface{}{"foo"})

assert.Empty(t, callerr)
assert.Equal(t, "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", ret)
assert.Empty(t, err)
}

func TestParseJSONEmptyDict(t *testing.T) {
ret, err, callerr := callNative("parseJson", []interface{}{"{}"})

Expand Down

0 comments on commit e264b4d

Please sign in to comment.