Skip to content

Commit df6a030

Browse files
committed
fix: escape tabs and newline when serializing to a config file
1 parent f5bae0d commit df6a030

File tree

4 files changed

+32
-4
lines changed

4 files changed

+32
-4
lines changed

changelog.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
- 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)
66
- Support if/else expressions in interpolation, and only resolve the relevant branch
7+
- Allow larger than 4096 bytes config files
8+
- Escape tabs and newline when serializing to a config file
79

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

confit/config.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -313,8 +313,7 @@ def represent_ref(self, node):
313313

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

confit/utils/xjson.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,8 @@ def _encode_str(s):
165165
"""Return an ASCII-only JSON representation of a Python string"""
166166
r = repr(s)
167167
if s.count('"') <= s.count("'") and r.startswith("'"):
168-
r = '"' + s.replace('"', '\\"').replace("\\'", "'") + '"'
168+
r = r[1:-1]
169+
r = '"' + r.replace('"', '\\"').replace("\\'", "'") + '"'
169170
return r
170171

171172

@@ -294,4 +295,5 @@ def dumps(o: Any):
294295
-------
295296
str
296297
"""
297-
return "".join(_make_iterencode()(o))
298+
res = "".join(_make_iterencode()(o))
299+
return res

tests/test_config_instance.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,3 +716,28 @@ def test_escaped_string():
716716
assert config["section"]["real_ref"] == "1"
717717
assert config["section"]["escaped_broken_ref"] == "${test.a"
718718
assert config["section"]["escaped_ref"] == "${test.a}"
719+
720+
721+
def test_newline_serialization():
722+
config = Config(
723+
{
724+
"section": {
725+
"string": "\tok\nok",
726+
}
727+
}
728+
)
729+
assert (
730+
config.to_yaml_str()
731+
== """\
732+
section:
733+
string: "\\tok\\nok"
734+
"""
735+
)
736+
assert (
737+
config.to_cfg_str()
738+
== """\
739+
[section]
740+
string = "\\tok\\nok"
741+
742+
"""
743+
)

0 commit comments

Comments
 (0)