Skip to content

Commit

Permalink
fix: preserve existing yaml quotes during update
Browse files Browse the repository at this point in the history
Preserve existing quotes in YAML files. The philosophy of the gitopscli is to only change the absolute minimum when applying YAML updates.

Fixes #152
  • Loading branch information
christiansiegel committed Mar 9, 2021
1 parent 90fb672 commit 590b2a2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
11 changes: 7 additions & 4 deletions gitopscli/io_api/yaml_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

_ARRAY_KEY_SEGMENT_PATTERN = re.compile(r"\[(\d+)\]")

YAML_INSTANCE = YAML()
YAML_INSTANCE.preserve_quotes = True # type: ignore


class YAMLException(Exception):
pass
Expand All @@ -14,26 +17,26 @@ class YAMLException(Exception):
def yaml_file_load(file_path: str) -> Any:
with open(file_path, "r") as stream:
try:
return YAML().load(stream)
return YAML_INSTANCE.load(stream)
except YAMLError as ex:
raise YAMLException(f"Error parsing YAML file: {file_path}") from ex


def yaml_file_dump(yaml: Any, file_path: str) -> None:
with open(file_path, "w+") as stream:
YAML().dump(yaml, stream)
YAML_INSTANCE.dump(yaml, stream)


def yaml_load(yaml_str: str) -> Any:
try:
return YAML().load(yaml_str)
return YAML_INSTANCE.load(yaml_str)
except YAMLError as ex:
raise YAMLException(f"Error parsing YAML string '{yaml_str}'") from ex


def yaml_dump(yaml: Any) -> str:
stream = StringIO()
YAML().dump(yaml, stream)
YAML_INSTANCE.dump(yaml, stream)
return stream.getvalue().rstrip()


Expand Down
2 changes: 2 additions & 0 deletions tests/io_api/test_yaml_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ def test_update_yaml_file(self):
b:
d: 1 # comment 3
c: 2 # comment 4
e: "expect quotes are preserved"
e:
- f: 3 # comment 5
g: 4 # comment 6
Expand All @@ -137,6 +138,7 @@ def test_update_yaml_file(self):
b:
d: 1 # comment 3
c: '2' # comment 4
e: "expect quotes are preserved"
e:
- f: 3 # comment 5
g: 42 # comment 6
Expand Down

0 comments on commit 590b2a2

Please sign in to comment.