Skip to content

Extract unknown reference repair base classes - #1276

Merged
frenck merged 6 commits into
mainfrom
refactor/unknown-reference-base
May 28, 2026
Merged

frenck merged 6 commits into
mainfrom
refactor/unknown-reference-base

Conversation

@frenckatron

Copy link
Copy Markdown
Collaborator

Description

Extract the repeated unknown-reference repair inspection loops into two abstract base classes in custom_components/spook/repairs.py.

The entity-component base handles the common DATA_INSTANCES walk, unavailable entity skip, issue payload, and debug logging. Automation repair modules now only provide the registry setup and per-entity unknown-reference lookup.

The entity-platform base handles the repeated DATA_ENTITY_PLATFORM source checks for integration, switch-as-x, trend, and utility meter repairs. Leaf modules now expose only the source entity attribute they need.

Motivation and Context

The affected repair modules were structurally identical, which made each change touch the same inspection boilerplate in several places. This keeps the behavior in one place and leaves the leaf modules focused on what differs.

This PR is stacked on #1275 so the automation unknown entity extractor tests are in place before the refactor.

How has this been tested?

  • uv run pytest -q
  • uv run ruff check custom_components/spook tests/ectoplasms/automation tests/ectoplasms/lovelace
  • uv run ruff format --check custom_components/spook tests/ectoplasms/automation tests/ectoplasms/lovelace
  • uv run pylint custom_components/spook

Screenshots (if appropriate):

Not applicable.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Other

Checklist

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.

@frenckatron frenckatron added the refactor Improvement of existing code, not introducing new features. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 76a51c36-6394-42a4-8b41-b9cd8752c904

📥 Commits

Reviewing files that changed from the base of the PR and between b7d9037 and 2518b2b.

📒 Files selected for processing (1)
  • custom_components/spook/repairs.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • custom_components/spook/repairs.py

📝 Walkthrough

Walkthrough

Spook repairs now use two new abstract bases for shared inspection and issue-creation flows; many repair modules switched to these hooks, entity-filtering helpers consolidated, dynamic setup forwarding moved to new helpers, integration linking utilities added, and extractor golden-path tests for automation and Lovelace were added.

Changes

Repair Refactoring & Infrastructure

Layer / File(s) Summary
Shared repair base classes
custom_components/spook/repairs.py
New AbstractSpookEntityComponentUnknownReferencesRepair and AbstractSpookEntityPlatformUnknownSourceRepair centralize inspection workflows, entity/platform iteration, and issue tracking.
Automation unknown-references repairs refactor
custom_components/spook/ectoplasms/automation/repairs/unknown_*.py
Six repairs (unknown_area_references, unknown_device_references, unknown_entity_references, unknown_floor_references, unknown_label_references, unknown_service_references) switched from manual async_inspect loops to abstract-base-class hooks with per-cycle caches and standardized metadata.
Automation entity-extraction test coverage
tests/ectoplasms/automation/repairs/test_unknown_entity_references.py, tests/ectoplasms/automation/*/__init__.py
Golden-path tests validating entity-ID extraction from automation config: raw values, triggers, conditions, actions, full configs, and template cases.
Entity-platform unknown-source repairs refactor
custom_components/spook/ectoplasms/*/repairs/unknown_source.py
Multiple repairs refactored from manual async_inspect implementations to AbstractSpookEntityPlatformUnknownSourceRepair, each declaring source_platform_domain and _get_source_entity_id.
Lovelace entity-extraction test coverage
tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py, tests/ectoplasms/lovelace/*/__init__.py
Comprehensive tests for Lovelace dashboard/card/badge/element entity extraction across nested structures and template-driven cases.
Linting configuration & duplicate-code handling
pyproject.toml, select mirrored modules
Pylint similarity detection added and duplicate-code removed from global disables; inline suppressions added to intentionally duplicated modules.
Dynamic setup forwarding helpers
custom_components/spook/setup_helpers.py
New functions to discover/import ectoplasm packages/platform modules and concurrently forward async_setup_entry and platform entry setups.
Entity filtering consolidation
custom_components/spook/entity_filtering.py
Centralizes entity/area/device/label/floor filtering helpers and trims unrelated setup/linking functions.
Integration linking helpers
custom_components/spook/integration_linking.py
New helpers to create/remove symlinks for packaged Spook sub-integrations in the user's custom_components directory.
Import wiring updates
custom_components/spook/*.py, custom_components/spook/*/*.py
Modules updated to import the new helper modules (entity_filtering, setup_helpers, integration_linking) instead of the consolidated util.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • frenck/spook#1275: Adds golden-path tests for automation entity extractor helpers referenced by this refactor.
  • frenck/spook#977: Related template-aware entity extraction work used by the refactored automation repair.
  • frenck/spook#1076: Related automation extractor adjustments affecting template/entity false-positives.

