]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
manager: datamodel: types: multiline method for EscapedStr
authorAleš Mrázek <ales.mrazek@nic.cz>
Fri, 23 Jun 2023 10:02:08 +0000 (12:02 +0200)
committerAleš Mrázek <ales.mrazek@nic.cz>
Thu, 13 Jul 2023 07:50:22 +0000 (09:50 +0200)
It escapes double square brackets.

manager/knot_resolver_manager/datamodel/templates/macros/local_data_macros.lua.j2
manager/knot_resolver_manager/datamodel/types/types.py
manager/tests/unit/datamodel/templates/test_types_render.py

index c3104b7de059f86cccf642880aef32bcbf349552..98819a8f354d27807a04d4b2cc74ce28e7213eaf 100644 (file)
@@ -46,7 +46,8 @@ assert(hints.add_hosts('{{ file }}').result == true)
 {{ id }}.filename = '{{ input_str }}'
 {% else %}
 {{ id }}.input_str = [[
-{{ input_str }}]]
+{{ input_str.multiline() }}
+]]
 {% endif %}
 assert(C.kr_rule_zonefile({{ id }})==0)
 {%- endmacro %}
index dfc2317cc31b20b044c51a38a91fff5ff55d5019..c8b533215e9d343007972470f2d3baa637617341 100644 (file)
@@ -99,6 +99,22 @@ class EscapedStr(StrBase):
                 s[i] = repr(c)[1:-1]
         self._value = "".join(s)
 
+    def multiline(self) -> str:
+        """
+        Lua multiline string is enclosed in double square brackets '[[ ]]'.
+        This method makes sure that double square brackets are escaped.
+        """
+
+        replace = {
+            "[[": r"\[\[",
+            "]]": r"\]\]",
+        }
+
+        ml = self._orig_value
+        for s, r in replace.items():
+            ml = ml.replace(s, r)
+        return ml
+
 
 class EscapedStr32B(EscapedStr, StringLengthBase):
     """
index 15a0611a433f3f81ef47c2f69b87114e2cc77b6f..f83b41e34de404bcc5884f4197a1f8272cfc39df 100644 (file)
@@ -9,6 +9,34 @@ from knot_resolver_manager.utils.modeling import ConfigSchema
 str_template = Template("'{{ string }}'")
 
 
+str_multiline_template = Template(
+    """[[
+{{ string.multiline() }}
+]]"""
+)
+
+
+@pytest.mark.parametrize(
+    "val,exp",
+    [
+        ("\a\b\f\n\r\t\v\\", "\a\b\f\n\r\t\v\\"),
+        ("[[ test ]]", r"\[\[ test \]\]"),
+        ("[ [ test ] ]", r"[ [ test ] ]"),
+    ],
+)
+def test_escaped_str_multiline(val: Any, exp: str):
+    class TestSchema(ConfigSchema):
+        pattern: EscapedStr
+
+    d = TestSchema({"pattern": val})
+    assert (
+        str_multiline_template.render(string=d.pattern)
+        == f"""[[
+{exp}
+]]"""
+    )
+
+
 @pytest.mark.parametrize(
     "val,exp",
     [