mirror of
https://github.com/element-hq/ess-helm.git
synced 2026-12-05 16:22:29 -08:00
Support array indices in set_nested_value
This commit is contained in:
2 files changed
+232
-24
No files matched your search
@@ -55,40 +55,124 @@ def yaml_dump_with_pipe_for_multiline(data: Any) -> str:
|
||||
def set_nested_value(config: dict[str, Any], path: str, value: Any) -> None:
|
||||
"""
|
||||
Set a value in a nested configuration at the specified path.
|
||||
Properly handles numeric indices to create/set values in arrays.
|
||||
|
||||
Args:
|
||||
config: Configuration dictionary to modify
|
||||
path: Dot-separated path where to set the value
|
||||
value: Value to set
|
||||
"""
|
||||
if "." in path:
|
||||
# Nested path
|
||||
parts = path.split(".")
|
||||
current = config
|
||||
if "." not in path:
|
||||
config[path] = value
|
||||
return
|
||||
|
||||
# Navigate/create the path
|
||||
for part in parts[:-1]:
|
||||
if isinstance(current, dict):
|
||||
if part not in current:
|
||||
current[part] = {}
|
||||
current = current[part]
|
||||
elif isinstance(current, list):
|
||||
if int(part) > len(current):
|
||||
# Create missing list items
|
||||
current.extend([None] * (int(part) - len(current) + 1))
|
||||
current = current[int(part)]
|
||||
else:
|
||||
# Can't navigate further, overwrite with dict
|
||||
current = {}
|
||||
config[parts[0]] = current
|
||||
parts = path.split(".")
|
||||
current: dict[str, Any] | list[Any] = config
|
||||
|
||||
for i, part in enumerate(parts[:-1]):
|
||||
next_part = parts[i + 1] if i + 1 < len(parts) else None
|
||||
|
||||
if isinstance(current, list):
|
||||
current[int(parts[-1])] = value
|
||||
# Current is a list, treat part as integer index
|
||||
try:
|
||||
idx = int(part)
|
||||
except ValueError:
|
||||
return # Invalid index
|
||||
# Extend list if needed
|
||||
while idx >= len(current):
|
||||
current.append(None)
|
||||
if current[idx] is None:
|
||||
# Create appropriate type for next level
|
||||
current[idx] = [] if (next_part and next_part.isdigit()) else {}
|
||||
current = current[idx]
|
||||
|
||||
elif isinstance(current, dict):
|
||||
if part in current:
|
||||
# Already exists, navigate to it
|
||||
current = current[part]
|
||||
else:
|
||||
# Create new structure
|
||||
# If next part is numeric, create a list here (for array indices)
|
||||
# Otherwise create a dict
|
||||
if next_part and next_part.isdigit():
|
||||
current[part] = []
|
||||
else:
|
||||
current[part] = {}
|
||||
current = current[part]
|
||||
else:
|
||||
current[parts[-1]] = value
|
||||
# Can't navigate further, start over
|
||||
current = {}
|
||||
config[parts[0]] = current
|
||||
|
||||
# Set final value
|
||||
final_part = parts[-1]
|
||||
if isinstance(current, list):
|
||||
try:
|
||||
idx = int(final_part)
|
||||
except ValueError:
|
||||
return
|
||||
while idx >= len(current):
|
||||
current.append(None)
|
||||
current[idx] = value
|
||||
else:
|
||||
# Direct key
|
||||
config[path] = value
|
||||
current[final_part] = value
|
||||
|
||||
|
||||
def is_wildcard_pattern(pattern: str) -> bool:
|
||||
"""Check if a path pattern contains a wildcard."""
|
||||
return "*" in pattern
|
||||
|
||||
|
||||
def path_matches_pattern(path: str, pattern: str) -> bool:
|
||||
"""
|
||||
Check if a concrete path matches a wildcard pattern.
|
||||
|
||||
The wildcard `*` in the pattern matches exactly one path component.
|
||||
All other components must match exactly.
|
||||
|
||||
Args:
|
||||
path: Concrete path like "certificates.0.value"
|
||||
pattern: Pattern like "certificates.*.value"
|
||||
|
||||
Returns:
|
||||
True if path matches pattern
|
||||
"""
|
||||
path_parts = path.split(".")
|
||||
pattern_parts = pattern.split(".")
|
||||
|
||||
if len(path_parts) != len(pattern_parts):
|
||||
return False
|
||||
|
||||
for path_part, pattern_part in zip(path_parts, pattern_parts, strict=True):
|
||||
if pattern_part == "*":
|
||||
continue
|
||||
elif path_part != pattern_part:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def find_matching_schema_key(path: str, schema: dict[str, Any]) -> str | None:
|
||||
"""
|
||||
Find a schema key that matches the given concrete path.
|
||||
|
||||
Checks for exact match first, then wildcard pattern match.
|
||||
|
||||
Args:
|
||||
path: Concrete path like "matrixAuthenticationService.certificates.0.value"
|
||||
schema: Dict of {schema_key: SecretConfig}
|
||||
|
||||
Returns:
|
||||
The matching schema key (exact or wildcard pattern), or None
|
||||
"""
|
||||
if path in schema:
|
||||
return path
|
||||
|
||||
for schema_key in schema:
|
||||
if is_wildcard_pattern(schema_key) and path_matches_pattern(path, schema_key):
|
||||
return schema_key
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_nested_value(config: dict[str, Any], path: str) -> Any:
|
||||
|
||||
@@ -4,7 +4,14 @@
|
||||
|
||||
|
||||
import pytest
|
||||
from ess_migration_tool.utils import get_nested_value, remove_nested_value, set_nested_value
|
||||
from ess_migration_tool.utils import (
|
||||
find_matching_schema_key,
|
||||
get_nested_value,
|
||||
is_wildcard_pattern,
|
||||
path_matches_pattern,
|
||||
remove_nested_value,
|
||||
set_nested_value,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -111,3 +118,120 @@ def test_remove_nested_value_empty_config():
|
||||
config = {}
|
||||
remove_nested_value(config, "a.b.c")
|
||||
assert config == {}
|
||||
|
||||
|
||||
# Tests for set_nested_value list creation
|
||||
|
||||
|
||||
def test_set_nested_value_creates_list_from_scratch():
|
||||
config = {}
|
||||
set_nested_value(config, "a.0", "val")
|
||||
assert config == {"a": ["val"]}
|
||||
|
||||
|
||||
def test_set_nested_value_creates_list_with_multiple_items():
|
||||
config = {}
|
||||
set_nested_value(config, "a.0", "first")
|
||||
set_nested_value(config, "a.1", "second")
|
||||
assert config == {"a": ["first", "second"]}
|
||||
|
||||
|
||||
def test_set_nested_value_creates_nested_list():
|
||||
config = {}
|
||||
set_nested_value(config, "a.0.b", "val")
|
||||
assert config == {"a": [{"b": "val"}]}
|
||||
|
||||
|
||||
def test_set_nested_value_extends_list():
|
||||
config = {"a": ["x"]}
|
||||
set_nested_value(config, "a.1", "val")
|
||||
assert config == {"a": ["x", "val"]}
|
||||
|
||||
|
||||
def test_set_nested_value_extends_list_with_gap():
|
||||
config = {"a": ["x"]}
|
||||
set_nested_value(config, "a.3", "val")
|
||||
assert config == {"a": ["x", None, None, "val"]}
|
||||
|
||||
|
||||
def test_set_nested_value_deep_path_creates_lists():
|
||||
config = {}
|
||||
set_nested_value(config, "a.b.0.c.1.d", "val")
|
||||
assert config["a"]["b"][0]["c"][1]["d"] == "val"
|
||||
|
||||
|
||||
# Tests for wildcard pattern matching
|
||||
|
||||
|
||||
def test_is_wildcard_pattern_true():
|
||||
assert is_wildcard_pattern("a.*.c") is True
|
||||
assert is_wildcard_pattern("*") is True
|
||||
assert is_wildcard_pattern("a.*") is True
|
||||
|
||||
|
||||
def test_is_wildcard_pattern_false():
|
||||
assert is_wildcard_pattern("a.b.c") is False
|
||||
assert is_wildcard_pattern("normal.path") is False
|
||||
assert is_wildcard_pattern("") is False
|
||||
|
||||
|
||||
def test_path_matches_pattern_basic():
|
||||
assert path_matches_pattern("certificates.0.value", "certificates.*.value") is True
|
||||
assert path_matches_pattern("certificates.1.value", "certificates.*.value") is True
|
||||
assert path_matches_pattern("certificates.999.value", "certificates.*.value") is True
|
||||
|
||||
|
||||
def test_path_matches_pattern_no_match():
|
||||
assert path_matches_pattern("certificates.0.name", "certificates.*.value") is False
|
||||
assert path_matches_pattern("other.0.value", "certificates.*.value") is False
|
||||
assert path_matches_pattern("certificates.value", "certificates.*.value") is False
|
||||
|
||||
|
||||
def test_path_matches_pattern_exact_components():
|
||||
assert path_matches_pattern("a.1.c", "a.*.c") is True
|
||||
assert path_matches_pattern("a.b.c", "a.*.c") is True
|
||||
assert path_matches_pattern("a.x.c", "a.*.c") is True
|
||||
assert path_matches_pattern("x.1.c", "a.*.c") is False
|
||||
assert path_matches_pattern("a.1.x", "a.*.c") is False
|
||||
|
||||
|
||||
def test_path_matches_pattern_different_length():
|
||||
assert path_matches_pattern("a.b", "a.*.c") is False
|
||||
assert path_matches_pattern("a.b.c.d", "a.*.c") is False
|
||||
|
||||
|
||||
def test_path_matches_pattern_multiple_wildcards():
|
||||
# path_matches_pattern doesn't support multiple wildcards in pattern
|
||||
# It will just check component by component
|
||||
assert path_matches_pattern("a.1.c.2", "a.*.c.*") is True
|
||||
|
||||
|
||||
# Tests for find_matching_schema_key
|
||||
|
||||
|
||||
def test_find_matching_schema_key_exact_match():
|
||||
schema = {"a.b.c": "config"}
|
||||
assert find_matching_schema_key("a.b.c", schema) == "a.b.c"
|
||||
|
||||
|
||||
def test_find_matching_schema_key_wildcard_match():
|
||||
schema = {"a.*.c": "wildcard_config"}
|
||||
assert find_matching_schema_key("a.999.c", schema) == "a.*.c"
|
||||
|
||||
|
||||
def test_find_matching_schema_key_no_match():
|
||||
schema = {"a.b.c": "config"}
|
||||
assert find_matching_schema_key("x.y.z", schema) is None
|
||||
|
||||
|
||||
def test_find_matching_schema_key_prefers_exact():
|
||||
# When both exact and wildcard match, exact takes precedence
|
||||
schema = {"a.0.c": "exact_config", "a.*.c": "wildcard_config"}
|
||||
assert find_matching_schema_key("a.0.c", schema) == "a.0.c"
|
||||
|
||||
|
||||
def test_find_matching_schema_key_multiple_patterns():
|
||||
schema = {"a.*.c": "pattern1", "x.*.y": "pattern2"}
|
||||
assert find_matching_schema_key("a.5.c", schema) == "a.*.c"
|
||||
assert find_matching_schema_key("x.5.y", schema) == "x.*.y"
|
||||
assert find_matching_schema_key("z.5.y", schema) is None
|
||||
Reference in new issue
Block a user