Suggested labels

maintenance

Suggested reviewers

  • frenck

Poem

🐰 I hopped through code both wide and deep,

Reused the bases, no more repeat.
Tests now guard each extractor's art,
Pylint watches, but we play smart.
A rabbit cheers: small changes, big leap!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and concisely summarizes the main change: extracting repeated unknown-reference repair inspection loops into abstract base classes.
Description check ✅ Passed The PR description is well-related to the changeset, explaining the motivation, implementation approach, and testing performed for the refactoring work.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/unknown-reference-base

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@frenckatron frenckatron mentioned this pull request May 27, 2026
2 of 7 tasks

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Refactors Spook’s “unknown reference/source” repair implementations by extracting shared inspection logic into two new abstract base classes, reducing repeated boilerplate across multiple ectoplasm repair modules. Also adjusts Pylint configuration to re-enable duplicate-code checking with tuned similarity settings and adds targeted per-file suppressions where duplication is intentional.

Changes:

  • Added AbstractSpookEntityComponentUnknownReferencesRepair and AbstractSpookEntityPlatformUnknownSourceRepair in custom_components/spook/repairs.py.
  • Refactored automation unknown-reference repairs and multiple helper unknown-source repairs to inherit from the new base classes.
  • Updated Pylint configuration for duplicate-code/similarity handling and added file-level duplicate-code disables for intentionally mirrored modules.

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
pyproject.toml Re-enables duplicate-code and configures Pylint similarities to reduce trivial overlap noise.
custom_components/spook/repairs.py Introduces two new abstract base classes consolidating entity-component and entity-platform repair inspection loops.
custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py Refactors to platform-based unknown-source base class; provides source attribute hook.
custom_components/spook/ectoplasms/trend/repairs/unknown_source.py Refactors to platform-based unknown-source base class; provides source attribute hook.
custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py Refactors to platform-based unknown-source base class; provides source attribute hook.
custom_components/spook/ectoplasms/integration/repairs/unknown_source.py Refactors to platform-based unknown-source base class; provides source attribute hook.
custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py Refactors to entity-component unknown-references base class; caches known services per inspection.
custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py Refactors to entity-component unknown-references base class; caches known labels per inspection.
custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py Refactors to entity-component unknown-references base class; caches known floors per inspection.
custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py Refactors to entity-component unknown-references base class; keeps custom extraction logic + per-inspection entity cache.
custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py Refactors to entity-component unknown-references base class; caches known devices per inspection.
custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py Refactors to entity-component unknown-references base class; caches known areas per inspection.
custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py Adds file-level duplicate-code suppression to document intentional mirroring.
custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py Adds file-level duplicate-code suppression to document intentional mirroring.
custom_components/spook/ectoplasms/person/services/add_device_tracker.py Adds file-level duplicate-code suppression to document intentional mirroring.
custom_components/spook/ectoplasms/person/services/remove_device_tracker.py Adds file-level duplicate-code suppression to document intentional mirroring.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread custom_components/spook/repairs.py Resolved
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) <noreply@anthropic.com>
@frenckatron
frenckatron force-pushed the refactor/unknown-reference-base branch from 66b1a36 to 8cd34d2 Compare May 27, 2026 21:43
Base automatically changed from test/unknown-entity-extractor-tests to main May 27, 2026 21:50
@codecov-commenter

