Skip to content

Commit

Permalink
eval: Allow map key as expression (grafana#896)
Browse files Browse the repository at this point in the history
* eval: Allow map key as expression
If the first level trying to eval has characters like `-` or `.` in them, it's currently impossible to eval
With this PR, we can do `-e '["my-key"]'`

* Add test
  • Loading branch information
julienduchesne authored Aug 4, 2023
1 parent 08e6a00 commit 8e496b7
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
3 changes: 1 addition & 2 deletions cmd/tk/jsonnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"encoding/json"
"fmt"

"github.com/go-clix/cli"

Expand All @@ -25,7 +24,7 @@ func evalCmd() *cli.Command {
JsonnetOpts: getJsonnetOpts(),
}
if *evalPattern != "" {
jsonnetOpts.EvalScript = fmt.Sprintf(tanka.PatternEvalScript, *evalPattern)
jsonnetOpts.EvalScript = tanka.PatternEvalScript(*evalPattern)
}
raw, err := tanka.Eval(args[0], jsonnetOpts)

Expand Down
7 changes: 6 additions & 1 deletion pkg/tanka/evaluators.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ function(%s)
return raw, nil
}

const PatternEvalScript = "main.%s"
func PatternEvalScript(expr string) string {
if strings.HasPrefix(expr, "[") {
return fmt.Sprintf("main%s", expr)
}
return fmt.Sprintf("main.%s", expr)
}

// MetadataEvalScript finds the Environment object (without its .data object)
const MetadataEvalScript = `
Expand Down
18 changes: 18 additions & 0 deletions pkg/tanka/evaluators_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,21 @@ func TestEvalJsonnet(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, `"foovalue"`, strings.TrimSpace(json))
}

func TestEvalJsonnetWithExpression(t *testing.T) {
exprs := []string{`["testCase"]`, "testCase"}

for _, expr := range exprs {
t.Run(expr, func(t *testing.T) {
opts := jsonnet.Opts{
EvalScript: PatternEvalScript(expr),
}

// This will fail intermittently if TLAs are passed as positional
// parameters.
json, err := evalJsonnet("testdata/cases/object", opts)
assert.NoError(t, err)
assert.Equal(t, `"object"`, strings.TrimSpace(json))
})
}
}

0 comments on commit 8e496b7

Please sign in to comment.