Skip to content

Commit 24d7b12

Browse files
committed
fix(yaml): Better preserve YAML formatting
Updated the YAML editing code to work around an issue where blank lines and multi-line comments weren't handled correctly, resulting in blank lines getting deleted and new blank lines getting inserted in comments. Also changed the default indentation to match what is used in the ZMK config template, and enabled preserving quotes by default.
1 parent bdf631c commit 24d7b12

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

zmk/yaml.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,22 @@ class YAML(ruamel.yaml.YAML):
1818
readable or seekable, a leading comment will be overwritten.
1919
"""
2020

21+
def __init__(self, *args, **kwargs) -> None:
22+
super().__init__(*args, **kwargs)
23+
24+
self.preserve_quotes = True
25+
self.indent(mapping=2, sequence=4, offset=2)
26+
27+
def load(self, stream: Path | IO | str) -> Any:
28+
# Reading from a Path causes a round-trip conversion to drop blank lines
29+
# for some reason. As a workaround, just read in the whole file to a
30+
# string and parse that. It's probably slower, but none of the file we
31+
# work with are large enough for it to matter.
32+
if isinstance(stream, Path):
33+
return super().load(stream.read_text())
34+
35+
return super().load(stream)
36+
2137
def dump(self, data, stream: Path | IO | None = None, *, transform=None) -> None:
2238
if stream is None:
2339
raise TypeError("Dumping from a context manager is not supported.")

0 commit comments

Comments
 (0)