google / go-jsonnet

Apache License 2.0
1.64k stars 236 forks source link

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

Open thatInfrastructureGuy opened 4 months ago

thatInfrastructureGuy commented 4 months ago

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

input.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

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
}
thatInfrastructureGuy commented 4 months ago

Based on https://github.com/google/go-jsonnet/issues/223