Skip to content

Commit

Permalink
vega: Escape special characters in field and title.
Browse files Browse the repository at this point in the history
Closes #80
  • Loading branch information
daavoo committed Sep 6, 2022
1 parent c6f6abc commit b4dbe1c
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/dvc_render/vega.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ def get_filled_template(
f"Template '{self.template.name}' "
f"is not using '{anchor}' anchor"
)
else:
value = self.template.escape_special_characters(value)
content = self.template.fill_anchor(content, name, value)

return content
Expand Down
7 changes: 7 additions & 0 deletions src/dvc_render/vega_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ def fill_anchor(cls, content, name, value) -> str:
)
return content.replace(cls.anchor_str(name), value_str)

@classmethod
def escape_special_characters(cls, value: str) -> str:
"Escape special characters in `value`"
for character in (".", "[", "]"):
value = value.replace(character, "\\" + character)
return value

@classmethod
def anchor_str(cls, name) -> str:
"Get string wrapping ANCHOR formatted with name."
Expand Down
6 changes: 6 additions & 0 deletions tests/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
TEMPLATES,
LinearTemplate,
ScatterTemplate,
Template,
TemplateContentDoesNotMatch,
TemplateNotFoundError,
dump_templates,
Expand Down Expand Up @@ -76,3 +77,8 @@ def test_raise_on_init_modified(tmp_dir):

with pytest.raises(TemplateContentDoesNotMatch):
dump_templates(output=".", targets=["linear"])


def test_escape_special_characters():
value = "foo.bar[2]"
assert Template.escape_special_characters(value) == "foo\\.bar\\[2\\]"
17 changes: 17 additions & 0 deletions tests/test_vega.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,20 @@ def test_invalid_generate_markdown():
match="`generate_markdown` can only be used with `LinearTemplate`",
):
renderer.generate_markdown("output")


def test_escape_special_characters():
datapoints = [
{"foo.bar[0]": 0, "foo.bar[1]": 3},
{"foo.bar[0]": 1, "foo.bar[1]": 4},
]
props = {"template": "simple", "x": "foo.bar[0]", "y": "foo.bar[1]"}
renderer = VegaRenderer(datapoints, "foo", **props)
filled = json.loads(renderer.get_filled_template())
# data is not escaped
assert filled["data"]["values"][0] == datapoints[0]
# field and title yes
assert filled["encoding"]["x"]["field"] == "foo\\.bar\\[0\\]"
assert filled["encoding"]["x"]["title"] == "foo\\.bar\\[0\\]"
assert filled["encoding"]["y"]["field"] == "foo\\.bar\\[1\\]"
assert filled["encoding"]["y"]["title"] == "foo\\.bar\\[1\\]"

0 comments on commit b4dbe1c

Please sign in to comment.