Skip to content

Commit

Permalink
fix: improve support for escaped strings in configs
Browse files Browse the repository at this point in the history
  • Loading branch information
percevalw committed Sep 2, 2024
1 parent 292a690 commit 542ecd2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 24 deletions.
27 changes: 6 additions & 21 deletions confit/utils/xjson.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import re
from json.encoder import ESCAPE_DCT
import ast
from typing import Any, Callable

from lark import Lark, Transformer, Tree
Expand Down Expand Up @@ -69,7 +68,6 @@ def __eq__(self, other):
SIGNED_FLOAT: ["+"|"-"] FLOAT
SIGNED_INT: ["+"|"-"] INT
%import common.ESCAPED_STRING
%import common.LETTER
%import common.DIGIT
%import common.FLOAT
Expand Down Expand Up @@ -98,14 +96,7 @@ def __init__(self, input_string: str):
def string(self, s):
"""Parse string"""
(s,) = s
if (
s.startswith('"')
and s.endswith('"')
or s.startswith("'")
and s.endswith("'")
):
return s[1:-1]
return s
return ast.literal_eval(s)

def float(self, n):
"""Parse number"""
Expand Down Expand Up @@ -170,18 +161,12 @@ def _floatstr(o, _repr=float.__repr__, _inf=float("inf"), _neginf=-float("inf"))
return text


ESCAPE_DCT_DOUBLE = {**ESCAPE_DCT, '"': '\\"'}
ESCAPE_DCT_DOUBLE.pop('"')
ESCAPE_DCT_DOUBLE.pop("\\")


def _encode_str(s):
"""Return an ASCII-only JSON representation of a Python string"""

if s.count('"') > s.count("'"):
return "'" + re.sub("'", "\\'", s) + "'"
else:
return '"' + re.sub('"', '\\"', s) + '"'
r = repr(s)
if s.count('"') <= s.count("'") and r.startswith("'"):
r = '"' + s.replace('"', '\\"').replace("\\'", "'") + '"'
return r


def _make_iterencode(
Expand Down
9 changes: 6 additions & 3 deletions tests/test_config_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def test_strings():
"bar": "bar",
"val": "val",
"quoted": "'val'",
"esc": '\\"val\\"',
"esc": '"val"',
}
assert (
cfg.to_str()
Expand All @@ -270,7 +270,7 @@ def test_strings():
bar = "bar"
val = "val"
quoted = "'val'"
esc = '\\"val\\"'
esc = '"val"'
"""
)
Expand Down Expand Up @@ -580,7 +580,10 @@ def test_string():
"""
[section]
string1 = '\"ok\"'
string2 = "\\bok\\b"
# When writing config strings in Python
# We have to double escape the backslashes,
# once for Python and once for the config parser
string2 = "\\\\bok\\\\b"
string3 = ok
"""
)
Expand Down

0 comments on commit 542ecd2

Please sign in to comment.