codecov-commenter commented May 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 29.78723% with 165 lines in your changes missing coverage. Please review.
✅ Project coverage is 47.83%. Comparing base (4adf17f) to head (2518b2b).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
custom_components/spook/repairs.py 37.73% 33 Missing ⚠️
...asms/automation/repairs/unknown_area_references.py 0.00% 13 Missing ⚠️
...ms/automation/repairs/unknown_device_references.py 0.00% 13 Missing ⚠️
...sms/automation/repairs/unknown_floor_references.py 0.00% 13 Missing ⚠️
...sms/automation/repairs/unknown_label_references.py 0.00% 13 Missing ⚠️
...s/automation/repairs/unknown_service_references.py 0.00% 13 Missing ⚠️
custom_components/spook/setup_helpers.py 56.66% 12 Missing and 1 partial ⚠️
...ms/automation/repairs/unknown_entity_references.py 61.11% 7 Missing ⚠️
custom_components/spook/integration_linking.py 68.18% 6 Missing and 1 partial ⚠️
...k/ectoplasms/integration/repairs/unknown_source.py 0.00% 6 Missing ⚠️
... and 20 more
Additional details and impacted files
@@             Coverage Diff             @@
##             main    #1276       +/-   ##
===========================================
+ Coverage   36.84%   47.83%   +10.99%     
===========================================
  Files         117      119        +2     
  Lines        3029     3008       -21     
  Branches      411      382       -29     
===========================================
+ Hits         1116     1439      +323     
+ Misses       1898     1531      -367     
- Partials       15       38       +23     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py (1)

14-22: ⚡ Quick win

Fix import order instead of suppressing the warning.

The wrong-import-order disable is currently necessary because pytest (third-party) is imported after custom_components (local). Standard Python import order places third-party imports before local imports.

♻️ Reorder imports to match PEP 8 convention
-# pylint: disable=protected-access,wrong-import-order
+# pylint: disable=protected-access
 from __future__ import annotations
 
 from typing import TYPE_CHECKING, Any
 
+import pytest
+
 from custom_components.spook.ectoplasms.lovelace.repairs.unknown_entity_references import (
     SpookRepair,
 )
-import pytest
 
 if TYPE_CHECKING:
     from homeassistant.core import HomeAssistant
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py` around
lines 14 - 22, The import order in the test file is wrong: move third-party
imports (pytest) before local package imports (custom_components...), e.g.,
reorder so typing/TYPE_CHECKING remain first, then pytest, then the local from
custom_components.spook... import SpookRepair; after reordering remove the
now-unnecessary "wrong-import-order" from the pylint disable comment while
keeping any other needed disables like "protected-access". Ensure the import
grouping follows stdlib -> third-party -> local convention.
custom_components/spook/repairs.py (1)

299-300: ⚡ Quick win

Downgrade the KeyError concern to a defensive/optional improvement for custom_components/spook/repairs.py.

  • Repairs are scheduled only after EVENT_HOMEASSISTANT_STARTED in custom_components/spook/__init__.py, and Home Assistant initializes the DATA_INSTANCES / DATA_ENTITY_PLATFORM containers as entity components/platforms register—so the “integration not loaded” early-returns already cover the common missing-domain case without a crash.
  • Using hass.data.get(..., {}) is still a safe defensive tweak for unusual startup/test states, but this isn’t a clear correctness bug confined to these two inspectors (other Spook code also indexes these HassKeys directly).
Suggested fix (defensive)
     async def async_inspect(self) -> None:
         """Trigger an inspection."""
-        if self.domain not in self.hass.data[DATA_INSTANCES]:
+        if self.domain not in self.hass.data.get(DATA_INSTANCES, {}):
             return

         entity_component = self.hass.data[DATA_INSTANCES][self.domain]
@@
     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)):
+        if not (
+            platforms := self.hass.data.get(DATA_ENTITY_PLATFORM, {}).get(self.domain)
+        ):
             return  # Nothing to do, integration is not loaded.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@custom_components/spook/repairs.py` around lines 299 - 300, The current check
