Skip to content

Commit

Permalink
Code clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelldls committed Sep 26, 2024
1 parent a97c973 commit 605bdbd
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
17 changes: 12 additions & 5 deletions src/edge_containers_cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,13 +140,20 @@ def get_key(self, key_path: str) -> str | bool | int | None:
def set_key(self, key_path: str, value: str | bool | int):
curser = self._yaml_data
keys = key_path.split(".")
element = keys[-1]

# Iterate through mappings to element - Entries must exist
for key in keys:
if key is keys[-1]:
if key is element:
break # Keep dict as pointer
curser = curser[key]

# Set element if exists or create it
try:
curser[keys[-1]] = type(curser[keys[-1]])(value) # Preserve type
except KeyError: # Create element if does not exist
log.debug(f"Entry '{keys[-1]}' in '{key_path}' not found - Creating")
curser[keys[-1]] = value
curser[element] = type(curser[element])(value) # Preserve type
except KeyError:
# Create element if does not exist
log.debug(f"Entry '{element}' in '{key_path}' not found - Creating")
curser[element] = value

log.debug(f"Set '{element}' in '{key_path}' to {value}")
5 changes: 4 additions & 1 deletion tests/data/yaml.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ trunk_A:
branch_A:
leaf_A: 0 # Leaf comment
leaf_B: zero

trunk_B:
leaf_A: false
leaf_B: true # Out of order
leaf_A: false # Comment before space

leaf_A: "False"
6 changes: 5 additions & 1 deletion tests/test_unit.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from edge_containers_cli.utils import YamlFile


def test_yaml_processor(data):
def test_yaml_processor_get(data):
processor = YamlFile(data / "yaml.yaml")
expect_0 = {
"trunk_A.branch_A.leaf_A": 0,
Expand All @@ -12,10 +12,14 @@ def test_yaml_processor(data):
for key_0 in expect_0:
assert processor.get_key(key_0) == expect_0[key_0]


def test_yaml_processor_set(data):
processor = YamlFile(data / "yaml.yaml")
expect_1 = {
"trunk_A.branch_A.leaf_A": 1,
"trunk_A.branch_A.leaf_B": "one",
"trunk_B.leaf_A": True,
"trunk_B.leaf_C": True, # insertion
"leaf_A": "True",
}
for key_1 in expect_1:
Expand Down

0 comments on commit 605bdbd

Please sign in to comment.