Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 53 additions & 7 deletions custom_components/spook/action_extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import re
from typing import TYPE_CHECKING, Any

from homeassistant.const import CONF_ENABLED

from .const import LOGGER
from .template_extraction import (
ENTITY_ID_PATTERN,
Expand All @@ -21,22 +23,53 @@


async def async_extract_entities_from_action_config(
hass: HomeAssistant, config: dict[str, Any] | list
hass: HomeAssistant,
config: dict[str, Any] | list,
*,
include_disabled: bool = True,
_in_sequence: bool = False,
_in_payload: bool = False,
) -> set[str]:
"""Extract entity IDs from action configuration."""
"""Extract entity IDs from action configuration.

Steps carrying ``enabled: false`` are skipped when ``include_disabled`` is
False. Extracting twice and taking the difference tells which entities a
configuration only references from steps that do not run.

``enabled`` only counts on list members, which is where steps, triggers and
conditions live, and never below a ``data`` key. Service data is arbitrary
payload: a dict or a list in there that happens to carry an ``enabled`` key
of its own must not hide the entities around it.
"""
entities = set()

if not config:
return entities

if isinstance(config, list):
for item in config:
entities.update(await async_extract_entities_from_action_config(hass, item))
entities.update(
await async_extract_entities_from_action_config(
hass,
item,
include_disabled=include_disabled,
_in_sequence=True,
_in_payload=_in_payload,
)
Comment thread
frenck marked this conversation as resolved.
Resolved
)
return entities

if not isinstance(config, dict):
return entities

if (
not include_disabled
and _in_sequence
and not _in_payload
and config.get(CONF_ENABLED) is False
):
return entities

# Extract entity IDs from direct fields
entities.update(await _extract_entities_from_action_fields(hass, config))

Expand All @@ -47,7 +80,11 @@ async def async_extract_entities_from_action_config(
entities.update(await _extract_entities_from_service_data(hass, config))

# Extract from nested configs (like if/then/else, repeat, etc.)
entities.update(await _extract_entities_from_nested_configs(hass, config))
entities.update(
await _extract_entities_from_nested_configs(
hass, config, include_disabled=include_disabled, in_payload=_in_payload
)
)

return entities

Expand Down Expand Up @@ -113,14 +150,23 @@ async def _extract_entities_from_service_data(


async def _extract_entities_from_nested_configs(
hass: HomeAssistant, config: dict[str, Any]
hass: HomeAssistant,
config: dict[str, Any],
*,
include_disabled: bool = True,
in_payload: bool = False,
) -> set[str]:
"""Extract entities from nested configurations."""
entities = set()
for value in config.values():
for key, value in config.items():
if isinstance(value, (dict, list)):
entities.update(
await async_extract_entities_from_action_config(hass, value)
await async_extract_entities_from_action_config(
hass,
value,
include_disabled=include_disabled,
_in_payload=in_payload or key == "data",
)
)
return entities

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ async def async_inspect(self) -> None:
# arm/disarm and so on. Those reference entities through structured
# config (target, entity_id, service data) rather than through Jinja,
# so the template extraction above does not see them.
#
# Extracting the actions twice separates references that a step
# carrying `enabled: false` is the only source of: those cannot
# break a run, so the report says so instead of listing them
# alongside the ones that can.
active = set(referenced)
for option in options.values():
# Only structured options can hold an action; a plain string
# option walks straight back out of the extractor.
Expand All @@ -88,18 +94,48 @@ async def async_inspect(self) -> None:
referenced |= await async_extract_entities_from_action_config(
self.hass, option
)
active |= await async_extract_entities_from_action_config(
self.hass, option, include_disabled=False
)

if unknown_entities := async_filter_known_entity_ids(
self.hass,
referenced,
known_entity_ids=known_entity_ids,
):
unknown_active = async_filter_known_entity_ids(
self.hass,
active,
known_entity_ids=known_entity_ids,
)
self.async_create_issue(
issue_id=entry.entry_id,
translation_placeholders={
"entities": async_describe_unknown_entities(
self.hass, sorted(unknown_entities)
),
"entities": self._describe(unknown_entities, unknown_active),
"helper": entry.title,
},
)

def _describe(self, unknown: set[str], unknown_active: set[str]) -> str:
"""Describe the unknown entities, qualifying the disabled-only ones.

An entity is only qualified when nothing that runs references it. A
Jinja template inside a disabled step is still seen by the template
extraction, so such a reference stays unqualified -- the report errs
towards saying too much rather than calling a live problem harmless.
"""
described = async_describe_unknown_entities(self.hass, sorted(unknown_active))
if disabled_only := unknown - unknown_active:
described = "\n".join(
part
for part in (
described,
async_describe_unknown_entities(
self.hass,
sorted(disabled_only),
note="only referenced from disabled steps",
),
)
if part
)
return described
14 changes: 12 additions & 2 deletions custom_components/spook/entity_suggestions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,27 @@
def async_describe_unknown_entities(
hass: HomeAssistant,
entity_ids: Iterable[str],
*,
note: str | None = None,
) -> str:
"""Return a bulleted, enriched description of unknown entity IDs."""
"""Return a bulleted, enriched description of unknown entity IDs.

A ``note`` is appended to every line, to qualify a group of entity IDs
that share something worth saying once per entry.
"""
entity_registry = er.async_get(hass)
deleted_by_entity_id = {
deleted.entity_id: deleted
for deleted in entity_registry.deleted_entities.values()
}
known_entity_ids = async_get_all_entity_ids(hass)
# Parenthesized, like the deleted-on and did-you-mean details below.
suffix = f" ({note})" if note else ""

return "\n".join(
f"- `{entity_id}`" + _detail(entity_id, deleted_by_entity_id, known_entity_ids)
f"- `{entity_id}`"
+ _detail(entity_id, deleted_by_entity_id, known_entity_ids)
+ suffix
for entity_id in entity_ids
)

Expand Down
Loading
Loading