indexes hass.data directly and can raise KeyError in rare startup/test states;
change the guard to use safe dict access like self.hass.data.get(DATA_INSTANCES,
{}) when checking membership (i.e., replace "if self.domain not in
self.hass.data[DATA_INSTANCES]" with a check against
self.hass.data.get(DATA_INSTANCES, {})). Do the same defensive pattern for any
similar lookups (e.g., DATA_ENTITY_PLATFORM) in repairs.py so self.domain
membership tests never assume the top-level keys exist.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@custom_components/spook/repairs.py`:
- Around line 297-309: Reset self.possible_issue_ids at the start of each
inspection: inside async_inspect (and the other inspector async_inspect
implementation in this file) call self.possible_issue_ids.clear() (or assign a
new set) immediately before _async_setup_inspection so previous/stale entity IDs
are not retained between runs; keep the rest of the logic that populates
possible_issue_ids unchanged.

---

Nitpick comments:
In `@custom_components/spook/repairs.py`:
- Around line 299-300: The current check indexes hass.data directly and can
raise KeyError in rare startup/test states; change the guard to use safe dict
access like self.hass.data.get(DATA_INSTANCES, {}) when checking membership
(i.e., replace "if self.domain not in self.hass.data[DATA_INSTANCES]" with a
check against self.hass.data.get(DATA_INSTANCES, {})). Do the same defensive
pattern for any similar lookups (e.g., DATA_ENTITY_PLATFORM) in repairs.py so
self.domain membership tests never assume the top-level keys exist.

In `@tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py`:
- Around line 14-22: The import order in the test file is wrong: move
third-party imports (pytest) before local package imports
(custom_components...), e.g., reorder so typing/TYPE_CHECKING remain first, then
pytest, then the local from custom_components.spook... import SpookRepair; after
reordering remove the now-unnecessary "wrong-import-order" from the pylint
disable comment while keeping any other needed disables like "protected-access".
Ensure the import grouping follows stdlib -> third-party -> local convention.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c8a6e78e-bbc6-424b-92ab-b50c20e3bf21

📥 Commits

Reviewing files that changed from the base of the PR and between e36c3e2 and cf78404.

📒 Files selected for processing (22)
  • custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py
  • custom_components/spook/ectoplasms/integration/repairs/unknown_source.py
  • custom_components/spook/ectoplasms/person/services/add_device_tracker.py
  • custom_components/spook/ectoplasms/person/services/remove_device_tracker.py
  • custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py
  • custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py
  • custom_components/spook/ectoplasms/switch_as_x/repairs/unknown_source.py
  • custom_components/spook/ectoplasms/trend/repairs/unknown_source.py
  • custom_components/spook/ectoplasms/utility_meter/repairs/unknown_source.py
  • custom_components/spook/repairs.py
  • pyproject.toml
  • tests/ectoplasms/automation/__init__.py
  • tests/ectoplasms/automation/repairs/__init__.py
  • tests/ectoplasms/automation/repairs/test_unknown_entity_references.py
  • tests/ectoplasms/lovelace/__init__.py
  • tests/ectoplasms/lovelace/repairs/__init__.py
  • tests/ectoplasms/lovelace/repairs/test_unknown_entity_references.py

Comment thread custom_components/spook/repairs.py Resolved
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
custom_components/spook/repairs.py (2)

368-370: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Same KeyError risk on DATA_ENTITY_PLATFORM access.

Consistent with the other base class, use .get() to avoid KeyError.

Proposed fix
-        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.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@custom_components/spook/repairs.py` around lines 368 - 370, The code risks a
KeyError by indexing self.hass.data[DATA_ENTITY_PLATFORM]; change the lookup to
safely call self.hass.data.get(DATA_ENTITY_PLATFORM, {}) before calling
.get(self.domain) so platforms is assigned from
self.hass.data.get(DATA_ENTITY_PLATFORM, {}).get(self.domain) (preserving the
current platforms variable and type annotation) in the same method where
DATA_ENTITY_PLATFORM, self.hass.data and self.domain are referenced.

299-302: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Potential KeyError if DATA_INSTANCES is not yet populated.

Direct indexing hass.data[DATA_INSTANCES] will raise KeyError if the key doesn't exist. Using .get() is safer.

Proposed fix
     async def async_inspect(self) -> None:
         """Trigger an inspection."""
-        if self.domain not in self.hass.data[DATA_INSTANCES]:
+        if self.domain not in self.hass.data.get(DATA_INSTANCES, {}):
             return
 
