From c012db477a8b78e8ab90bd547be26aba8640cc78 Mon Sep 17 00:00:00 2001 From: Frenckatron Date: Wed, 27 May 2026 23:21:30 +0200 Subject: [PATCH 1/6] Add unknown entity extractor tests --- tests/ectoplasms/automation/__init__.py | 1 + .../ectoplasms/automation/repairs/__init__.py | 1 + .../repairs/test_unknown_entity_references.py | 250 ++++++++++++++ tests/ectoplasms/lovelace/__init__.py | 1 + tests/ectoplasms/lovelace/repairs/__init__.py | 1 + .../repairs/test_unknown_entity_references.py | 320 ++++++++++++++++++ 6 files changed, 574 insertions(+) create mode 100644 tests/ectoplasms/automation/__init__.py create mode 100644 tests/ectoplasms/automation/repairs/__init__.py create mode 100644 tests/ectoplasms/automation/repairs/test_unknown_entity_references.py create mode 100644 tests/ectoplasms/lovelace/__init__.py create mode 100644 tests/ectoplasms/lovelace/repairs/__init__.py create mode 100644 tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py diff --git a/tests/ectoplasms/automation/__init__.py b/tests/ectoplasms/automation/__init__.py new file mode 100644 index 0000000000..19fa720380 --- /dev/null +++ b/tests/ectoplasms/automation/__init__.py @@ -0,0 +1 @@ +"""Tests for the Spook automation ectoplasm.""" diff --git a/tests/ectoplasms/automation/repairs/__init__.py b/tests/ectoplasms/automation/repairs/__init__.py new file mode 100644 index 0000000000..b92674ff5c --- /dev/null +++ b/tests/ectoplasms/automation/repairs/__init__.py @@ -0,0 +1 @@ +"""Tests for the Spook automation repairs.""" diff --git a/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py b/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py new file mode 100644 index 0000000000..224f1b1c81 --- /dev/null +++ b/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py @@ -0,0 +1,250 @@ +"""Golden-path tests for the automation entity-reference extractor. + +These tests pin down the observable behavior of the module-level extractors used +by ``SpookRepair`` in +``custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py`` +so the upcoming consolidation into a single recursive walker cannot regress them +silently. +""" + +# pylint: disable=wrong-import-order +from __future__ import annotations + +from typing import TYPE_CHECKING + +from custom_components.spook.ectoplasms.automation.repairs.unknown_entity_references import ( + extract_entities_from_action_config, + extract_entities_from_automation_config, + extract_entities_from_condition_config, + extract_entities_from_trigger_config, + extract_entities_from_value, +) +import pytest + +if TYPE_CHECKING: + from homeassistant.core import HomeAssistant + + +async def test_value_plain_entity_id(hass: HomeAssistant) -> None: + """A bare entity ID string is recognized as an entity reference.""" + assert await extract_entities_from_value(hass, "light.kitchen") == {"light.kitchen"} + + +async def test_value_unknown_domain_is_ignored(hass: HomeAssistant) -> None: + """Strings using an unknown domain are not treated as entity IDs.""" + assert await extract_entities_from_value(hass, "totally_made_up.kitchen") == set() + + +async def test_value_list_of_entity_ids(hass: HomeAssistant) -> None: + """A list of entity ID strings yields every valid entry.""" + result = await extract_entities_from_value( + hass, ["light.kitchen", "switch.lamp", "not_a_domain.foo"] + ) + assert result == {"light.kitchen", "switch.lamp"} + + +async def test_value_entity_dict_form(hass: HomeAssistant) -> None: + """``{"entity": "..."}`` dicts are unwrapped into their entity ID.""" + assert await extract_entities_from_value( + hass, {"entity": "sensor.temperature"} + ) == {"sensor.temperature"} + + +async def test_value_template_extracts_referenced_entity( + hass: HomeAssistant, +) -> None: + """Template strings have their referenced entity IDs extracted.""" + template = "{{ states('light.kitchen') }}" + assert await extract_entities_from_value(hass, template) == {"light.kitchen"} + + +async def test_value_non_string_non_collection_returns_empty( + hass: HomeAssistant, +) -> None: + """Numbers, booleans, and None yield no entities.""" + assert await extract_entities_from_value(hass, 42) == set() + assert await extract_entities_from_value(hass, None) == set() + value = True + assert await extract_entities_from_value(hass, value) == set() + + +async def test_trigger_state_entity_id(hass: HomeAssistant) -> None: + """A state trigger's ``entity_id`` is captured.""" + config = {"platform": "state", "entity_id": "binary_sensor.door"} + assert await extract_entities_from_trigger_config(hass, config) == { + "binary_sensor.door" + } + + +async def test_trigger_zone_field(hass: HomeAssistant) -> None: + """A zone trigger's ``zone`` field is captured.""" + config = { + "platform": "zone", + "entity_id": "person.alice", + "zone": "zone.home", + "event": "enter", + } + assert await extract_entities_from_trigger_config(hass, config) == { + "person.alice", + "zone.home", + } + + +async def test_trigger_list_of_triggers(hass: HomeAssistant) -> None: + """Lists of triggers are walked recursively.""" + config = [ + {"platform": "state", "entity_id": "light.kitchen"}, + {"platform": "state", "entity_id": ["switch.lamp", "switch.fan"]}, + ] + assert await extract_entities_from_trigger_config(hass, config) == { + "light.kitchen", + "switch.lamp", + "switch.fan", + } + + +async def test_trigger_empty_or_none_returns_empty(hass: HomeAssistant) -> None: + """Empty inputs produce no entities.""" + assert await extract_entities_from_trigger_config(hass, None) == set() + assert await extract_entities_from_trigger_config(hass, {}) == set() + assert await extract_entities_from_trigger_config(hass, []) == set() + + +async def test_condition_state_entity_id(hass: HomeAssistant) -> None: + """A state condition's ``entity_id`` is captured.""" + config = {"condition": "state", "entity_id": "switch.lamp", "state": "on"} + assert await extract_entities_from_condition_config(hass, config) == {"switch.lamp"} + + +async def test_condition_zone(hass: HomeAssistant) -> None: + """Zone conditions capture both the tracked entity and the zone.""" + config = { + "condition": "zone", + "entity_id": "person.alice", + "zone": "zone.home", + } + assert await extract_entities_from_condition_config(hass, config) == { + "person.alice", + "zone.home", + } + + +async def test_condition_nested_and(hass: HomeAssistant) -> None: + """An ``and`` condition recurses into its nested condition list.""" + config = { + "condition": "and", + "conditions": [ + {"condition": "state", "entity_id": "light.kitchen", "state": "on"}, + {"condition": "numeric_state", "entity_id": "sensor.temperature"}, + ], + } + assert await extract_entities_from_condition_config(hass, config) == { + "light.kitchen", + "sensor.temperature", + } + + +async def test_action_direct_entity_id(hass: HomeAssistant) -> None: + """A direct ``entity_id`` on an action is captured.""" + config = {"service": "light.turn_on", "entity_id": "light.kitchen"} + assert await extract_entities_from_action_config(hass, config) == {"light.kitchen"} + + +async def test_action_target_block(hass: HomeAssistant) -> None: + """``target.entity_id`` on an action is captured.""" + config = { + "service": "light.turn_on", + "target": {"entity_id": ["light.kitchen", "light.living_room"]}, + } + assert await extract_entities_from_action_config(hass, config) == { + "light.kitchen", + "light.living_room", + } + + +async def test_action_data_dict(hass: HomeAssistant) -> None: + """Entities buried inside ``data`` values are captured.""" + config = { + "service": "notify.notify", + "data": {"message": "hello", "target": "person.alice"}, + } + assert await extract_entities_from_action_config(hass, config) == {"person.alice"} + + +async def test_action_data_as_template_string(hass: HomeAssistant) -> None: + """A template string assigned directly to ``data`` is parsed.""" + config = { + "service": "notify.notify", + "data": "{{ states('sensor.temperature') }}", + } + assert await extract_entities_from_action_config(hass, config) == { + "sensor.temperature" + } + + +async def test_action_if_then_else_nested(hass: HomeAssistant) -> None: + """``if``/``then``/``else`` nested actions are walked.""" + config = { + "if": [{"condition": "state", "entity_id": "binary_sensor.door"}], + "then": [{"service": "light.turn_on", "target": {"entity_id": "light.hall"}}], + "else": [{"service": "light.turn_off", "target": {"entity_id": "light.hall"}}], + } + result = await extract_entities_from_action_config(hass, config) + assert {"binary_sensor.door", "light.hall"} <= result + + +async def test_action_list_of_actions(hass: HomeAssistant) -> None: + """A top-level list of actions is walked.""" + config = [ + {"service": "light.turn_on", "target": {"entity_id": "light.a"}}, + {"service": "switch.turn_on", "entity_id": "switch.b"}, + ] + assert await extract_entities_from_action_config(hass, config) == { + "light.a", + "switch.b", + } + + +async def test_automation_full_config(hass: HomeAssistant) -> None: + """A complete automation config yields entities from all three sections.""" + config = { + "alias": "Test", + "trigger": [{"platform": "state", "entity_id": "binary_sensor.motion"}], + "condition": [ + {"condition": "state", "entity_id": "input_boolean.guest", "state": "on"} + ], + "action": [ + {"service": "light.turn_on", "target": {"entity_id": "light.kitchen"}}, + ], + } + assert await extract_entities_from_automation_config(hass, config) == { + "binary_sensor.motion", + "input_boolean.guest", + "light.kitchen", + } + + +async def test_automation_non_dict_returns_empty(hass: HomeAssistant) -> None: + """A non-dict argument short-circuits to an empty set.""" + assert await extract_entities_from_automation_config(hass, []) == set() + assert await extract_entities_from_automation_config(hass, "not a dict") == set() + + +@pytest.mark.parametrize("section", ["trigger", "condition", "action"]) +async def test_automation_missing_sections(hass: HomeAssistant, section: str) -> None: + """Automations missing one of the three sections still extract from the rest.""" + config = { + "trigger": [{"platform": "state", "entity_id": "binary_sensor.t"}], + "condition": [ + {"condition": "state", "entity_id": "binary_sensor.c", "state": "on"} + ], + "action": [{"service": "light.turn_on", "entity_id": "light.a"}], + } + config.pop(section) + result = await extract_entities_from_automation_config(hass, config) + expected = { + "trigger": {"binary_sensor.c", "light.a"}, + "condition": {"binary_sensor.t", "light.a"}, + "action": {"binary_sensor.t", "binary_sensor.c"}, + }[section] + assert result == expected diff --git a/tests/ectoplasms/lovelace/__init__.py b/tests/ectoplasms/lovelace/__init__.py new file mode 100644 index 0000000000..83285eff9f --- /dev/null +++ b/tests/ectoplasms/lovelace/__init__.py @@ -0,0 +1 @@ +"""Tests for the Spook Lovelace ectoplasm.""" diff --git a/tests/ectoplasms/lovelace/repairs/__init__.py b/tests/ectoplasms/lovelace/repairs/__init__.py new file mode 100644 index 0000000000..a645a29e64 --- /dev/null +++ b/tests/ectoplasms/lovelace/repairs/__init__.py @@ -0,0 +1 @@ +"""Tests for the Spook Lovelace repairs.""" diff --git a/tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py b/tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py new file mode 100644 index 0000000000..9657a14402 --- /dev/null +++ b/tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py @@ -0,0 +1,320 @@ +"""Golden-path tests for the Lovelace entity-reference extractor. + +The dashboard walker in +``custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py`` +is the only place where Spook converts Lovelace YAML into a flat set of entity +IDs. These tests pin down its current behavior so the upcoming flattening into a +single recursive walker cannot regress it silently. + +The extraction methods are name-mangled private methods on ``SpookRepair``; +tests call them through the mangled attribute names, which is intentional — the +mission says "lock down the riskiest logic before any refactor". +""" + +# pylint: disable=protected-access,wrong-import-order +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from custom_components.spook.ectoplasms.lovelace.repairs.unknown_entity_references import ( + SpookRepair, +) +import pytest + +if TYPE_CHECKING: + from homeassistant.core import HomeAssistant + + +@pytest.fixture(name="repair") +def repair_fixture(hass: HomeAssistant) -> SpookRepair: + """Return a ``SpookRepair`` instance wired up to the test ``hass``.""" + return SpookRepair(hass) + + +def _extract(repair: SpookRepair, config: dict[str, Any]) -> set[str]: + """Call the name-mangled dashboard-level extractor.""" + return repair._SpookRepair__async_extract_entities(config) # noqa: SLF001 # type: ignore[attr-defined] + + +def _extract_card(repair: SpookRepair, config: dict[str, Any]) -> set[str]: + """Call the name-mangled card-level extractor.""" + return repair._SpookRepair__async_extract_entities_from_card(config) # noqa: SLF001 # type: ignore[attr-defined] + + +def _extract_badge(repair: SpookRepair, config: Any) -> set[str]: + """Call the name-mangled badge-level extractor.""" + return repair._SpookRepair__async_extract_entities_from_badge(config) # noqa: SLF001 # type: ignore[attr-defined] + + +def _extract_element(repair: SpookRepair, config: dict[str, Any]) -> set[str]: + """Call the name-mangled element-level extractor.""" + return repair._SpookRepair__async_extract_entities_from_element(config) # noqa: SLF001 # type: ignore[attr-defined] + + +def test_dashboard_with_no_views_returns_empty(repair: SpookRepair) -> None: + """A dashboard with no ``views`` key yields no entities.""" + assert _extract(repair, {}) == set() + + +def test_dashboard_non_dict_returns_empty(repair: SpookRepair) -> None: + """A non-dict config yields no entities.""" + assert _extract(repair, "not a dict") == set() # type: ignore[arg-type] + + +def test_dashboard_full_walk(repair: SpookRepair) -> None: + """Views, badges, cards, and sections are all walked.""" + config = { + "views": [ + { + "title": "Home", + "badges": [{"entity": "sensor.outside_temperature"}], + "cards": [{"type": "entity", "entity": "light.kitchen"}], + "sections": [{"cards": [{"type": "entity", "entity": "switch.lamp"}]}], + } + ] + } + assert _extract(repair, config) == { + "sensor.outside_temperature", + "light.kitchen", + "switch.lamp", + } + + +def test_card_single_entity_field(repair: SpookRepair) -> None: + """A card with a plain ``entity`` field is captured.""" + assert _extract_card(repair, {"type": "entity", "entity": "light.kitchen"}) == { + "light.kitchen" + } + + +def test_card_entities_list_mixed_forms(repair: SpookRepair) -> None: + """A card's ``entities`` list accepts strings and ``{"entity": ...}`` dicts.""" + config = { + "type": "entities", + "entities": [ + "light.kitchen", + {"entity": "switch.lamp"}, + {"entity": "sensor.temperature", "name": "Temp"}, + ], + } + assert _extract_card(repair, config) == { + "light.kitchen", + "switch.lamp", + "sensor.temperature", + } + + +def test_card_camera_image(repair: SpookRepair) -> None: + """The ``camera_image`` common field is captured.""" + assert _extract_card( + repair, {"type": "picture-entity", "camera_image": "camera.front"} + ) == {"camera.front"} + + +def test_card_nested_card_and_cards(repair: SpookRepair) -> None: + """``card`` (single) and ``cards`` (list) are both walked.""" + config = { + "type": "conditional", + "card": {"type": "entity", "entity": "light.kitchen"}, + "cards": [ + {"type": "entity", "entity": "switch.lamp"}, + {"type": "entity", "entity": "sensor.temperature"}, + ], + } + assert _extract_card(repair, config) == { + "light.kitchen", + "switch.lamp", + "sensor.temperature", + } + + +def test_card_tap_action_target(repair: SpookRepair) -> None: + """A ``tap_action`` with a target entity is captured.""" + config = { + "type": "button", + "tap_action": { + "action": "call-service", + "service": "light.toggle", + "target": {"entity_id": "light.kitchen"}, + }, + } + assert _extract_card(repair, config) == {"light.kitchen"} + + +def test_card_hold_action_service_data(repair: SpookRepair) -> None: + """A ``hold_action`` with service_data entities is captured.""" + config = { + "type": "button", + "hold_action": { + "action": "call-service", + "service": "light.turn_on", + "service_data": {"entity_id": ["light.kitchen", "light.living_room"]}, + }, + } + assert _extract_card(repair, config) == { + "light.kitchen", + "light.living_room", + } + + +def test_card_condition_entity(repair: SpookRepair) -> None: + """A card's ``condition.entity`` is captured.""" + config = { + "type": "conditional", + "condition": {"entity": "input_boolean.guest", "state": "on"}, + "card": {"type": "entity", "entity": "light.kitchen"}, + } + assert _extract_card(repair, config) == { + "input_boolean.guest", + "light.kitchen", + } + + +def test_card_visibility_conditions(repair: SpookRepair) -> None: + """A card's ``visibility`` list of conditions is captured.""" + config = { + "type": "entity", + "entity": "light.kitchen", + "visibility": [ + {"condition": "state", "entity": "input_boolean.guest", "state": "on"}, + ], + } + assert _extract_card(repair, config) == { + "light.kitchen", + "input_boolean.guest", + } + + +def test_card_header_and_footer(repair: SpookRepair) -> None: + """Header and footer common fields are captured.""" + config = { + "type": "entities", + "header": {"type": "picture", "camera_image": "camera.front"}, + "footer": {"type": "graph", "entity": "sensor.power"}, + "entities": ["light.kitchen"], + } + assert _extract_card(repair, config) == { + "camera.front", + "sensor.power", + "light.kitchen", + } + + +def test_card_picture_elements_walked(repair: SpookRepair) -> None: + """``elements`` on a picture-elements card are walked into.""" + config = { + "type": "picture-elements", + "elements": [ + {"type": "state-icon", "entity": "light.kitchen"}, + { + "type": "service-button", + "tap_action": { + "action": "call-service", + "service": "switch.toggle", + "target": {"entity_id": "switch.lamp"}, + }, + }, + ], + } + assert _extract_card(repair, config) == {"light.kitchen", "switch.lamp"} + + +def test_card_mushroom_chips(repair: SpookRepair) -> None: + """``chips`` on a mushroom chips card are walked and conditions captured.""" + config = { + "type": "custom:mushroom-chips-card", + "chips": [ + {"type": "entity", "entity": "sensor.temperature"}, + { + "type": "template", + "entity": "switch.lamp", + "conditions": [ + {"entity": "input_boolean.guest"}, + ], + }, + ], + } + assert _extract_card(repair, config) == { + "sensor.temperature", + "switch.lamp", + "input_boolean.guest", + } + + +def test_card_non_dict_returns_empty(repair: SpookRepair) -> None: + """A non-dict card config returns an empty set.""" + assert _extract_card(repair, "string-card") == set() # type: ignore[arg-type] + + +def test_badge_string_form(repair: SpookRepair) -> None: + """A bare string badge is treated as the entity itself.""" + assert _extract_badge(repair, "sensor.temperature") == {"sensor.temperature"} + + +def test_badge_entity_dict(repair: SpookRepair) -> None: + """A badge with an ``entity`` field is captured.""" + assert _extract_badge(repair, {"entity": "sensor.temperature"}) == { + "sensor.temperature" + } + + +def test_badge_entities_list(repair: SpookRepair) -> None: + """A badge with an ``entities`` list captures all forms.""" + config = { + "entities": [ + "sensor.a", + {"entity": "sensor.b"}, + ] + } + assert _extract_badge(repair, config) == {"sensor.a", "sensor.b"} + + +def test_badge_unknown_shape_returns_empty(repair: SpookRepair) -> None: + """An unrecognized badge shape yields an empty set.""" + assert _extract_badge(repair, {"foo": "bar"}) == set() + assert _extract_badge(repair, 42) == set() + + +def test_element_with_nested_elements(repair: SpookRepair) -> None: + """``elements`` nested inside an element are walked recursively.""" + config = { + "type": "state-badge", + "entity": "sensor.outside", + "elements": [ + {"type": "state-icon", "entity": "light.kitchen"}, + ], + } + assert _extract_element(repair, config) == { + "sensor.outside", + "light.kitchen", + } + + +def test_element_with_visibility(repair: SpookRepair) -> None: + """An element's ``visibility`` conditions contribute entities.""" + config = { + "type": "state-icon", + "entity": "light.kitchen", + "visibility": [ + {"condition": "state", "entity": "input_boolean.guest", "state": "on"}, + ], + } + assert _extract_element(repair, config) == { + "light.kitchen", + "input_boolean.guest", + } + + +def test_element_action_target(repair: SpookRepair) -> None: + """An element acting as its own action (``service_data``) contributes.""" + config = { + "type": "service-button", + "service": "switch.toggle", + "service_data": {"entity_id": "switch.lamp"}, + } + assert _extract_element(repair, config) == {"switch.lamp"} + + +def test_element_non_dict_returns_empty(repair: SpookRepair) -> None: + """A non-dict element returns an empty set.""" + assert _extract_element(repair, "not a dict") == set() # type: ignore[arg-type] From 92bd52d22992cb9a7fd04a314e2e7ba615b99e30 Mon Sep 17 00:00:00 2001 From: Frenckatron Date: Wed, 27 May 2026 23:30:06 +0200 Subject: [PATCH 2/6] Tighten nested action extractor assertion --- .../automation/repairs/test_unknown_entity_references.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py b/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py index 224f1b1c81..f3adf66a3c 100644 --- a/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py +++ b/tests/ectoplasms/automation/repairs/test_unknown_entity_references.py @@ -189,8 +189,10 @@ async def test_action_if_then_else_nested(hass: HomeAssistant) -> None: "then": [{"service": "light.turn_on", "target": {"entity_id": "light.hall"}}], "else": [{"service": "light.turn_off", "target": {"entity_id": "light.hall"}}], } - result = await extract_entities_from_action_config(hass, config) - assert {"binary_sensor.door", "light.hall"} <= result + assert await extract_entities_from_action_config(hass, config) == { + "binary_sensor.door", + "light.hall", + } async def test_action_list_of_actions(hass: HomeAssistant) -> None: From 8cd34d246ac9e66cb64ebf571e0fec03cfc0d45c Mon Sep 17 00:00:00 2001 From: Frenckatron Date: Wed, 20 May 2026 21:10:50 +0200 Subject: [PATCH 3/6] Extract base classes for unknown-reference repair boilerplate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ten repair modules ground out near-identical async_inspect bodies — six under ectoplasms/automation/repairs/unknown_*_references.py and four unknown_source.py files across switch_as_x, integration, utility_meter and trend. Each variant differed only in the registry queried, the attribute looked up on the entity, and a placeholder key. This pulls the boilerplate into two abstract bases on repairs.py: - AbstractSpookEntityComponentUnknownReferencesRepair walks an EntityComponent (DATA_INSTANCES) and exposes three hooks: _async_setup_inspection (cache known IDs once per cycle), _should_inspect_entity (defaults True, overridden for "skip disabled automations"), and _async_compute_unknown_references (per-entity lookup). The issue payload and debug logging are built once at the base. - AbstractSpookEntityPlatformUnknownSourceRepair walks an EntityPlatform (DATA_ENTITY_PLATFORM), optionally filtered to a single source_platform_domain, and asks subclasses only for the per-entity _get_source_entity_id. Net: ~440 lines deleted, ~155 of base infra added. The 10 leaf modules now read as the ~5 attributes that actually differentiate them. A side effect is that pylint's duplicate-code can be re-enabled without flooding the report. The four remaining pre-existing duplicates outside this mission's scope (person services pair, proximity repairs pair) carry a local pylint: disable=duplicate-code explaining the intent; min-similarity-lines is also bumped to 12 so trivial header overlap (imports, inspect_events sets) doesn't trigger. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../repairs/unknown_area_references.py | 64 +++----- .../repairs/unknown_device_references.py | 66 +++----- .../repairs/unknown_entity_references.py | 90 ++++------ .../repairs/unknown_floor_references.py | 64 +++----- .../repairs/unknown_label_references.py | 64 +++----- .../repairs/unknown_service_references.py | 68 +++----- .../integration/repairs/unknown_source.py | 54 ++---- .../person/services/add_device_tracker.py | 1 + .../person/services/remove_device_tracker.py | 1 + .../repairs/unknown_ignored_zones.py | 1 + .../repairs/unknown_tracked_entities.py | 1 + .../switch_as_x/repairs/unknown_source.py | 48 ++---- .../trend/repairs/unknown_source.py | 54 ++---- .../utility_meter/repairs/unknown_source.py | 54 ++---- custom_components/spook/repairs.py | 154 ++++++++++++++++++ pyproject.toml | 9 +- 16 files changed, 357 insertions(+), 436 deletions(-) diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py index 99bb01ffa8..84d537edb5 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py @@ -2,16 +2,19 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components import automation from homeassistant.helpers import area_registry as ar -from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent -from ....const import LOGGER -from ....repairs import AbstractSpookRepair +from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair from ....util import async_filter_known_area_ids, async_get_all_area_ids +if TYPE_CHECKING: + from typing import Any + -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityComponentUnknownReferencesRepair): """Spook repair tries to find unknown referenced areas in automations.""" domain = automation.DOMAIN @@ -22,44 +25,21 @@ class SpookRepair(AbstractSpookRepair): } inspect_on_reload = True - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - if self.domain not in self.hass.data[DATA_INSTANCES]: - return - - entity_component: EntityComponent[automation.AutomationEntity] = self.hass.data[ - DATA_INSTANCES - ][self.domain] + unavailable_entity_class = automation.UnavailableAutomationEntity + entity_label = "automation" + reference_label = "areas" + edit_url_pattern = "/config/automation/edit/{unique_id}" - LOGGER.debug("Spook is inspecting: %s", self.repair) + _known_area_ids: set[str] - known_area_ids = async_get_all_area_ids(self.hass) + async def _async_setup_inspection(self) -> None: + """Cache known area IDs for this inspection cycle.""" + self._known_area_ids = async_get_all_area_ids(self.hass) - for entity in entity_component.entities: - self.possible_issue_ids.add(entity.entity_id) - if not isinstance(entity, automation.UnavailableAutomationEntity) and ( - unknown_areas := async_filter_known_area_ids( - self.hass, - area_ids=entity.referenced_areas, - known_area_ids=known_area_ids, - ) - ): - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "areas": "\n".join(f"- `{area}`" for area in unknown_areas), - "automation": entity.name, - "edit": f"/config/automation/edit/{entity.unique_id}", - "entity_id": entity.entity_id, - }, - ) - LOGGER.debug( - ( - "Spook found unknown areas in %s " - "and created an issue for it; Areas: %s", - ), - entity.entity_id, - ", ".join(unknown_areas), - ) + async def _async_compute_unknown_references(self, entity: Any) -> set[str]: + """Return unknown area IDs referenced by ``entity``.""" + return async_filter_known_area_ids( + self.hass, + area_ids=entity.referenced_areas, + known_area_ids=self._known_area_ids, + ) diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py index 59060ea2b4..36fa33d184 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py @@ -2,16 +2,19 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components import automation from homeassistant.helpers import device_registry as dr -from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent -from ....const import LOGGER -from ....repairs import AbstractSpookRepair +from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair from ....util import async_filter_known_device_ids, async_get_all_device_ids +if TYPE_CHECKING: + from typing import Any + -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityComponentUnknownReferencesRepair): """Spook repair tries to find unknown referenced devices in automations.""" domain = automation.DOMAIN @@ -23,46 +26,21 @@ class SpookRepair(AbstractSpookRepair): inspect_config_entry_changed = True inspect_on_reload = True - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - if self.domain not in self.hass.data[DATA_INSTANCES]: - return - - entity_component: EntityComponent[automation.AutomationEntity] = self.hass.data[ - DATA_INSTANCES - ][self.domain] + unavailable_entity_class = automation.UnavailableAutomationEntity + entity_label = "automation" + reference_label = "devices" + edit_url_pattern = "/config/automation/edit/{unique_id}" - LOGGER.debug("Spook is inspecting: %s", self.repair) + _known_device_ids: set[str] - known_device_ids = async_get_all_device_ids(self.hass) + async def _async_setup_inspection(self) -> None: + """Cache known device IDs for this inspection cycle.""" + self._known_device_ids = async_get_all_device_ids(self.hass) - for entity in entity_component.entities: - self.possible_issue_ids.add(entity.entity_id) - if not isinstance(entity, automation.UnavailableAutomationEntity) and ( - unknown_devices := async_filter_known_device_ids( - self.hass, - device_ids=entity.referenced_devices, - known_device_ids=known_device_ids, - ) - ): - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "devices": "\n".join( - f"- `{device}`" for device in unknown_devices - ), - "automation": entity.name, - "edit": f"/config/automation/edit/{entity.unique_id}", - "entity_id": entity.entity_id, - }, - ) - LOGGER.debug( - ( - "Spook found unknown devices in %s " - "and created an issue for it; Areas: %s", - ), - entity.entity_id, - ", ".join(unknown_devices), - ) + async def _async_compute_unknown_references(self, entity: Any) -> set[str]: + """Return unknown device IDs referenced by ``entity``.""" + return async_filter_known_device_ids( + self.hass, + device_ids=entity.referenced_devices, + known_device_ids=self._known_device_ids, + ) diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py index 0c72a81b30..a3a8d860a9 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py @@ -8,10 +8,9 @@ from homeassistant.components import automation from homeassistant.const import EVENT_COMPONENT_LOADED from homeassistant.helpers import entity_registry as er -from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent from ....const import LOGGER -from ....repairs import AbstractSpookRepair +from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair from ....util import ( ENTITY_ID_PATTERN, async_extract_entities_from_config, @@ -259,7 +258,7 @@ async def extract_entities_from_value(hass: HomeAssistant, value: Any) -> set[st return entities -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityComponentUnknownReferencesRepair): """Spook repair tries to find unknown referenced entity in automations.""" domain = automation.DOMAIN @@ -271,67 +270,42 @@ class SpookRepair(AbstractSpookRepair): inspect_config_entry_changed = True inspect_on_reload = True - automatically_clean_up_issues = True + unavailable_entity_class = automation.UnavailableAutomationEntity + entity_label = "automation" + reference_label = "entities" + edit_url_pattern = "/config/automation/edit/{unique_id}" - async def async_inspect(self) -> None: - """Trigger a inspection.""" - if self.domain not in self.hass.data[DATA_INSTANCES]: - return + _known_entity_ids: set[str] - entity_component: EntityComponent[automation.AutomationEntity] = self.hass.data[ - DATA_INSTANCES - ][self.domain] - - LOGGER.debug("Spook is inspecting: %s", self.repair) - - known_entity_ids = async_get_all_entity_ids(self.hass, include_all_none=True) - - for entity in entity_component.entities: - self.possible_issue_ids.add(entity.entity_id) + async def _async_setup_inspection(self) -> None: + """Cache known entity IDs (including ALL/NONE) for this inspection cycle.""" + self._known_entity_ids = async_get_all_entity_ids( + self.hass, include_all_none=True + ) - # Skip disabled automations - if not entity.enabled: - continue + def _should_inspect_entity(self, entity: Any) -> bool: + """Skip disabled automations.""" + return entity.enabled - # Collect entities from multiple sources - all_entities = set(entity.referenced_entities) + async def _async_compute_unknown_references(self, entity: Any) -> set[str]: + """Return unknown entity IDs referenced by ``entity`` (incl. templates).""" + all_entities = set(entity.referenced_entities) - # Also extract entities directly from raw configuration if available - if hasattr(entity, "raw_config") and entity.raw_config: - config_entities = await extract_entities_from_automation_config( + # Also extract entities directly from raw configuration if available + if hasattr(entity, "raw_config") and entity.raw_config: + all_entities.update( + await extract_entities_from_automation_config( self.hass, entity.raw_config ) - all_entities.update(config_entities) - - # Extract entities from Template objects within the automation entity - template_entities = await extract_template_entities_from_automation_entity( - self.hass, entity ) - all_entities.update(template_entities) - if not isinstance(entity, automation.UnavailableAutomationEntity) and ( - unknown_entities := await async_filter_known_entity_ids_with_templates( - self.hass, - entity_ids=all_entities, - known_entity_ids=known_entity_ids, - ) - ): - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "entities": "\n".join( - f"- `{entity_id}`" for entity_id in unknown_entities - ), - "automation": entity.name, - "edit": f"/config/automation/edit/{entity.unique_id}", - "entity_id": entity.entity_id, - }, - ) - LOGGER.debug( - ( - "Spook found unknown entities in %s " - "and created an issue for it; Entities: %s", - ), - entity.entity_id, - ", ".join(unknown_entities), - ) + # Extract entities from Template objects within the automation entity + all_entities.update( + await extract_template_entities_from_automation_entity(self.hass, entity) + ) + + return await async_filter_known_entity_ids_with_templates( + self.hass, + entity_ids=all_entities, + known_entity_ids=self._known_entity_ids, + ) diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py index 04172b710c..3381d6958c 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py @@ -2,16 +2,19 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components import automation from homeassistant.helpers import floor_registry as fr -from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent -from ....const import LOGGER -from ....repairs import AbstractSpookRepair +from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair from ....util import async_filter_known_floor_ids, async_get_all_floor_ids +if TYPE_CHECKING: + from typing import Any + -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityComponentUnknownReferencesRepair): """Spook repair tries to find unknown referenced floors in automations.""" domain = automation.DOMAIN @@ -21,44 +24,21 @@ class SpookRepair(AbstractSpookRepair): } inspect_on_reload = True - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - if self.domain not in self.hass.data[DATA_INSTANCES]: - return - - entity_component: EntityComponent[automation.AutomationEntity] = self.hass.data[ - DATA_INSTANCES - ][self.domain] + unavailable_entity_class = automation.UnavailableAutomationEntity + entity_label = "automation" + reference_label = "floors" + edit_url_pattern = "/config/automation/edit/{unique_id}" - LOGGER.debug("Spook is inspecting: %s", self.repair) + _known_floor_ids: set[str] - known_floor_ids = async_get_all_floor_ids(self.hass) + async def _async_setup_inspection(self) -> None: + """Cache known floor IDs for this inspection cycle.""" + self._known_floor_ids = async_get_all_floor_ids(self.hass) - for entity in entity_component.entities: - self.possible_issue_ids.add(entity.entity_id) - if not isinstance(entity, automation.UnavailableAutomationEntity) and ( - unknown_floors := async_filter_known_floor_ids( - self.hass, - floor_ids=entity.referenced_floors, - known_floor_ids=known_floor_ids, - ) - ): - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "floors": "\n".join(f"- `{floor}`" for floor in unknown_floors), - "automation": entity.name, - "edit": f"/config/automation/edit/{entity.unique_id}", - "entity_id": entity.entity_id, - }, - ) - LOGGER.debug( - ( - "Spook found unknown floors in %s " - "and created an issue for it; Floors: %s", - ), - entity.entity_id, - ", ".join(unknown_floors), - ) + async def _async_compute_unknown_references(self, entity: Any) -> set[str]: + """Return unknown floor IDs referenced by ``entity``.""" + return async_filter_known_floor_ids( + self.hass, + floor_ids=entity.referenced_floors, + known_floor_ids=self._known_floor_ids, + ) diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py index 5c79d593de..4c5a9ccbcb 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py @@ -2,16 +2,19 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components import automation from homeassistant.helpers import label_registry as lr -from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent -from ....const import LOGGER -from ....repairs import AbstractSpookRepair +from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair from ....util import async_filter_known_label_ids, async_get_all_label_ids +if TYPE_CHECKING: + from typing import Any + -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityComponentUnknownReferencesRepair): """Spook repair tries to find unknown referenced labels in automations.""" domain = automation.DOMAIN @@ -21,44 +24,21 @@ class SpookRepair(AbstractSpookRepair): } inspect_on_reload = True - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - if self.domain not in self.hass.data[DATA_INSTANCES]: - return - - entity_component: EntityComponent[automation.AutomationEntity] = self.hass.data[ - DATA_INSTANCES - ][self.domain] + unavailable_entity_class = automation.UnavailableAutomationEntity + entity_label = "automation" + reference_label = "labels" + edit_url_pattern = "/config/automation/edit/{unique_id}" - LOGGER.debug("Spook is inspecting: %s", self.repair) + _known_label_ids: set[str] - known_label_ids = async_get_all_label_ids(self.hass) + async def _async_setup_inspection(self) -> None: + """Cache known label IDs for this inspection cycle.""" + self._known_label_ids = async_get_all_label_ids(self.hass) - for entity in entity_component.entities: - self.possible_issue_ids.add(entity.entity_id) - if not isinstance(entity, automation.UnavailableAutomationEntity) and ( - unknown_labels := async_filter_known_label_ids( - self.hass, - label_ids=entity.referenced_labels, - known_label_ids=known_label_ids, - ) - ): - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "labels": "\n".join(f"- `{label}`" for label in unknown_labels), - "automation": entity.name, - "edit": f"/config/automation/edit/{entity.unique_id}", - "entity_id": entity.entity_id, - }, - ) - LOGGER.debug( - ( - "Spook found unknown labels in %s " - "and created an issue for it; Labels: %s", - ), - entity.entity_id, - ", ".join(unknown_labels), - ) + async def _async_compute_unknown_references(self, entity: Any) -> set[str]: + """Return unknown label IDs referenced by ``entity``.""" + return async_filter_known_label_ids( + self.hass, + label_ids=entity.referenced_labels, + known_label_ids=self._known_label_ids, + ) diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py index 192eceabbf..4212172095 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py @@ -2,23 +2,26 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components import automation from homeassistant.const import ( EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, ) -from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent -from ....const import LOGGER -from ....repairs import AbstractSpookRepair +from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair from ....util import ( async_filter_known_services, async_find_services_in_sequence, async_get_all_services, ) +if TYPE_CHECKING: + from typing import Any + -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityComponentUnknownReferencesRepair): """Spook repair tries to find unknown referenced services in automations.""" domain = automation.DOMAIN @@ -31,48 +34,21 @@ class SpookRepair(AbstractSpookRepair): inspect_config_entry_changed = True inspect_on_reload = True - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - if self.domain not in self.hass.data[DATA_INSTANCES]: - return - - entity_component: EntityComponent[automation.AutomationEntity] = self.hass.data[ - DATA_INSTANCES - ][self.domain] - - LOGGER.debug("Spook is inspecting: %s", self.repair) - - known_services = async_get_all_services(self.hass) + unavailable_entity_class = automation.UnavailableAutomationEntity + entity_label = "automation" + reference_label = "services" + edit_url_pattern = "/config/automation/edit/{unique_id}" - for entity in entity_component.entities: - self.possible_issue_ids.add(entity.entity_id) + _known_services: set[str] - if isinstance(entity, automation.UnavailableAutomationEntity): - continue + async def _async_setup_inspection(self) -> None: + """Cache known services for this inspection cycle.""" + self._known_services = async_get_all_services(self.hass) - if unknown_services := async_filter_known_services( - self.hass, - services=async_find_services_in_sequence(entity.action_script.sequence), - known_services=known_services, - ): - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "services": "\n".join( - f"- `{service}`" for service in unknown_services - ), - "automation": entity.name, - "edit": f"/config/automation/edit/{entity.unique_id}", - "entity_id": entity.entity_id, - }, - ) - LOGGER.debug( - ( - "Spook found unknown action calls in %s " - "and created an issue for it; Actions: %s", - ), - entity.entity_id, - ", ".join(unknown_services), - ) + async def _async_compute_unknown_references(self, entity: Any) -> set[str]: + """Return unknown services called by ``entity``.""" + return async_filter_known_services( + self.hass, + services=async_find_services_in_sequence(entity.action_script.sequence), + known_services=self._known_services, + ) diff --git a/custom_components/spook/ectoplasms/integration/repairs/unknown_source.py b/custom_components/spook/ectoplasms/integration/repairs/unknown_source.py index d7277cb31e..55b16a159d 100644 --- a/custom_components/spook/ectoplasms/integration/repairs/unknown_source.py +++ b/custom_components/spook/ectoplasms/integration/repairs/unknown_source.py @@ -2,17 +2,19 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components import sensor from homeassistant.const import EVENT_COMPONENT_LOADED from homeassistant.helpers import entity_registry as er -from homeassistant.helpers.entity_platform import DATA_ENTITY_PLATFORM, EntityPlatform -from ....const import LOGGER -from ....repairs import AbstractSpookRepair -from ....util import async_get_all_entity_ids +from ....repairs import AbstractSpookEntityPlatformUnknownSourceRepair + +if TYPE_CHECKING: + from typing import Any -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityPlatformUnknownSourceRepair): """Spook repair tries to find unknown source entites for integration.""" domain = "integration" @@ -24,39 +26,9 @@ class SpookRepair(AbstractSpookRepair): inspect_config_entry_changed = True inspect_on_reload = "integration" - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - LOGGER.debug("Spook is inspecting: %s", self.repair) - - platforms: list[EntityPlatform] | None - if not (platforms := self.hass.data[DATA_ENTITY_PLATFORM].get(self.domain)): - return # Nothing to do. - - known_entity_ids = async_get_all_entity_ids(self.hass) - - for platform in platforms: - # We only care about the sensor domain - if platform.domain != sensor.DOMAIN: - continue - - for entity in platform.entities.values(): - self.possible_issue_ids.add(entity.entity_id) - # pylint: disable-next=protected-access - source = entity._sensor_source_id # noqa: SLF001 - if source not in known_entity_ids: - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "entity_id": entity.entity_id, - "helper": entity.name, - "source": source, - }, - ) - LOGGER.debug( - "Spook found unknown source entity %s in %s " - "and created an issue for it", - source, - entity.entity_id, - ) + source_platform_domain = sensor.DOMAIN + + def _get_source_entity_id(self, entity: Any) -> str: + """Return the integrating sensor's source entity ID.""" + # pylint: disable-next=protected-access + return entity._sensor_source_id # noqa: SLF001 diff --git a/custom_components/spook/ectoplasms/person/services/add_device_tracker.py b/custom_components/spook/ectoplasms/person/services/add_device_tracker.py index dbfebee83e..7ce55bf4ed 100644 --- a/custom_components/spook/ectoplasms/person/services/add_device_tracker.py +++ b/custom_components/spook/ectoplasms/person/services/add_device_tracker.py @@ -1,3 +1,4 @@ +# pylint: disable=duplicate-code # Mirrors remove_device_tracker by design. """Spook - Your homie.""" from __future__ import annotations diff --git a/custom_components/spook/ectoplasms/person/services/remove_device_tracker.py b/custom_components/spook/ectoplasms/person/services/remove_device_tracker.py index a37421abff..f2b7235cb7 100644 --- a/custom_components/spook/ectoplasms/person/services/remove_device_tracker.py +++ b/custom_components/spook/ectoplasms/person/services/remove_device_tracker.py @@ -1,3 +1,4 @@ +# pylint: disable=duplicate-code # Mirrors add_device_tracker by design. """Spook - Your homie.""" from __future__ import annotations diff --git a/custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py b/custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py index e375c34a7c..9ab6b8abc7 100644 --- a/custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py +++ b/custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py @@ -1,3 +1,4 @@ +# pylint: disable=duplicate-code # Mirrors unknown_tracked_entities by design. """Spook - Your homie.""" from __future__ import annotations diff --git a/custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py b/custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py index c710c0ed14..b042f4fd19 100644 --- a/custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py +++ b/custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py @@ -1,3 +1,4 @@ +# pylint: disable=duplicate-code # Mirrors unknown_ignored_zones by design. """Spook - Your homie.""" from __future__ import annotations diff --git a/custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py b/custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py index cb7bf36c37..a837d688bc 100644 --- a/custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py +++ b/custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py @@ -2,16 +2,18 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.const import EVENT_COMPONENT_LOADED from homeassistant.helpers import entity_registry as er -from homeassistant.helpers.entity_platform import DATA_ENTITY_PLATFORM, EntityPlatform -from ....const import LOGGER -from ....repairs import AbstractSpookRepair -from ....util import async_get_all_entity_ids +from ....repairs import AbstractSpookEntityPlatformUnknownSourceRepair + +if TYPE_CHECKING: + from typing import Any -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityPlatformUnknownSourceRepair): """Spook repair tries to find unknown source entites for switch_as_x.""" domain = "switch_as_x" @@ -22,35 +24,7 @@ class SpookRepair(AbstractSpookRepair): } inspect_config_entry_changed = "switch_as_x" - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - LOGGER.debug("Spook is inspecting: %s", self.repair) - - platforms: list[EntityPlatform] | None - if not (platforms := self.hass.data[DATA_ENTITY_PLATFORM].get(self.domain)): - return # Nothing to do, switch_as_x is not loaded - - known_entity_ids = async_get_all_entity_ids(self.hass) - - for platform in platforms: - for entity in platform.entities.values(): - self.possible_issue_ids.add(entity.entity_id) - # pylint: disable-next=protected-access - source = entity._switch_entity_id # noqa: SLF001 - if source not in known_entity_ids: - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "entity_id": entity.entity_id, - "helper": entity.name, - "source": source, - }, - ) - LOGGER.debug( - "Spook found unknown source entity %s in %s " - "and created an issue for it", - source, - entity.entity_id, - ) + def _get_source_entity_id(self, entity: Any) -> str: + """Return the wrapped switch's entity ID.""" + # pylint: disable-next=protected-access + return entity._switch_entity_id # noqa: SLF001 diff --git a/custom_components/spook/ectoplasms/trend/repairs/unknown_source.py b/custom_components/spook/ectoplasms/trend/repairs/unknown_source.py index 75a967ef3d..c577d20363 100644 --- a/custom_components/spook/ectoplasms/trend/repairs/unknown_source.py +++ b/custom_components/spook/ectoplasms/trend/repairs/unknown_source.py @@ -2,17 +2,19 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components import binary_sensor from homeassistant.const import EVENT_COMPONENT_LOADED from homeassistant.helpers import entity_registry as er -from homeassistant.helpers.entity_platform import DATA_ENTITY_PLATFORM, EntityPlatform -from ....const import LOGGER -from ....repairs import AbstractSpookRepair -from ....util import async_get_all_entity_ids +from ....repairs import AbstractSpookEntityPlatformUnknownSourceRepair + +if TYPE_CHECKING: + from typing import Any -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityPlatformUnknownSourceRepair): """Spook repair tries to find unknown source entites for trend sensors.""" domain = "trend" @@ -23,39 +25,9 @@ class SpookRepair(AbstractSpookRepair): } inspect_on_reload = "trend" - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - LOGGER.debug("Spook is inspecting: %s", self.repair) - - platforms: list[EntityPlatform] | None - if not (platforms := self.hass.data[DATA_ENTITY_PLATFORM].get(self.domain)): - return # Nothing to do. - - known_entity_ids = async_get_all_entity_ids(self.hass) - - for platform in platforms: - # We only care about the binary sensor domain - if platform.domain != binary_sensor.DOMAIN: - continue - - for entity in platform.entities.values(): - self.possible_issue_ids.add(entity.entity_id) - # pylint: disable-next=protected-access - source = entity._entity_id # noqa: SLF001 - if source not in known_entity_ids: - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "entity_id": entity.entity_id, - "helper": entity.name, - "source": source, - }, - ) - LOGGER.debug( - "Spook found unknown source entity %s in %s " - "and created an issue for it", - source, - entity.entity_id, - ) + source_platform_domain = binary_sensor.DOMAIN + + def _get_source_entity_id(self, entity: Any) -> str: + """Return the trend sensor's source entity ID.""" + # pylint: disable-next=protected-access + return entity._entity_id # noqa: SLF001 diff --git a/custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py b/custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py index 8d4d0e04f7..3c24fcf5c1 100644 --- a/custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py +++ b/custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py @@ -2,17 +2,19 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components import sensor from homeassistant.const import EVENT_COMPONENT_LOADED from homeassistant.helpers import entity_registry as er -from homeassistant.helpers.entity_platform import DATA_ENTITY_PLATFORM, EntityPlatform -from ....const import LOGGER -from ....repairs import AbstractSpookRepair -from ....util import async_get_all_entity_ids +from ....repairs import AbstractSpookEntityPlatformUnknownSourceRepair + +if TYPE_CHECKING: + from typing import Any -class SpookRepair(AbstractSpookRepair): +class SpookRepair(AbstractSpookEntityPlatformUnknownSourceRepair): """Spook repair tries to find unknown source entites for utility meters.""" domain = "utility_meter" @@ -23,39 +25,9 @@ class SpookRepair(AbstractSpookRepair): } inspect_on_reload = "utility_meter" - automatically_clean_up_issues = True - - async def async_inspect(self) -> None: - """Trigger a inspection.""" - LOGGER.debug("Spook is inspecting: %s", self.repair) - - platforms: list[EntityPlatform] | None - if not (platforms := self.hass.data[DATA_ENTITY_PLATFORM].get(self.domain)): - return # Nothing to do. - - known_entity_ids = async_get_all_entity_ids(self.hass) - - for platform in platforms: - # We only care about the sensor domain - if platform.domain != sensor.DOMAIN: - continue - - for entity in platform.entities.values(): - self.possible_issue_ids.add(entity.entity_id) - # pylint: disable-next=protected-access - source = entity._sensor_source_id # noqa: SLF001 - if source not in known_entity_ids: - self.async_create_issue( - issue_id=entity.entity_id, - translation_placeholders={ - "entity_id": entity.entity_id, - "helper": entity.name, - "source": source, - }, - ) - LOGGER.debug( - "Spook found unknown source entity %s in %s " - "and created an issue for it", - source, - entity.entity_id, - ) + source_platform_domain = sensor.DOMAIN + + def _get_source_entity_id(self, entity: Any) -> str: + """Return the utility-meter sensor's source entity ID.""" + # pylint: disable-next=protected-access + return entity._sensor_source_id # noqa: SLF001 diff --git a/custom_components/spook/repairs.py b/custom_components/spook/repairs.py index 2c453d2e16..28524fdc5d 100644 --- a/custom_components/spook/repairs.py +++ b/custom_components/spook/repairs.py @@ -25,15 +25,19 @@ ) from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.dispatcher import async_dispatcher_connect +from homeassistant.helpers.entity_component import DATA_INSTANCES +from homeassistant.helpers.entity_platform import DATA_ENTITY_PLATFORM from homeassistant.util.async_ import create_eager_task from .const import DOMAIN, LOGGER +from .util import async_get_all_entity_ids if TYPE_CHECKING: from collections.abc import Callable, Coroutine, Mapping from types import ModuleType from homeassistant.data_entry_flow import FlowResult + from homeassistant.helpers.entity_platform import EntityPlatform from homeassistant.util.event_type import EventType @@ -240,6 +244,156 @@ async def async_deactivate(self) -> None: await super().async_deactivate() +class AbstractSpookEntityComponentUnknownReferencesRepair(AbstractSpookRepair, ABC): + """Base class for repairs that find unknown references in component entities. + + Handles the shared boilerplate for inspecting entities loaded via + `EntityComponent` (e.g. automations, scripts): iterating the component's + entities, skipping unavailable ones, computing per-entity unknown references + via a subclass hook, and creating an issue with the standard translation + placeholders (````, ````, ``edit``, + ``entity_id``). + """ + + automatically_clean_up_issues = True + + #: Entity class representing an unavailable/broken instance. Entities of + #: this type are still tracked in ``possible_issue_ids`` but skipped during + #: issue creation. + unavailable_entity_class: type + + #: Translation placeholder key holding the entity's display name (e.g. + #: ``"automation"`` or ``"script"``). + entity_label: str + + #: Translation placeholder key holding the bulleted list of unknown + #: references (e.g. ``"areas"``, ``"floors"``, ``"entities"``). + reference_label: str + + #: Format string used to build the ``edit`` placeholder. Must contain a + #: ``{unique_id}`` field (e.g. ``"/config/automation/edit/{unique_id}"``). + edit_url_pattern: str + + async def _async_setup_inspection(self) -> None: + """Prepare per-inspection state (called once per inspection cycle). + + Override to cache lookups (e.g. known IDs from a registry) on ``self`` + for use during per-entity inspection. + """ + + # pylint: disable-next=unused-argument + def _should_inspect_entity(self, entity: Any) -> bool: # noqa: ARG002 + """Decide whether the given entity should be inspected. + + Defaults to inspecting every entity. Override (e.g. to skip disabled + entities) when needed. + """ + return True + + @abstractmethod + async def _async_compute_unknown_references(self, entity: Any) -> set[str]: + """Return the set of unknown referenced IDs for a single entity.""" + + async def async_inspect(self) -> None: + """Trigger an inspection.""" + if self.domain not in self.hass.data[DATA_INSTANCES]: + return + + entity_component = self.hass.data[DATA_INSTANCES][self.domain] + + LOGGER.debug("Spook is inspecting: %s", self.repair) + + await self._async_setup_inspection() + + for entity in entity_component.entities: + self.possible_issue_ids.add(entity.entity_id) + + if isinstance(entity, self.unavailable_entity_class): + continue + + if not self._should_inspect_entity(entity): + continue + + unknown = await self._async_compute_unknown_references(entity) + if not unknown: + continue + + self.async_create_issue( + issue_id=entity.entity_id, + translation_placeholders={ + self.reference_label: "\n".join(f"- `{item}`" for item in unknown), + self.entity_label: entity.name, + "edit": self.edit_url_pattern.format(unique_id=entity.unique_id), + "entity_id": entity.entity_id, + }, + ) + LOGGER.debug( + "Spook found unknown %s in %s and created an issue for it; %s: %s", + self.reference_label, + entity.entity_id, + self.reference_label.capitalize(), + ", ".join(unknown), + ) + + +class AbstractSpookEntityPlatformUnknownSourceRepair(AbstractSpookRepair, ABC): + """Base class for repairs that find unknown source entities on helpers. + + Handles the shared boilerplate for inspecting entities loaded via + `EntityPlatform` (e.g. ``switch_as_x``, ``integration``, ``utility_meter``, + ``trend``): walking the platforms, optionally filtering by platform domain, + pulling each entity's source attribute via a subclass hook, and raising an + issue when the source is no longer known to Home Assistant. + """ + + automatically_clean_up_issues = True + + #: When set, only entities living on platforms whose ``domain`` equals this + #: value are inspected. ``None`` (the default) inspects every platform of + #: the integration domain. + source_platform_domain: str | None = None + + @abstractmethod + def _get_source_entity_id(self, entity: Any) -> str: + """Return the source entity ID for the given helper entity.""" + + async def async_inspect(self) -> None: + """Trigger an inspection.""" + LOGGER.debug("Spook is inspecting: %s", self.repair) + + platforms: list[EntityPlatform] | None + if not (platforms := self.hass.data[DATA_ENTITY_PLATFORM].get(self.domain)): + return # Nothing to do, integration is not loaded. + + known_entity_ids = async_get_all_entity_ids(self.hass) + + for platform in platforms: + if ( + self.source_platform_domain is not None + and platform.domain != self.source_platform_domain + ): + continue + + for entity in platform.entities.values(): + self.possible_issue_ids.add(entity.entity_id) + source = self._get_source_entity_id(entity) + if source not in known_entity_ids: + self.async_create_issue( + issue_id=entity.entity_id, + translation_placeholders={ + "entity_id": entity.entity_id, + "helper": entity.name, + "source": source, + }, + ) + LOGGER.debug( + "Spook found unknown source entity %s in %s " + "and created an issue for it", + source, + entity.entity_id, + ) + + class AbstractSpookSingleShotRepairs(AbstractSpookRepairBase, ABC): """Abstract class to hold repairs that are single a shot.""" diff --git a/pyproject.toml b/pyproject.toml index 2926d2db22..aea17576c0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -106,11 +106,9 @@ combine-as-imports = true [tool.pylint."MESSAGES CONTROL"] # Reasons disabled: # format - handled by ruff -# duplicate-code - unavoidable # used-before-assignment - false positives with TYPE_CHECKING structures disable = [ "abstract-method", - "duplicate-code", "format", "unexpected-keyword-arg", "used-before-assignment", @@ -127,6 +125,13 @@ source = ["custom_components/spook"] [tool.coverage.report] show_missing = true +[tool.pylint.similarities] +# Trivial header overlap (imports, class skeletons, `inspect_events = {...}`) is +# inherent to Home Assistant ectoplasms and not worth deduplicating. +ignore-imports = true +ignore-signatures = true +min-similarity-lines = 12 + [tool.uv] environments = [ "python_full_version >= '3.14.2'", From cf7840463179116a98fa7673801fac62032e6aca Mon Sep 17 00:00:00 2001 From: Frenckatron Date: Wed, 27 May 2026 23:53:10 +0200 Subject: [PATCH 4/6] Stabilize unknown reference issue output --- .../ectoplasms/integration/repairs/unknown_source.py | 2 +- .../ectoplasms/switch_as_x/repairs/unknown_source.py | 2 +- .../spook/ectoplasms/trend/repairs/unknown_source.py | 2 +- .../ectoplasms/utility_meter/repairs/unknown_source.py | 2 +- custom_components/spook/repairs.py | 8 ++++++-- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/custom_components/spook/ectoplasms/integration/repairs/unknown_source.py b/custom_components/spook/ectoplasms/integration/repairs/unknown_source.py index 55b16a159d..fa05dfcdfa 100644 --- a/custom_components/spook/ectoplasms/integration/repairs/unknown_source.py +++ b/custom_components/spook/ectoplasms/integration/repairs/unknown_source.py @@ -15,7 +15,7 @@ class SpookRepair(AbstractSpookEntityPlatformUnknownSourceRepair): - """Spook repair tries to find unknown source entites for integration.""" + """Spook repair tries to find unknown source entities for integration.""" domain = "integration" repair = "integration_unknown_source" diff --git a/custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py b/custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py index a837d688bc..8e5f5404f9 100644 --- a/custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py +++ b/custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py @@ -14,7 +14,7 @@ class SpookRepair(AbstractSpookEntityPlatformUnknownSourceRepair): - """Spook repair tries to find unknown source entites for switch_as_x.""" + """Spook repair tries to find unknown source entities for switch_as_x.""" domain = "switch_as_x" repair = "switch_as_x_unknown_source" diff --git a/custom_components/spook/ectoplasms/trend/repairs/unknown_source.py b/custom_components/spook/ectoplasms/trend/repairs/unknown_source.py index c577d20363..8c31078a96 100644 --- a/custom_components/spook/ectoplasms/trend/repairs/unknown_source.py +++ b/custom_components/spook/ectoplasms/trend/repairs/unknown_source.py @@ -15,7 +15,7 @@ class SpookRepair(AbstractSpookEntityPlatformUnknownSourceRepair): - """Spook repair tries to find unknown source entites for trend sensors.""" + """Spook repair tries to find unknown source entities for trend sensors.""" domain = "trend" repair = "trend_unknown_source" diff --git a/custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py b/custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py index 3c24fcf5c1..89f7dabc48 100644 --- a/custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py +++ b/custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py @@ -15,7 +15,7 @@ class SpookRepair(AbstractSpookEntityPlatformUnknownSourceRepair): - """Spook repair tries to find unknown source entites for utility meters.""" + """Spook repair tries to find unknown source entities for utility meters.""" domain = "utility_meter" repair = "utility_meter_unknown_source" diff --git a/custom_components/spook/repairs.py b/custom_components/spook/repairs.py index 28524fdc5d..1dc9e2552c 100644 --- a/custom_components/spook/repairs.py +++ b/custom_components/spook/repairs.py @@ -318,10 +318,14 @@ async def async_inspect(self) -> None: if not unknown: continue + sorted_unknown = sorted(unknown) + self.async_create_issue( issue_id=entity.entity_id, translation_placeholders={ - self.reference_label: "\n".join(f"- `{item}`" for item in unknown), + self.reference_label: "\n".join( + f"- `{item}`" for item in sorted_unknown + ), self.entity_label: entity.name, "edit": self.edit_url_pattern.format(unique_id=entity.unique_id), "entity_id": entity.entity_id, @@ -332,7 +336,7 @@ async def async_inspect(self) -> None: self.reference_label, entity.entity_id, self.reference_label.capitalize(), - ", ".join(unknown), + ", ".join(sorted_unknown), ) From b7d9037ff3b0de317d47763e032bc85f2e2b7fd9 Mon Sep 17 00:00:00 2001 From: Frenckatron Date: Thu, 28 May 2026 01:08:48 +0200 Subject: [PATCH 5/6] Split util helpers into focused modules (#1277) Co-authored-by: Claude Opus 4.7 (1M context) --- custom_components/spook/__init__.py | 9 +- custom_components/spook/binary_sensor.py | 2 +- custom_components/spook/button.py | 2 +- .../repairs/unknown_area_references.py | 2 +- .../repairs/unknown_device_references.py | 2 +- .../repairs/unknown_entity_references.py | 4 +- .../repairs/unknown_floor_references.py | 2 +- .../repairs/unknown_label_references.py | 2 +- .../repairs/unknown_service_references.py | 4 +- .../group/repairs/unknown_members.py | 2 +- .../repairs/unknown_entity_references.py | 2 +- .../repairs/unknown_ignored_zones.py | 2 +- .../repairs/unknown_tracked_entities.py | 2 +- .../proximity/repairs/unknown_zone.py | 2 +- .../repairs/unknown_entity_references.py | 2 +- .../script/repairs/unknown_area_references.py | 2 +- .../repairs/unknown_device_references.py | 2 +- .../repairs/unknown_entity_references.py | 4 +- .../repairs/unknown_floor_references.py | 2 +- .../repairs/unknown_label_references.py | 2 +- .../spook/{util.py => entity_filtering.py} | 102 +----------------- custom_components/spook/event.py | 2 +- .../spook/integration_linking.py | 42 ++++++++ custom_components/spook/number.py | 2 +- custom_components/spook/repairs.py | 2 +- custom_components/spook/select.py | 2 +- custom_components/spook/sensor.py | 2 +- custom_components/spook/setup_helpers.py | 79 ++++++++++++++ custom_components/spook/switch.py | 2 +- custom_components/spook/time.py | 2 +- tests/test_util.py | 2 +- 31 files changed, 156 insertions(+), 136 deletions(-) rename custom_components/spook/{util.py => entity_filtering.py} (84%) create mode 100644 custom_components/spook/integration_linking.py create mode 100644 custom_components/spook/setup_helpers.py diff --git a/custom_components/spook/__init__.py b/custom_components/spook/__init__.py index 1abc79d6ce..739d350fdf 100644 --- a/custom_components/spook/__init__.py +++ b/custom_components/spook/__init__.py @@ -17,14 +17,11 @@ from homeassistant.helpers import issue_registry as ir from .const import DOMAIN, LOGGER, PLATFORMS +from .entity_filtering import async_setup_all_entity_ids_cache_invalidation +from .integration_linking import link_sub_integrations, unlink_sub_integrations from .repairs import SpookRepairManager from .services import SpookServiceManager -from .util import ( - async_forward_setup_entry, - async_setup_all_entity_ids_cache_invalidation, - link_sub_integrations, - unlink_sub_integrations, -) +from .setup_helpers import async_forward_setup_entry if TYPE_CHECKING: from collections.abc import Callable diff --git a/custom_components/spook/binary_sensor.py b/custom_components/spook/binary_sensor.py index 351b74f45d..1cbf2b7b0f 100644 --- a/custom_components/spook/binary_sensor.py +++ b/custom_components/spook/binary_sensor.py @@ -6,7 +6,7 @@ from homeassistant.const import Platform -from .util import async_forward_platform_entry_setups_to_ectoplasm +from .setup_helpers import async_forward_platform_entry_setups_to_ectoplasm if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry diff --git a/custom_components/spook/button.py b/custom_components/spook/button.py index 3dfa11e3b7..89e8cec390 100644 --- a/custom_components/spook/button.py +++ b/custom_components/spook/button.py @@ -6,7 +6,7 @@ from homeassistant.const import Platform -from .util import async_forward_platform_entry_setups_to_ectoplasm +from .setup_helpers import async_forward_platform_entry_setups_to_ectoplasm if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py index 84d537edb5..7bbb20eba3 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py @@ -7,8 +7,8 @@ from homeassistant.components import automation from homeassistant.helpers import area_registry as ar +from ....entity_filtering import async_filter_known_area_ids, async_get_all_area_ids from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair -from ....util import async_filter_known_area_ids, async_get_all_area_ids if TYPE_CHECKING: from typing import Any diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py index 36fa33d184..705a90c7bf 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py @@ -7,8 +7,8 @@ from homeassistant.components import automation from homeassistant.helpers import device_registry as dr +from ....entity_filtering import async_filter_known_device_ids, async_get_all_device_ids from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair -from ....util import async_filter_known_device_ids, async_get_all_device_ids if TYPE_CHECKING: from typing import Any diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py index a3a8d860a9..a34aeab60a 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py @@ -10,8 +10,7 @@ from homeassistant.helpers import entity_registry as er from ....const import LOGGER -from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair -from ....util import ( +from ....entity_filtering import ( ENTITY_ID_PATTERN, async_extract_entities_from_config, async_extract_entities_from_template_string, @@ -19,6 +18,7 @@ async_get_all_entity_ids, is_template_string, ) +from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair if TYPE_CHECKING: from homeassistant.core import HomeAssistant diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py index 3381d6958c..04a12c1aaa 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py @@ -7,8 +7,8 @@ from homeassistant.components import automation from homeassistant.helpers import floor_registry as fr +from ....entity_filtering import async_filter_known_floor_ids, async_get_all_floor_ids from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair -from ....util import async_filter_known_floor_ids, async_get_all_floor_ids if TYPE_CHECKING: from typing import Any diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py index 4c5a9ccbcb..faa8f78e10 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py @@ -7,8 +7,8 @@ from homeassistant.components import automation from homeassistant.helpers import label_registry as lr +from ....entity_filtering import async_filter_known_label_ids, async_get_all_label_ids from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair -from ....util import async_filter_known_label_ids, async_get_all_label_ids if TYPE_CHECKING: from typing import Any diff --git a/custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py b/custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py index 4212172095..593153ba6c 100644 --- a/custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py +++ b/custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py @@ -10,12 +10,12 @@ EVENT_SERVICE_REMOVED, ) -from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair -from ....util import ( +from ....entity_filtering import ( async_filter_known_services, async_find_services_in_sequence, async_get_all_services, ) +from ....repairs import AbstractSpookEntityComponentUnknownReferencesRepair if TYPE_CHECKING: from typing import Any diff --git a/custom_components/spook/ectoplasms/group/repairs/unknown_members.py b/custom_components/spook/ectoplasms/group/repairs/unknown_members.py index 30fb92d765..c2560d7f99 100644 --- a/custom_components/spook/ectoplasms/group/repairs/unknown_members.py +++ b/custom_components/spook/ectoplasms/group/repairs/unknown_members.py @@ -10,8 +10,8 @@ from homeassistant.helpers.entity_platform import DATA_ENTITY_PLATFORM, EntityPlatform from ....const import LOGGER +from ....entity_filtering import async_filter_known_entity_ids, async_get_all_entity_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_entity_ids, async_get_all_entity_ids class SpookRepair(AbstractSpookRepair): diff --git a/custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py b/custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py index b18ec8742b..8e1bbebadb 100644 --- a/custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py +++ b/custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py @@ -14,8 +14,8 @@ from homeassistant.helpers import entity_registry as er from ....const import LOGGER +from ....entity_filtering import async_filter_known_entity_ids, async_get_all_entity_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_entity_ids, async_get_all_entity_ids if TYPE_CHECKING: from homeassistant.components.lovelace.dashboard import ( diff --git a/custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py b/custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py index 9ab6b8abc7..4328cb6cfc 100644 --- a/custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py +++ b/custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py @@ -9,8 +9,8 @@ from homeassistant.helpers import entity_registry as er from ....const import LOGGER +from ....entity_filtering import async_filter_known_entity_ids, async_get_all_entity_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_entity_ids, async_get_all_entity_ids if TYPE_CHECKING: from homeassistant.components.proximity.coordinator import ( diff --git a/custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py b/custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py index b042f4fd19..f79604345b 100644 --- a/custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py +++ b/custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py @@ -9,8 +9,8 @@ from homeassistant.helpers import entity_registry as er from ....const import LOGGER +from ....entity_filtering import async_filter_known_entity_ids, async_get_all_entity_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_entity_ids, async_get_all_entity_ids if TYPE_CHECKING: from homeassistant.components.proximity.coordinator import ( diff --git a/custom_components/spook/ectoplasms/proximity/repairs/unknown_zone.py b/custom_components/spook/ectoplasms/proximity/repairs/unknown_zone.py index 744100c8af..27413774df 100644 --- a/custom_components/spook/ectoplasms/proximity/repairs/unknown_zone.py +++ b/custom_components/spook/ectoplasms/proximity/repairs/unknown_zone.py @@ -8,8 +8,8 @@ from homeassistant.helpers import entity_registry as er from ....const import LOGGER +from ....entity_filtering import async_get_all_entity_ids from ....repairs import AbstractSpookRepair -from ....util import async_get_all_entity_ids if TYPE_CHECKING: from homeassistant.components.proximity.coordinator import ( diff --git a/custom_components/spook/ectoplasms/scene/repairs/unknown_entity_references.py b/custom_components/spook/ectoplasms/scene/repairs/unknown_entity_references.py index 28949b38eb..09eb5f8881 100644 --- a/custom_components/spook/ectoplasms/scene/repairs/unknown_entity_references.py +++ b/custom_components/spook/ectoplasms/scene/repairs/unknown_entity_references.py @@ -8,8 +8,8 @@ from homeassistant.helpers import entity_registry as er from ....const import LOGGER +from ....entity_filtering import async_filter_known_entity_ids, async_get_all_entity_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_entity_ids, async_get_all_entity_ids if TYPE_CHECKING: from homeassistant.components.homeassistant import scene diff --git a/custom_components/spook/ectoplasms/script/repairs/unknown_area_references.py b/custom_components/spook/ectoplasms/script/repairs/unknown_area_references.py index c8fc732975..c36d452ac3 100644 --- a/custom_components/spook/ectoplasms/script/repairs/unknown_area_references.py +++ b/custom_components/spook/ectoplasms/script/repairs/unknown_area_references.py @@ -7,8 +7,8 @@ from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent from ....const import LOGGER +from ....entity_filtering import async_filter_known_area_ids, async_get_all_area_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_area_ids, async_get_all_area_ids class SpookRepair(AbstractSpookRepair): diff --git a/custom_components/spook/ectoplasms/script/repairs/unknown_device_references.py b/custom_components/spook/ectoplasms/script/repairs/unknown_device_references.py index 7c816e9b8c..3d2e7dc49c 100644 --- a/custom_components/spook/ectoplasms/script/repairs/unknown_device_references.py +++ b/custom_components/spook/ectoplasms/script/repairs/unknown_device_references.py @@ -7,8 +7,8 @@ from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent from ....const import LOGGER +from ....entity_filtering import async_filter_known_device_ids, async_get_all_device_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_device_ids, async_get_all_device_ids class SpookRepair(AbstractSpookRepair): diff --git a/custom_components/spook/ectoplasms/script/repairs/unknown_entity_references.py b/custom_components/spook/ectoplasms/script/repairs/unknown_entity_references.py index 1a43b4cb67..1fb67a360a 100644 --- a/custom_components/spook/ectoplasms/script/repairs/unknown_entity_references.py +++ b/custom_components/spook/ectoplasms/script/repairs/unknown_entity_references.py @@ -9,12 +9,12 @@ from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent -from ....repairs import AbstractSpookRepair -from ....util import ( +from ....entity_filtering import ( async_extract_entities_from_config, async_filter_known_entity_ids_with_templates, async_get_all_entity_ids, ) +from ....repairs import AbstractSpookRepair if TYPE_CHECKING: from homeassistant.core import HomeAssistant diff --git a/custom_components/spook/ectoplasms/script/repairs/unknown_floor_references.py b/custom_components/spook/ectoplasms/script/repairs/unknown_floor_references.py index 7b0029e996..620fe88c63 100644 --- a/custom_components/spook/ectoplasms/script/repairs/unknown_floor_references.py +++ b/custom_components/spook/ectoplasms/script/repairs/unknown_floor_references.py @@ -7,8 +7,8 @@ from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent from ....const import LOGGER +from ....entity_filtering import async_filter_known_floor_ids, async_get_all_floor_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_floor_ids, async_get_all_floor_ids class SpookRepair(AbstractSpookRepair): diff --git a/custom_components/spook/ectoplasms/script/repairs/unknown_label_references.py b/custom_components/spook/ectoplasms/script/repairs/unknown_label_references.py index cd616daef1..4d24aa18b0 100644 --- a/custom_components/spook/ectoplasms/script/repairs/unknown_label_references.py +++ b/custom_components/spook/ectoplasms/script/repairs/unknown_label_references.py @@ -7,8 +7,8 @@ from homeassistant.helpers.entity_component import DATA_INSTANCES, EntityComponent from ....const import LOGGER +from ....entity_filtering import async_filter_known_label_ids, async_get_all_label_ids from ....repairs import AbstractSpookRepair -from ....util import async_filter_known_label_ids, async_get_all_label_ids class SpookRepair(AbstractSpookRepair): diff --git a/custom_components/spook/util.py b/custom_components/spook/entity_filtering.py similarity index 84% rename from custom_components/spook/util.py rename to custom_components/spook/entity_filtering.py index 6aea27c34a..80a5a29f32 100644 --- a/custom_components/spook/util.py +++ b/custom_components/spook/entity_filtering.py @@ -1,10 +1,7 @@ -"""Spook - Your homie.""" +"""Spook - Your homie. Entity, registry, and template filtering helpers.""" from __future__ import annotations -import asyncio -import importlib -from pathlib import Path import re from typing import TYPE_CHECKING, Any @@ -38,15 +35,12 @@ ) from homeassistant.helpers.template import Template -from .const import DOMAIN, LOGGER +from .const import LOGGER if TYPE_CHECKING: from collections.abc import Callable, Iterable, Sequence - from types import ModuleType - from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant - from homeassistant.helpers.entity_platform import AddEntitiesCallback # Entity domains to ignore when filtering unknown entities @@ -223,98 +217,6 @@ def async_get_all_entity_ids( return _CACHED_ALL_ENTITY_IDS.copy() -async def async_forward_setup_entry( - hass: HomeAssistant, - entry: ConfigEntry, -) -> None: - """Set up Spook ectoplasms.""" - LOGGER.debug("Setting up Spook ectoplasms") - - modules: list[ModuleType] = [] - - def _load_all_ectoplasm_modules() -> None: - """Load all Spook ectoplasm modules.""" - for module_file in Path(__file__).parent.rglob("ectoplasms/*/__init__.py"): - module_path = str(module_file.relative_to(Path(__file__).parent))[ - :-3 - ].replace( - "/", - ".", - ) - LOGGER.debug("Loading Spook ectoplasm: %s", module_path) - module = importlib.import_module(f".{module_path}", __package__) - if hasattr(module, "async_setup_entry"): - modules.append(module) - LOGGER.debug("Setting up Spook ectoplasm: %s", module_path) - - await hass.async_add_import_executor_job(_load_all_ectoplasm_modules) - await asyncio.gather(*(module.async_setup_entry(hass, entry) for module in modules)) - - -async def async_forward_platform_entry_setups_to_ectoplasm( - hass: HomeAssistant, - entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - platform: Platform, -) -> None: - """Set up Spook ectoplasm platform.""" - LOGGER.debug("Setting up Spook ectoplasm platform: %s", platform) - - modules: list[ModuleType] = [] - - def _load_all_ectoplasm_platform_modules() -> None: - """Load all Spook ectoplasm platform modules.""" - for module_file in Path(__file__).parent.rglob(f"ectoplasms/*/{platform}.py"): - module_path = str(module_file.relative_to(Path(__file__).parent))[ - :-3 - ].replace( - "/", - ".", - ) - LOGGER.debug("Loading Spook %s from ectoplasm: %s", platform, module_path) - modules.append(importlib.import_module(f".{module_path}", __package__)) - LOGGER.debug("Setting up Spook ectoplasm %s: %s", platform, module_path) - - await hass.async_add_import_executor_job(_load_all_ectoplasm_platform_modules) - await asyncio.gather( - *( - module.async_setup_entry(hass, entry, async_add_entities) - for module in modules - ) - ) - - -def link_sub_integrations(hass: HomeAssistant) -> bool: - """Link Spook sub integrations.""" - LOGGER.debug("Linking up Spook sub integrations") - - changes = False - for manifest in Path(__file__).parent.rglob("integrations/*/manifest.json"): - LOGGER.debug("Linking Spook sub integration: %s", manifest.parent.name) - dest = Path(hass.config.config_dir) / "custom_components" / manifest.parent.name - if not dest.exists(): - src = ( - Path(hass.config.config_dir) - / "custom_components" - / DOMAIN - / "integrations" - / manifest.parent.name - ) - dest.symlink_to(src) - changes = True - return changes - - -def unlink_sub_integrations(hass: HomeAssistant) -> None: - """Unlink Spook sub integrations.""" - LOGGER.debug("Unlinking Spook sub integrations") - for manifest in Path(__file__).parent.rglob("integrations/*/manifest.json"): - LOGGER.debug("Unlinking Spook sub integration: %s", manifest.parent.name) - dest = Path(hass.config.config_dir) / "custom_components" / manifest.parent.name - if dest.exists(): - dest.unlink() - - @callback def async_get_all_area_ids(hass: HomeAssistant) -> set[str]: """Return all area IDs, known to Home Assistant.""" diff --git a/custom_components/spook/event.py b/custom_components/spook/event.py index b0c8d4f0a8..8314ce846d 100644 --- a/custom_components/spook/event.py +++ b/custom_components/spook/event.py @@ -6,7 +6,7 @@ from homeassistant.const import Platform -from .util import async_forward_platform_entry_setups_to_ectoplasm +from .setup_helpers import async_forward_platform_entry_setups_to_ectoplasm if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry diff --git a/custom_components/spook/integration_linking.py b/custom_components/spook/integration_linking.py new file mode 100644 index 0000000000..3b1303b23d --- /dev/null +++ b/custom_components/spook/integration_linking.py @@ -0,0 +1,42 @@ +"""Spook - Your homie. Sub-integration symlinking helpers.""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from .const import DOMAIN, LOGGER + +if TYPE_CHECKING: + from homeassistant.core import HomeAssistant + + +def link_sub_integrations(hass: HomeAssistant) -> bool: + """Link Spook sub integrations.""" + LOGGER.debug("Linking up Spook sub integrations") + + changes = False + for manifest in Path(__file__).parent.rglob("integrations/*/manifest.json"): + LOGGER.debug("Linking Spook sub integration: %s", manifest.parent.name) + dest = Path(hass.config.config_dir) / "custom_components" / manifest.parent.name + if not dest.exists(): + src = ( + Path(hass.config.config_dir) + / "custom_components" + / DOMAIN + / "integrations" + / manifest.parent.name + ) + dest.symlink_to(src) + changes = True + return changes + + +def unlink_sub_integrations(hass: HomeAssistant) -> None: + """Unlink Spook sub integrations.""" + LOGGER.debug("Unlinking Spook sub integrations") + for manifest in Path(__file__).parent.rglob("integrations/*/manifest.json"): + LOGGER.debug("Unlinking Spook sub integration: %s", manifest.parent.name) + dest = Path(hass.config.config_dir) / "custom_components" / manifest.parent.name + if dest.exists(): + dest.unlink() diff --git a/custom_components/spook/number.py b/custom_components/spook/number.py index c633d0acb8..d5a3a481db 100644 --- a/custom_components/spook/number.py +++ b/custom_components/spook/number.py @@ -6,7 +6,7 @@ from homeassistant.const import Platform -from .util import async_forward_platform_entry_setups_to_ectoplasm +from .setup_helpers import async_forward_platform_entry_setups_to_ectoplasm if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry diff --git a/custom_components/spook/repairs.py b/custom_components/spook/repairs.py index 1dc9e2552c..7464614d2e 100644 --- a/custom_components/spook/repairs.py +++ b/custom_components/spook/repairs.py @@ -30,7 +30,7 @@ from homeassistant.util.async_ import create_eager_task from .const import DOMAIN, LOGGER -from .util import async_get_all_entity_ids +from .entity_filtering import async_get_all_entity_ids if TYPE_CHECKING: from collections.abc import Callable, Coroutine, Mapping diff --git a/custom_components/spook/select.py b/custom_components/spook/select.py index 3a44052525..e9ead54fc7 100644 --- a/custom_components/spook/select.py +++ b/custom_components/spook/select.py @@ -6,7 +6,7 @@ from homeassistant.const import Platform -from .util import async_forward_platform_entry_setups_to_ectoplasm +from .setup_helpers import async_forward_platform_entry_setups_to_ectoplasm if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry diff --git a/custom_components/spook/sensor.py b/custom_components/spook/sensor.py index e1f30d90be..55cb0f6add 100644 --- a/custom_components/spook/sensor.py +++ b/custom_components/spook/sensor.py @@ -6,7 +6,7 @@ from homeassistant.const import Platform -from .util import async_forward_platform_entry_setups_to_ectoplasm +from .setup_helpers import async_forward_platform_entry_setups_to_ectoplasm if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry diff --git a/custom_components/spook/setup_helpers.py b/custom_components/spook/setup_helpers.py new file mode 100644 index 0000000000..56e19b360f --- /dev/null +++ b/custom_components/spook/setup_helpers.py @@ -0,0 +1,79 @@ +"""Spook - Your homie. Ectoplasm setup forwarding helpers.""" + +from __future__ import annotations + +import asyncio +import importlib +from pathlib import Path +from typing import TYPE_CHECKING + +from .const import LOGGER + +if TYPE_CHECKING: + from types import ModuleType + + from homeassistant.config_entries import ConfigEntry + from homeassistant.const import Platform + from homeassistant.core import HomeAssistant + from homeassistant.helpers.entity_platform import AddEntitiesCallback + + +async def async_forward_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, +) -> None: + """Set up Spook ectoplasms.""" + LOGGER.debug("Setting up Spook ectoplasms") + + modules: list[ModuleType] = [] + + def _load_all_ectoplasm_modules() -> None: + """Load all Spook ectoplasm modules.""" + for module_file in Path(__file__).parent.rglob("ectoplasms/*/__init__.py"): + module_path = str(module_file.relative_to(Path(__file__).parent))[ + :-3 + ].replace( + "/", + ".", + ) + LOGGER.debug("Loading Spook ectoplasm: %s", module_path) + module = importlib.import_module(f".{module_path}", __package__) + if hasattr(module, "async_setup_entry"): + modules.append(module) + LOGGER.debug("Setting up Spook ectoplasm: %s", module_path) + + await hass.async_add_import_executor_job(_load_all_ectoplasm_modules) + await asyncio.gather(*(module.async_setup_entry(hass, entry) for module in modules)) + + +async def async_forward_platform_entry_setups_to_ectoplasm( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, + platform: Platform, +) -> None: + """Set up Spook ectoplasm platform.""" + LOGGER.debug("Setting up Spook ectoplasm platform: %s", platform) + + modules: list[ModuleType] = [] + + def _load_all_ectoplasm_platform_modules() -> None: + """Load all Spook ectoplasm platform modules.""" + for module_file in Path(__file__).parent.rglob(f"ectoplasms/*/{platform}.py"): + module_path = str(module_file.relative_to(Path(__file__).parent))[ + :-3 + ].replace( + "/", + ".", + ) + LOGGER.debug("Loading Spook %s from ectoplasm: %s", platform, module_path) + modules.append(importlib.import_module(f".{module_path}", __package__)) + LOGGER.debug("Setting up Spook ectoplasm %s: %s", platform, module_path) + + await hass.async_add_import_executor_job(_load_all_ectoplasm_platform_modules) + await asyncio.gather( + *( + module.async_setup_entry(hass, entry, async_add_entities) + for module in modules + ) + ) diff --git a/custom_components/spook/switch.py b/custom_components/spook/switch.py index 77c486f16a..da13a01808 100644 --- a/custom_components/spook/switch.py +++ b/custom_components/spook/switch.py @@ -6,7 +6,7 @@ from homeassistant.const import Platform -from .util import async_forward_platform_entry_setups_to_ectoplasm +from .setup_helpers import async_forward_platform_entry_setups_to_ectoplasm if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry diff --git a/custom_components/spook/time.py b/custom_components/spook/time.py index 5e111e6bdd..b3049957fd 100644 --- a/custom_components/spook/time.py +++ b/custom_components/spook/time.py @@ -6,7 +6,7 @@ from homeassistant.const import Platform -from .util import async_forward_platform_entry_setups_to_ectoplasm +from .setup_helpers import async_forward_platform_entry_setups_to_ectoplasm if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry diff --git a/tests/test_util.py b/tests/test_util.py index 1851023fb3..eba0ea3f97 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -6,7 +6,7 @@ import pytest -from custom_components.spook.util import ( +from custom_components.spook.entity_filtering import ( extract_template_strings_from_config, is_template_string, split_comma_separated_entity_ids, From 2518b2bd997dfde4f5ef5c898bbcfc38f79e5e1c Mon Sep 17 00:00:00 2001 From: Frenckatron Date: Thu, 28 May 2026 01:21:51 +0200 Subject: [PATCH 6/6] Reset unknown repair issue tracking per inspection --- custom_components/spook/repairs.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/custom_components/spook/repairs.py b/custom_components/spook/repairs.py index 7464614d2e..77b6f2457f 100644 --- a/custom_components/spook/repairs.py +++ b/custom_components/spook/repairs.py @@ -296,10 +296,12 @@ async def _async_compute_unknown_references(self, entity: Any) -> set[str]: async def async_inspect(self) -> None: """Trigger an inspection.""" - if self.domain not in self.hass.data[DATA_INSTANCES]: + self.possible_issue_ids.clear() + + if self.domain not in (instances := self.hass.data.get(DATA_INSTANCES, {})): return - entity_component = self.hass.data[DATA_INSTANCES][self.domain] + entity_component = instances[self.domain] LOGGER.debug("Spook is inspecting: %s", self.repair) @@ -363,10 +365,14 @@ def _get_source_entity_id(self, entity: Any) -> str: async def async_inspect(self) -> None: """Trigger an inspection.""" + self.possible_issue_ids.clear() + LOGGER.debug("Spook is inspecting: %s", self.repair) platforms: list[EntityPlatform] | None - if not (platforms := self.hass.data[DATA_ENTITY_PLATFORM].get(self.domain)): + if not ( + platforms := self.hass.data.get(DATA_ENTITY_PLATFORM, {}).get(self.domain) + ): return # Nothing to do, integration is not loaded. known_entity_ids = async_get_all_entity_ids(self.hass)