Skip to content

Commit

Permalink
feat: Add support for python lambda filter
Browse files Browse the repository at this point in the history
  • Loading branch information
huyenngn committed Nov 27, 2024
1 parent bed6a30 commit 4d00c51
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion capellambse_context_diagrams/collectors/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,41 @@ def _fix_box_heights(self) -> None:
box = self.boxes[uuid]
box.height = max([box.height] + list(min_heights.values()))

def _safely_eval_filter(self, obj: m.ModelElement, filter: str) -> bool:
if not filter.startswith("lambda"):
raise ValueError(f"Filter '{filter}' is not a lambda expression.")

import capellambse

allowed_builtins = {
"True": True,
"False": False,
"isinstance": isinstance,
"len": len,
"sum": sum,
"min": min,
"max": max,
"abs": abs,
"round": round,
"capellambse": capellambse,
}
try:
result = eval(filter, {"__builtins__": allowed_builtins})(obj)
except Exception as e:
raise ValueError(
f"Filter '{filter}' raised an exception: {e}"
) from e
if not isinstance(result, bool):
raise ValueError(
f"Filter '{filter}' did not return a boolean value."
)
return result

def _matches_filters(
self, obj: m.ModelElement, filters: dict[str, t.Any]
self, obj: m.ModelElement, filters: dict[str, t.Any] | str
) -> bool:
if isinstance(filters, str):
return self._safely_eval_filter(obj, filters)
for key, value in filters.items():
if getattr(obj, key) != value:
return False
Expand Down

0 comments on commit 4d00c51

Please sign in to comment.