-        entity_component = self.hass.data[DATA_INSTANCES][self.domain]
+        entity_component = self.hass.data.get(DATA_INSTANCES, {}).get(self.domain)
+        if entity_component is None:
+            return
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@custom_components/spook/repairs.py` around lines 299 - 302, The code directly
indexes self.hass.data[DATA_INSTANCES] which can raise KeyError if
DATA_INSTANCES isn't present; change the lookup to use
self.hass.data.get(DATA_INSTANCES) and guard for None before checking domain
membership and assigning entity_component (i.e., retrieve instances =
self.hass.data.get(DATA_INSTANCES); if not instances or self.domain not in
instances: return; entity_component = instances[self.domain]) so you avoid
KeyError while still using the existing symbols self.domain, self.hass.data,
DATA_INSTANCES and entity_component.
custom_components/spook/entity_filtering.py (1)

309-310: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Bug: async_filter_known_floor_ids calls async_get_all_label_ids instead of async_get_all_floor_ids.

This will cause floor filtering to incorrectly use label IDs as the known set, leading to false positives for unknown floors.

Proposed fix
     if known_floor_ids is None:
-        known_floor_ids = async_get_all_label_ids(hass)
+        known_floor_ids = async_get_all_floor_ids(hass)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@custom_components/spook/entity_filtering.py` around lines 309 - 310, The
function async_filter_known_floor_ids currently populates known_floor_ids by
calling async_get_all_label_ids; change that to call async_get_all_floor_ids
instead (and await it if async) so the known_floor_ids set comes from floor IDs
not label IDs; update the single line using async_get_all_label_ids(hass) to
async_get_all_floor_ids(hass) (or await async_get_all_floor_ids(hass) if the
caller is async) to ensure correct floor filtering.
🧹 Nitpick comments (1)
custom_components/spook/setup_helpers.py (1)

33-38: 💤 Low value

Path separator is hardcoded to /; may fail on Windows.

Path.relative_to() returns OS-native separators. On Windows this would be \, causing the module path construction to fail. Consider using parts or pathlib.PurePosixPath.

Portable alternative
-            module_path = str(module_file.relative_to(Path(__file__).parent))[
-                :-3
-            ].replace(
-                "/",
-                ".",
-            )
+            relative = module_file.relative_to(Path(__file__).parent)
+            # Remove .py suffix and join parts with dots
+            module_path = ".".join(relative.with_suffix("").parts)

Also applies to lines 63-68.

Also applies to: 63-68

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@custom_components/spook/setup_helpers.py` around lines 33 - 38, The
module_path construction hardcodes "/" and slices off the ".py", which breaks on
Windows; update the logic that builds module_path from
module_file.relative_to(...) to use a POSIX-safe conversion (e.g., call
.with_suffix("") and .as_posix() or wrap the relative path in
pathlib.PurePosixPath) and then replace "/" with "." (or split on "/" and join
with ".") to produce the dotted module path; apply the same fix for the other
occurrence that builds module_path (the block around the
module_file.relative_to(...) usage at lines 63-68) so both places use
OS-independent path-to-module conversion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@custom_components/spook/integration_linking.py`:
- Around line 21-31: The symlink creation currently checks dest.exists() which
returns False for broken symlinks and so dest.symlink_to(src) can raise
FileExistsError; update the logic in integration_linking.py around the dest
variable and manifest.parent.name so you first check dest.is_symlink() and if it
is a symlink but not dest.exists() remove/unlink that stale symlink, then create
the new symlink; also handle the case where dest exists and is not a symlink
(skip or log) to avoid clobbering real files.
- Around line 40-42: The code currently unconditionally calls dest.unlink()
which will raise IsADirectoryError if dest is a real directory; change the
removal to only unlink when dest.is_symlink() is True. Update the block that
computes dest (Path(hass.config.config_dir) / "custom_components" /
manifest.parent.name) to check dest.exists() and dest.is_symlink() before
calling dest.unlink(), and leave non-symlink directories untouched (do not
attempt unlink or rmtree).

---

Outside diff comments:
In `@custom_components/spook/entity_filtering.py`:
- Around line 309-310: The function async_filter_known_floor_ids currently
populates known_floor_ids by calling async_get_all_label_ids; change that to
call async_get_all_floor_ids instead (and await it if async) so the
known_floor_ids set comes from floor IDs not label IDs; update the single line
using async_get_all_label_ids(hass) to async_get_all_floor_ids(hass) (or await
async_get_all_floor_ids(hass) if the caller is async) to ensure correct floor
filtering.

