From 84dea236c4ebee922f04fe869c2213014830115f Mon Sep 17 00:00:00 2001 From: Feng Huang Date: Fri, 28 Jun 2024 16:36:59 -0400 Subject: [PATCH] allow to patch multiple object in patch path by a single template Signed-off-by: Feng Huang --- reconcile/templating/lib/rendering.py | 47 +++++++++++++++------------ 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/reconcile/templating/lib/rendering.py b/reconcile/templating/lib/rendering.py index 2fe5f359ef..48bece1fb1 100644 --- a/reconcile/templating/lib/rendering.py +++ b/reconcile/templating/lib/rendering.py @@ -126,10 +126,6 @@ def render_output(self) -> str: def get_identifier(data: dict[str, Any]) -> Any: assert self.template.patch is not None # mypy - if not self.template.patch.identifier: - raise ValueError( - f"Expected identifier in patch for list at {self.template}" - ) if self.template.patch.identifier.startswith( "$" ) and not self.template.patch.identifier.startswith("$ref"): @@ -144,24 +140,35 @@ def get_identifier(data: dict[str, Any]) -> Any: return None return data.get(self.template.patch.identifier) - dta_identifier = get_identifier(data_to_add) - if not dta_identifier: - raise ValueError( - f"Expected identifier {self.template.patch.identifier} in data to add" + def update_data(data_to_add: dict[str, Any], matched_value: list) -> None: + assert self.template.patch is not None # mypy + if not self.template.patch.identifier: + raise ValueError( + f"Expected identifier in patch for list at {self.template}" + ) + dta_identifier = get_identifier(data_to_add) + if not dta_identifier: + raise ValueError( + f"Expected identifier {self.template.patch.identifier} in data to add" + ) + index = next( + ( + index + for index, data in enumerate(matched_value) + if get_identifier(data) == dta_identifier + ), + None, ) - - index = next( - ( - index - for index, data in enumerate(matched_value) - if get_identifier(data) == dta_identifier - ), - None, - ) - if index is None: - matched_value.append(data_to_add) + if index is None: + matched_value.append(data_to_add) + else: + matched_value[index] = data_to_add + + if isinstance(data_to_add, list): + for d in data_to_add: + update_data(d, matched_value) else: - matched_value[index] = data_to_add + update_data(data_to_add, matched_value) else: matched_value.update(data_to_add)