Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve $$ escaping in Config.to_str #49

Merged
merged 1 commit into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions confection/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def interpolate(self, parser, option, accum, rest, section, map, depth):
else:
accum.append(v)
else:
err = "'$' must be followed by '$' or '{', " "found: %r" % (rest,)
err = "'$' must be followed by '$' or '{', found: %r" % (rest,)
raise InterpolationSyntaxError(option, section, err)

def _get_section_name(self, name: str) -> str:
Expand Down Expand Up @@ -520,7 +520,10 @@ def try_dump_json(value: Any, data: Union[Dict[str, dict], Config, str] = "") ->
# Work around values that are strings but numbers
value = f'"{value}"'
try:
return srsly.json_dumps(value)
value = srsly.json_dumps(value)
value = re.sub(r"\$([^{])", "$$\1", value)
value = re.sub(r"\$$", "$$", value)
return value
except Exception as e:
err_msg = (
f"Couldn't serialize config value of type {type(value)}: {e}. Make "
Expand Down
23 changes: 23 additions & 0 deletions confection/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,29 @@ def test_config_to_str_creates_intermediate_blocks():
)


def test_config_to_str_escapes():
section_str = """
[section]
node1 = "^a$$"
node2 = "$$b$$c"
"""
section_dict = {"section": {"node1": "^a$", "node2": "$b$c"}}

# parse from escaped string
cfg = Config().from_str(section_str)
assert cfg == section_dict

# parse from non-escaped dict
cfg = Config(section_dict)
assert cfg == section_dict

# roundtrip through str
cfg_str = cfg.to_str()
assert "^a$$" in cfg_str
new_cfg = Config().from_str(cfg_str)
assert cfg == section_dict


def test_config_roundtrip_bytes():
cfg = Config().from_str(OPTIMIZER_CFG)
cfg_bytes = cfg.to_bytes()
Expand Down
Loading