Skip to content

Commit

Permalink
Preserve $$ escaping in Config.to_str (explosion#49)
Browse files Browse the repository at this point in the history
Output `$$` as the escaped value of literal `$` in `Config.to_str` to
preserve the literal `$` value (as opposed to the variable `${...}`).
  • Loading branch information
adrianeboyd committed Nov 21, 2023
1 parent a182a5c commit 3790548
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
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

0 comments on commit 3790548

Please sign in to comment.