Skip to content

Commit

Permalink
fix: escape tabs and newline when serializing to a config file
Browse files Browse the repository at this point in the history
  • Loading branch information
percevalw committed Jan 15, 2025
1 parent f5bae0d commit df6a030
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

- Support interpolated seed in the config file (as a reminder, the seed is treated specifically by confit to initialize random generators **before** any object is resolved)
- Support if/else expressions in interpolation, and only resolve the relevant branch
- Allow larger than 4096 bytes config files
- Escape tabs and newline when serializing to a config file

## v0.7.2 (2024-11-23)

Expand Down
3 changes: 1 addition & 2 deletions confit/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,7 @@ def represent_ref(self, node):

def represent_str(self, data):
node = super().represent_scalar("tag:yaml.org,2002:str", data)
if set(",'\"{}[]$") & set(data):
# node.value = dumps(data)
if set(",'\"{}[]$\n\t") & set(data):
node.style = "'" if data.count('"') > data.count("'") else '"'
return node

Expand Down
6 changes: 4 additions & 2 deletions confit/utils/xjson.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,8 @@ def _encode_str(s):
"""Return an ASCII-only JSON representation of a Python string"""
r = repr(s)
if s.count('"') <= s.count("'") and r.startswith("'"):
r = '"' + s.replace('"', '\\"').replace("\\'", "'") + '"'
r = r[1:-1]
r = '"' + r.replace('"', '\\"').replace("\\'", "'") + '"'
return r


Expand Down Expand Up @@ -294,4 +295,5 @@ def dumps(o: Any):
-------
str
"""
return "".join(_make_iterencode()(o))
res = "".join(_make_iterencode()(o))
return res
25 changes: 25 additions & 0 deletions tests/test_config_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -716,3 +716,28 @@ def test_escaped_string():
assert config["section"]["real_ref"] == "1"
assert config["section"]["escaped_broken_ref"] == "${test.a"
assert config["section"]["escaped_ref"] == "${test.a}"


def test_newline_serialization():
config = Config(
{
"section": {
"string": "\tok\nok",
}
}
)
assert (
config.to_yaml_str()
== """\
section:
string: "\\tok\\nok"
"""
)
assert (
config.to_cfg_str()
== """\
[section]
string = "\\tok\\nok"
"""
)

0 comments on commit df6a030

Please sign in to comment.