Skip to content

Commit

Permalink
fix: handle quotes in --tla-str and --ext-str in "tk eval" (#1237)
Browse files Browse the repository at this point in the history
* fix: Handle quotes in --tla-str and --ext-str in "tk eval".

Problem: If a string with a quote was passes to tk eval's --tla-str or
--ext-str, things would break in an unexpected fashion.

Fix: Properly JSON-quote any given string.

* test: Add test for the --tla-* and --ext-* flags parsing.
  • Loading branch information
rudo-thomas authored Nov 22, 2024
1 parent d712789 commit 7cba21d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
10 changes: 8 additions & 2 deletions cmd/tk/flags.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"fmt"
"encoding/json"
"strings"

"github.com/rs/zerolog/log"
Expand Down Expand Up @@ -95,7 +95,13 @@ func cliCodeParser(fs *pflag.FlagSet) (func() map[string]string, func() map[stri
if len(split) != 2 {
log.Fatal().Msgf(kind+"-str argument has wrong format: `%s`. Expected `key=<value>`", s)
}
m[split[0]] = fmt.Sprintf(`"%s"`, split[1])
// Properly quote the string; note that fmt.Sprintf("%q",...) could
// produce \U escapes which are not valid Jsonnet.
js, err := json.Marshal(split[1])
if err != nil {
log.Fatal().Msgf("impossible: failed to convert string to JSON: %s", err)
}
m[split[0]] = string(js)
}
return m
}
Expand Down
34 changes: 34 additions & 0 deletions cmd/tk/flags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"testing"

"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
)

func TestCliCodeParser(t *testing.T) {
fs := pflag.NewFlagSet("test-cli-code-parser", pflag.ContinueOnError)
parseExt, parseTLA := cliCodeParser(fs)
err := fs.Parse([]string{
"--ext-str", "es=1a \" \U0001f605 ' b\nc\u010f",
"--tla-str", "ts=2a \" \U0001f605 ' b\nc\u010f",
"--ext-code", "ec=1+2",
"--tla-code", "tc=2+3",
"-A", "ts2=ts2", // tla-str
"-V", "es2=es2", // ext-str
})
assert.NoError(t, err)
ext := parseExt()
assert.Equal(t, map[string]string{
"es": `"1a \" ` + "\U0001f605" + ` ' b\nc` + "\u010f" + `"`,
"ec": "1+2",
"es2": `"es2"`,
}, ext)
tla := parseTLA()
assert.Equal(t, map[string]string{
"ts": `"2a \" ` + "\U0001f605" + ` ' b\nc` + "\u010f" + `"`,
"tc": "2+3",
"ts2": `"ts2"`,
}, tla)
}

0 comments on commit 7cba21d

Please sign in to comment.