google / google/go-jsonnet

Error when using custom functions with `int` parameters or return types

Open
#761 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
1.8k
Forks
263
PR merge metrics
No merged PRs in 30d

Description

I am new to jsonnet, so I might be missing something.

* Issue-1: Custom function only accepts `float64`, but not integer.
* Issue-2: Custom function returning `integer` throws error but returning `float` works. (Resolved on latest master. Only affects `v0.20.0`. )

---

input.jsonnet
```jsonnet
local convertToInt = std.native('convertToInt');
// local replicas = convertToInt(3); -> (Issue-1)This does NOT Accept integer. But float64 works.
local replicas = convertToInt('3');
{
replicas: replicas,
}
```

main.go
```go
package main

import (
"fmt"
"log"
"strconv"

jsonnet "github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/ast"
"gopkg.in/yaml.v3"
)

func main() {
// Create a new Jsonnet VM
vm := jsonnet.MakeVM()

// Custom Golang function embed
jsonToStringFunc := &jsonnet.NativeFunction{
Name: "convertToInt",
Params: ast.Identifiers{"x"},
Func: convertToInt,
}
vm.NativeFunction(jsonToStringFunc)

// Read the Jsonnet file
jsonnetCode, err := vm.EvaluateFile("input.jsonnet")
if err != nil {
log.Fatal(err)
}

// Marshal the output to YAML
var output interface{}
err = yaml.Unmarshal([]byte(jsonnetCode), &output)
if err != nil {
log.Fatal(err)
}

// Print the YAML output
yamlOutput, err := yaml.Marshal(output)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(yamlOutput))
}

func convertToInt(x []interface{}) (interface{}, error) {
log.Printf("%v %T", x, x)
y, ok := x[0].(string)
// y, ok := x[0].(int) // (Issue-1) int does not work, but float64 works, when x is a number.
if !ok {
return nil, fmt.Errorf("Error: Not a string")
}
log.Printf("%v %T", y, y)
num, err := strconv.ParseFloat(y, 10) // works
// num, err := strconv.Atoi(y) // (Issue-2)does not work if returning int
if err != nil {
return nil, err
}
return num, nil
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.