In `@custom_components/spook/repairs.py`:
- Around line 368-370: The code risks a KeyError by indexing
self.hass.data[DATA_ENTITY_PLATFORM]; change the lookup to safely call
self.hass.data.get(DATA_ENTITY_PLATFORM, {}) before calling .get(self.domain) so
platforms is assigned from self.hass.data.get(DATA_ENTITY_PLATFORM,
{}).get(self.domain) (preserving the current platforms variable and type
annotation) in the same method where DATA_ENTITY_PLATFORM, self.hass.data and
self.domain are referenced.
- Around line 299-302: The code directly indexes self.hass.data[DATA_INSTANCES]
which can raise KeyError if DATA_INSTANCES isn't present; change the lookup to
use self.hass.data.get(DATA_INSTANCES) and guard for None before checking domain
membership and assigning entity_component (i.e., retrieve instances =
self.hass.data.get(DATA_INSTANCES); if not instances or self.domain not in
instances: return; entity_component = instances[self.domain]) so you avoid
KeyError while still using the existing symbols self.domain, self.hass.data,
DATA_INSTANCES and entity_component.

---

Nitpick comments:
In `@custom_components/spook/setup_helpers.py`:
- Around line 33-38: The module_path construction hardcodes "/" and slices off
the ".py", which breaks on Windows; update the logic that builds module_path
from module_file.relative_to(...) to use a POSIX-safe conversion (e.g., call
.with_suffix("") and .as_posix() or wrap the relative path in
pathlib.PurePosixPath) and then replace "/" with "." (or split on "/" and join
with ".") to produce the dotted module path; apply the same fix for the other
occurrence that builds module_path (the block around the
module_file.relative_to(...) usage at lines 63-68) so both places use
OS-independent path-to-module conversion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8d4b727c-bb47-4d4d-9d77-7840b6c418e0

📥 Commits

Reviewing files that changed from the base of the PR and between cf78404 and b7d9037.

📒 Files selected for processing (31)
  • custom_components/spook/__init__.py
  • custom_components/spook/binary_sensor.py
  • custom_components/spook/button.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py
  • custom_components/spook/ectoplasms/group/repairs/unknown_members.py
  • custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py
  • custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py
  • custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py
  • custom_components/spook/ectoplasms/proximity/repairs/unknown_zone.py
  • custom_components/spook/ectoplasms/scene/repairs/unknown_entity_references.py
  • custom_components/spook/ectoplasms/script/repairs/unknown_area_references.py
  • custom_components/spook/ectoplasms/script/repairs/unknown_device_references.py
  • custom_components/spook/ectoplasms/script/repairs/unknown_entity_references.py
  • custom_components/spook/ectoplasms/script/repairs/unknown_floor_references.py
  • custom_components/spook/ectoplasms/script/repairs/unknown_label_references.py
  • custom_components/spook/entity_filtering.py
  • custom_components/spook/event.py
  • custom_components/spook/integration_linking.py
  • custom_components/spook/number.py
  • custom_components/spook/repairs.py
  • custom_components/spook/select.py
  • custom_components/spook/sensor.py
  • custom_components/spook/setup_helpers.py
  • custom_components/spook/switch.py
  • custom_components/spook/time.py
  • tests/test_util.py
✅ Files skipped from review due to trivial changes (8)
  • custom_components/spook/ectoplasms/group/repairs/unknown_members.py
  • custom_components/spook/time.py
  • custom_components/spook/button.py
  • custom_components/spook/ectoplasms/script/repairs/unknown_floor_references.py
  • custom_components/spook/init.py
  • tests/test_util.py
  • custom_components/spook/ectoplasms/lovelace/repairs/unknown_entity_references.py
  • custom_components/spook/ectoplasms/script/repairs/unknown_label_references.py
🚧 Files skipped from review as they are similar to previous changes (8)
  • custom_components/spook/ectoplasms/proximity/repairs/unknown_tracked_entities.py
  • custom_components/spook/ectoplasms/proximity/repairs/unknown_ignored_zones.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_device_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_label_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_entity_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_service_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_floor_references.py
  • custom_components/spook/ectoplasms/automation/repairs/unknown_area_references.py

@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

refactor Improvement of existing code, not introducing new features.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants