Skip to content

Commit

Permalink
refactor: Improve readability of port_exchange_collector
Browse files Browse the repository at this point in the history
  • Loading branch information
huyenngn committed Jun 18, 2024
1 parent 7516c0a commit 742b4f7
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions capellambse_context_diagrams/collectors/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@
None,
]

Filter: t.TypeAlias = cabc.Callable[
[cabc.Iterable[common.GenericElement]],
cabc.Iterable[common.GenericElement],
]

STYLECLASS_PREFIX = "__Derived"


Expand Down Expand Up @@ -263,27 +268,29 @@ def __collect(target):
return all_ports


def _extract_edges(
obj: common.ElementList[common.GenericElement],
attribute: str,
filter: Filter,
) -> common.ElementList[common.GenericElement] | list:
return filter(getattr(obj, attribute, []))


def port_exchange_collector(
ports: t.Iterable[common.GenericElement],
filter: cabc.Callable[
[cabc.Iterable[common.GenericElement]],
cabc.Iterable[common.GenericElement],
] = lambda i: i,
filter: Filter = lambda i: i,
) -> dict[str, common.ElementList[fa.AbstractExchange]]:
"""Collect exchanges from `ports` savely."""
edges: dict[str, common.ElementList[fa.AbstractExchange]] = {}
for i in ports:
try:
if exs := filter(getattr(i, "exchanges")):
edges[i.uuid] = exs
continue
except AttributeError:
pass
try:
if links := filter(getattr(i, "links")):
edges[i.uuid] = links
except AttributeError:
pass

for port in ports:
if exs := _extract_edges(port, "exchanges", filter):
edges[port.uuid] = exs
continue

if links := _extract_edges(port, "links", filter):
edges[port.uuid] = links

return edges


Expand Down

0 comments on commit 742b4f7

Please sign in to comment.