-
Notifications
You must be signed in to change notification settings - Fork 684
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enable mypy part 1 (addons and api) #5759
base: main
Are you sure you want to change the base?
Conversation
📝 WalkthroughWalkthroughThis update introduces wide-ranging improvements across multiple modules. Changes include enhanced type annotations, stricter error handling, and refined control flows. Notably, properties in the Changes
Sequence Diagram(s)sequenceDiagram
participant Module as Affected Module
participant SysRes as System Resolution
participant Log as Logger
Module->>SysRes: Encounter error (e.g. EBADMSG)
Note right of SysRes: Instead of direct assignment,\\call add_unhealthy_reason(reason)
SysRes-->>Module: Unhealthy state updated
Module->>Log: Log error message
sequenceDiagram
participant Request as API Request
participant AM as AddonManager
participant Scheduler as Job Scheduler
Request->>AM: Call uninstall(addon_slug, remove_config)
AM->>Scheduler: @Job decorator triggers job scheduling
Scheduler-->>AM: Execute uninstall asynchronously
AM-->>Request: Return response
Tip ⚡🧪 Multi-step agentic review comment chat (experimental)
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
⏰ Context from checks skipped due to timeout of 90000ms (3)
🔇 Additional comments (6)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
supervisor/addons/addon.py (1)
288-289
: Improved property guard conditions.Added an additional check for
addon_store
availability alongside the existingis_detached
check. This prevents potential attribute access errors when the addon store reference is missing or not properly initialized.Consider adding a helper method to check for both conditions since this pattern is repeated across multiple properties.
+def _use_local_data(self) -> bool: + """Return whether to use local data instead of store data.""" + return self.is_detached or not self.addon_store + @property def with_icon(self) -> bool: """Return True if an icon exists.""" - if self.is_detached or not self.addon_store: + if self._use_local_data(): return super().with_icon return self.addon_store.with_iconAlso applies to: 295-296, 302-303, 309-310
supervisor/resolution/module.py (1)
133-140
: Improved unhealthy reason management with dedicated method.The
add_unhealthy_reason
method provides better encapsulation of the logic for adding unhealthy reasons, including duplicate checking and event notification.Note the small typo in the docstring: "unhrealthy" should be "unhealthy".
Fix the typo in the docstring:
-"""Add a reason for unhrealthy.""" +"""Add a reason for unhealthy."""
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (62)
supervisor/addons/addon.py
(14 hunks)supervisor/addons/build.py
(4 hunks)supervisor/addons/manager.py
(2 hunks)supervisor/addons/model.py
(2 hunks)supervisor/addons/options.py
(3 hunks)supervisor/api/__init__.py
(7 hunks)supervisor/api/addons.py
(7 hunks)supervisor/api/audio.py
(3 hunks)supervisor/api/auth.py
(3 hunks)supervisor/api/backups.py
(9 hunks)supervisor/api/discovery.py
(6 hunks)supervisor/api/hardware.py
(1 hunks)supervisor/api/host.py
(3 hunks)supervisor/api/ingress.py
(5 hunks)supervisor/api/jobs.py
(2 hunks)supervisor/api/middleware/security.py
(6 hunks)supervisor/api/mounts.py
(5 hunks)supervisor/api/network.py
(4 hunks)supervisor/api/proxy.py
(5 hunks)supervisor/api/resolution.py
(1 hunks)supervisor/api/services.py
(1 hunks)supervisor/api/store.py
(7 hunks)supervisor/api/supervisor.py
(1 hunks)supervisor/api/utils.py
(6 hunks)supervisor/auth.py
(1 hunks)supervisor/backups/manager.py
(4 hunks)supervisor/core.py
(2 hunks)supervisor/coresys.py
(3 hunks)supervisor/discovery/__init__.py
(2 hunks)supervisor/docker/interface.py
(1 hunks)supervisor/hardware/monitor.py
(1 hunks)supervisor/homeassistant/api.py
(3 hunks)supervisor/homeassistant/module.py
(1 hunks)supervisor/host/apparmor.py
(3 hunks)supervisor/jobs/decorator.py
(1 hunks)supervisor/os/manager.py
(1 hunks)supervisor/plugins/audio.py
(2 hunks)supervisor/plugins/dns.py
(4 hunks)supervisor/resolution/checks/supervisor_trust.py
(1 hunks)supervisor/resolution/evaluate.py
(1 hunks)supervisor/resolution/evaluations/base.py
(1 hunks)supervisor/resolution/evaluations/container.py
(1 hunks)supervisor/resolution/evaluations/source_mods.py
(1 hunks)supervisor/resolution/module.py
(4 hunks)supervisor/store/data.py
(1 hunks)supervisor/supervisor.py
(1 hunks)supervisor/utils/systemd_journal.py
(1 hunks)tests/api/test_resolution.py
(6 hunks)tests/jobs/test_job_decorator.py
(1 hunks)tests/misc/test_filter_data.py
(2 hunks)tests/resolution/fixup/test_addon_execute_remove.py
(1 hunks)tests/resolution/fixup/test_fixup.py
(1 hunks)tests/resolution/fixup/test_store_execute_reload.py
(1 hunks)tests/resolution/fixup/test_store_execute_remove.py
(1 hunks)tests/resolution/fixup/test_store_execute_reset.py
(1 hunks)tests/resolution/fixup/test_system_adopt_data_disk.py
(4 hunks)tests/resolution/fixup/test_system_clear_full_backup.py
(1 hunks)tests/resolution/fixup/test_system_create_full_backup.py
(1 hunks)tests/resolution/fixup/test_system_execute_integrity.py
(2 hunks)tests/resolution/fixup/test_system_execute_reboot.py
(1 hunks)tests/resolution/fixup/test_system_rename_data_disk.py
(3 hunks)tests/resolution/test_resolution_manager.py
(12 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
`*/**(html|markdown|md)`: - For instructional content in doc...
*/**(html|markdown|md)
: - For instructional content in documentation, use a direct and authoritative tone. Avoid expressions of politeness such as 'may' or 'please', and ensure the goal of the instruction is fronted.
- Apply the Microsoft Style Guide to ensure documentation maintains clarity and conciseness.
- In step-by-step instructions, front the location phrase in the instructional sentence.
- In step-by-step instructions, front the 'goal' in the instructional sentence.
- In step-by-step instructions, if in doubt what to front, front the 'goal' before the location phrase in the instructional sentence.
- do not hyphenate terms like 'top-right' or 'bottom-left' with 'corner'
supervisor/auth.py
supervisor/supervisor.py
supervisor/core.py
supervisor/coresys.py
`*/**(html|markdown|md)`: - Use bold to mark UI strings. - I...
*/**(html|markdown|md)
: - Use bold to mark UI strings.
- If "" are used to mark UI strings, replace them by bold.
supervisor/auth.py
supervisor/supervisor.py
supervisor/core.py
supervisor/coresys.py
`*/**(html|markdown|md)`: - Be brief in your replies and don...
*/**(html|markdown|md)
: - Be brief in your replies and don't add fluff like "thank you for..." and "Please let me know if"
supervisor/auth.py
supervisor/supervisor.py
supervisor/core.py
supervisor/coresys.py
`*/**(html|markdown|md)`: - Use sentence-style capitalizatio...
*/**(html|markdown|md)
: - Use sentence-style capitalization also in headings.
supervisor/auth.py
supervisor/supervisor.py
supervisor/core.py
supervisor/coresys.py
`*/**(html|markdown|md)`: do not comment on HTML used for ic...
*/**(html|markdown|md)
: do not comment on HTML used for icons
supervisor/auth.py
supervisor/supervisor.py
supervisor/core.py
supervisor/coresys.py
`*/**(html|markdown|md)`: Avoid flagging inline HTML for emb...
*/**(html|markdown|md)
: Avoid flagging inline HTML for embedding videos in future reviews for this repository.
supervisor/auth.py
supervisor/supervisor.py
supervisor/core.py
supervisor/coresys.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Run the Supervisor
- GitHub Check: Run tests Python 3.13.2
🔇 Additional comments (192)
supervisor/jobs/decorator.py (1)
38-38
: Improved type annotation foron_condition
parameterThe changed type annotation from
JobException | None
totype[JobException] | None
now correctly indicates that the parameter should be a class type rather than an instance. This matches the actual usage in the code (e.g., at lines 185, 245, and 292), whereon_condition
is instantiated with parameters.supervisor/api/resolution.py (3)
36-36
: Added default value for robust error handlingAdding a default empty string ensures that
get_issue
always receives a string value even if the "issue" key is missing frommatch_info
. This prevents potentialNone
values being passed to methods expecting strings.
44-44
: Added default value for robust error handlingAdding a default empty string ensures that
get_suggestion
always receives a string value even if the "suggestion" key is missing frommatch_info
. This is consistent with the other similar changes in this file.
52-52
: Added default value for robust error handlingAdding a default empty string ensures that the
get
method always receives a string value even if the "check" key is missing frommatch_info
. This follows the same pattern as the other similar changes in this file.supervisor/homeassistant/module.py (1)
332-334
: Improved unhealthy state managementReplacing direct assignment with a method call to
add_unhealthy_reason()
allows tracking multiple unhealthy reasons simultaneously instead of overwriting with a single reason. This provides better diagnostics and follows proper OOP principles of encapsulating state changes behind methods.supervisor/discovery/__init__.py (1)
8-8
: Corrected type annotation for uuid attributeThe type annotation for
uuid
has been changed fromUUID
tostr
, which matches how it's actually used throughout the code. The factory function already returnsuuid4().hex
(a string representation), and all usages (in dictionary keys, logging, API paths) treat it as a string. The import has also been simplified to only include what's needed.Also applies to: 34-34
supervisor/api/hardware.py (1)
71-74
: Improved error handling for missing filesystems.This change adds a null-check that prevents potential
AttributeError
exceptions whenfs_block.filesystem
isNone
. Using a conditional expression to fallback to an empty list is appropriate here.supervisor/resolution/checks/supervisor_trust.py (1)
33-33
: Good refactoring to use the dedicated method instead of direct assignment.Changing from direct assignment to
self.sys_resolution.unhealthy
to using theadd_unhealthy_reason
method is a better approach, as it allows accumulating multiple reasons rather than replacing the existing value.supervisor/addons/manager.py (2)
197-197
: Good addition of Job decorator for better tracking.Adding the job decorator to the uninstall method provides better management, tracking, and potentially cancellation capabilities for uninstall operations. This is consistent with other operations like install, update, and rebuild.
317-317
: Type annotation improved to represent possible states.The updated type annotation
bool | None
more accurately represents the possible states of the variable, even though the current initialization isFalse
. This improves type safety and code readability.supervisor/auth.py (1)
71-73
: Improved type annotation to match actual function behavior.The parameter types have been updated to correctly reflect that both
username
andpassword
can beNone
. This is important for mypy type checking and matches the existing error handling logic at line 75 that already checks forNone
password.supervisor/utils/systemd_journal.py (1)
64-64
: Return type signature improved for clarity and type safetyThe return type annotation has been updated to better reflect the actual values yielded by this generator. The function yields tuples with both the cursor and formatted entry, which is now properly documented in the type signature.
supervisor/host/apparmor.py (3)
93-95
: Improved error handling with structured approachReplacing direct assignment to
unhealthy
withadd_unhealthy_reason
allows for tracking multiple issues rather than just a binary unhealthy state, providing better diagnostics and resolving capabilities.
120-122
: Consistent structured error handlingThe approach of using
add_unhealthy_reason
is consistently applied here, improving error tracking capabilities.
138-140
: Maintaining systematic error handlingThe same pattern of structured error handling is applied here, completing the consistent approach throughout the file.
supervisor/addons/model.py (2)
297-297
: Better property naming for improved clarityRenaming from
watchdog
towatchdog_url
clarifies that this property returns a URL string, not a boolean or other watchdog-related object.
609-609
: Fixed type annotation with proper capitalizationUpdated the type hint to use proper
Any
from typing module rather than lowercaseany
, which isn't a valid type annotation. This ensures mypy will correctly process this type hint.supervisor/api/mounts.py (6)
3-3
: Added cast for proper type handlingAdded the
cast
function import from the typing module to enable explicit type casting of validated request data toMountData
.
13-13
: Imported MountData type for better type annotationsAdded the import of
MountData
type to improve type checking when validating request data.
29-29
: Added default value for safer error handlingAdded default empty string when getting the mount name from request match info, preventing potential
KeyError
exceptions if the key is missing.
74-74
: Added explicit type cast for improved type safetyUsing
cast()
ensures that mypy correctly understands thatbody
is of typeMountData
after validation, improving type checking throughout the function.
76-77
: Consistent key access for mount nameChanged from using the
ATTR_NAME
constant to using the string literal"name"
directly, ensuring consistent access to the name field in the validated data.
100-103
: Added explicit type cast with improved formattingThe type cast to
MountData
ensures mypy understands the type ofbody
after validation, maintaining type safety throughout the function.supervisor/api/jobs.py (2)
29-29
: Good defensive programming.Adding a default empty string when getting UUID from match_info prevents potential NoneType errors in the get_job method if the UUID is missing.
72-78
: Good defensive programming.Using
.get(current_job.uuid, [])
instead of just.get(current_job.uuid)
prevents potential NoneType errors by ensuring an empty list is returned when no jobs are associated with the current job's UUID.supervisor/addons/options.py (4)
140-140
: Good type annotation addition.Adding the
dict[str, Any]
type annotation for range_args helps with type checking and code clarity.
393-398
: Good type annotation improvement.Updating the type annotation for ui_node to
dict[str, Any]
properly represents that the dictionary can contain values of different types, not just strings.
400-400
: Good type annotation addition.Adding the
list[dict[str, Any]]
type annotation for nested_schema helps with type checking and code clarity.
416-416
: Good type annotation addition.Adding the
dict[str, Any]
type annotation for clean_filter helps with type checking and code clarity.supervisor/api/auth.py (3)
4-4
: Good import addition for typing.Adding the Awaitable import from collections.abc supports the return type annotations in the methods below.
46-46
: Correct return type annotation.The method returns
self.sys_auth.check_login()
which is a coroutine, so changing the return type frombool
toAwaitable[bool]
is correct. This also matches how the method is used on line 76 withawait self._process_basic()
.
55-57
: Correct return type annotation.The method returns
self.sys_auth.check_login()
which is a coroutine, so changing the return type frombool
toAwaitable[bool]
is correct. This also matches how the method is used on lines 83 and 88 withawait self._process_dict()
.supervisor/api/proxy.py (5)
4-4
: Good import addition for typing.Adding the AsyncIterator import from collections.abc supports the return type annotation in the _api_client method.
44-44
: Good defensive programming.Adding a default empty string when getting the supervisor token prevents potential NoneType errors if the HEADER_HA_ACCESS header is missing.
58-60
: Improved method signature with explicit typing.The updated signature properly indicates that timeout can be either an int or None, and that the method returns an AsyncIterator of ClientResponse objects. This provides better type safety and documentation.
99-99
: Good defensive programming.Adding a default empty string when getting the content type prevents potential NoneType errors if the CONTENT_TYPE header is missing.
187-198
: Improved code readability with match statement.Replacing the if-elif-else chain with a Python 3.10+ match statement makes the code more readable and maintainable. The exhaustive case handling with proper error raising for unsupported types is a good practice.
supervisor/api/network.py (5)
135-140
: Improved robustness with null-safety checksThe conditional expressions ensure that
ipconfig_struct
is only called when both the IP configuration and its settings exist, preventing potential null reference errors during serialization.
197-197
: Enhanced parameter safety with default valuesAdding a default empty string to
match_info.get()
ensures the method never passes None to_get_interface
, improving type safety.
204-204
: Enhanced parameter safety with default valuesSame improvement as in the
interface_info
method - adding default empty string to prevent None values.
250-250
: Enhanced parameter safety with default valuesSame pattern applied consistently across all methods that call
_get_interface
.
263-266
: Added validation for VLAN parameterThis validation check prevents invalid VLAN numbers, enhancing the robustness of the API by failing early with a clear error message instead of potentially propagating invalid values.
supervisor/api/ingress.py (5)
86-86
: Enhanced parameter safety with default valuesUsing an empty string as default prevents
None
values when the token isn't present in the request's match info.
135-135
: Updated return type annotation to match implementationThe return type has been updated from
dict[str, Any]
toNone
to accurately reflect that this method doesn't return a value, improving type correctness.
150-150
: Enhanced parameter safety with default valuesUsing an empty string as default for the session cookie ensures consistent handling when the cookie is missing.
157-157
: Enhanced parameter safety with default valuesConsistent use of the default value pattern for path parameters.
186-186
: Improved type consistency for protocol handlingChanged the initialization of
req_protocols
to use an empty list instead of what was likely a tuple, ensuring consistent typing throughout the method.supervisor/homeassistant/api.py (2)
4-5
: Updated imports for better type handlingChanged imports to support the updated type annotations in the
make_request
method. AddedAsyncIterator
andMultiMapping
to properly type the method parameters and return value.Also applies to: 14-14
89-92
: Enhanced type annotations for make_request methodImproved type safety through several changes:
- Changed
timeout
fromint
toint | None
to explicitly allow None values- Updated
params
fromdict[str, str] | None
toMultiMapping[str] | None
for more flexible parameter mapping- Changed return type from
AbstractAsyncContextManager[aiohttp.ClientResponse]
toAsyncIterator[aiohttp.ClientResponse]
to better match the actual implementationThese changes provide more precise type information for mypy validation.
supervisor/api/middleware/security.py (3)
3-3
: Corrected imports and fixed function name typoThe changes improve code correctness by:
- Adding specific import for
Callable
fromcollections.abc
- Importing necessary types directly from
aiohttp.web
- Fixing the typo in the function name from
excract_supervisor_token
toextract_supervisor_token
Also applies to: 9-9, 27-27
183-183
: Updated handler parameter types for middleware methodsChanged the type annotation for
handler
fromRequestHandler
toCallable
in multiple middleware methods, providing more flexibility for handler implementations while maintaining type safety.Also applies to: 201-201, 215-215, 286-286
217-218
: Added type annotation for request_from variableAdded an explicit type annotation for the
request_from
variable asCoreSysAttributes | None
, improving type clarity and consistency.supervisor/api/backups.py (7)
191-191
: Method renamed for clarity and Python naming best practices.The method has been renamed from
list
tolist_backups
. This is a good change as it avoids potential confusion with Python's built-inlist
type and more clearly communicates the method's purpose.
299-304
: Type casting added to ensure type safety with job scheduling.Adding explicit type casting with
cast()
ensures the correct types are used in type checking and helps mypy identify potential issues. This promotes type safety and clearer code.
501-504
: Added type casting to ensure type safety for location validation.The cast to
list[str | None]
ensures type compatibility with the_validate_cloud_backup_location
method. This change improves type safety for the validation function.
515-515
: Type casting added to clarify Mount type access.Adding
cast(Mount, location)
ensures that the.local_where
attribute is safely accessed after type checking. This improves type safety when working with different location types.
546-548
: Added explicit type check to prevent processing invalid uploads.This change adds a critical validation to ensure the uploaded content is of the expected type before processing. This helps prevent errors from incorrectly formatted API requests.
551-554
: Added type casting for file operations to ensure type safety.The explicit casting of
backup_file_stream
toIOBase
ensures proper type checking when accessing write and close methods. This makes the code more robust when handling file operations.
569-571
: Replaced direct state modification with method call for better encapsulation.Changed from directly setting unhealthy state to using the
add_unhealthy_reason
method. This is a good practice as it encapsulates state management logic within the appropriate method.supervisor/coresys.py (3)
809-811
: Simplified method signature for more flexible argument passing.Removed explicit type annotations for
*args
and**kwargs
, which allows for more flexible argument passing. This is in line with Python's dynamic typing approach and makes the method more adaptable.
819-825
: Simplified method signature for more flexible argument passing.Removed explicit type annotations for
*args
and**kwargs
in thesys_call_later
method. This change makes the method signature more flexible and is consistent with the changes to other methods.
829-835
: Simplified method signature for more flexible argument passing.Removed explicit type annotations for
*args
and**kwargs
in thesys_call_at
method. This change makes the method signature more flexible and is consistent with the changes to other methods.supervisor/api/utils.py (6)
32-32
: Fixed function name typo for better code clarity.Corrected the function name from
excract_supervisor_token
toextract_supervisor_token
, fixing a typo. This improves code readability and ensures consistent naming.
61-63
: Added type annotations for improved type checking.Added explicit type annotations for the
api
parameter and return type, specifyingapi
asCoreSysAttributes
and return type asweb.Response | web.StreamResponse
. This enhances type safety and code clarity.
90-90
: Added type annotation for parameter in wrapped API function.Added explicit type annotation for the
api
parameter asCoreSysAttributes
, improving type safety and making the expected parameter type clear to callers.
107-109
: Added type annotations for improved type checking.Added explicit type annotations for the
api
parameter and return type, consistent with other similar functions in the file. This enhances type safety and documentation.
172-172
: Enhanced type flexibility for the data parameter.Modified the type annotation to allow both dictionary and list types for the
data
parameter. This provides more flexibility in the types of data that can be returned while maintaining type safety.
181-181
: Expanded schema type annotation for more flexible validation.Added support for
vol.All
in the schema parameter type annotation, allowing for more flexible schema validation. This change accommodates different validation approaches.supervisor/api/store.py (7)
96-96
: Added default value for improved robustness.Added a default empty string when retrieving
addon_slug
from request match info. This prevents potentialNone
values and ensures consistent type handling.
105-105
: Added type casting for safer type handling.Added explicit type casting to
Addon
to ensure proper type checking when accessingaddon_store
attribute. This improves type safety when working with addon objects.
114-114
: Added default value for improved robustness.Added a default empty string when retrieving
repository_slug
from request match info. This prevents potentialNone
values and improves code resilience.
129-132
: Added type casting for clearer type handling in conditional assignment.Added explicit type casting to
Addon
when retrieving an addon by slug. This ensures proper type checking while maintaining the conditional logic.
149-149
: Simplified conditional logic for better readability.Improved the expression for determining
ATTR_UPDATE_AVAILABLE
by using a concise conditional expression. This makes the code more readable while preserving the same behavior.
152-152
: Simplified conditional logic for better readability.Improved the expression for determining
ATTR_VERSION
by using a concise conditional expression. This makes the code more readable while preserving the same behavior.
249-249
: Added type casting for improved type safety.Added explicit type casting to
AddonStore
after extracting the addon. This ensures proper type checking and clarity about the expected object type.supervisor/docker/interface.py (1)
56-56
: Great enhancement to type safety.Adding explicit type annotation to
MAP_ARCH
will help mypy verify correct usage of this dictionary and improve code readability.supervisor/api/audio.py (3)
127-127
: Improved parameter handling with default value.Adding a default empty string prevents potential
None
values being passed toStreamType()
, which could cause runtime errors. The type annotation also enhances type safety.
140-140
: Consistent parameter handling with default value.Similar improvement as in the
set_volume
method, ensuringsource
is always a string before being passed toStreamType()
.
153-153
: Consistent parameter handling with default value.Same improvement as in the previous methods, ensuring type safety and preventing potential
None
values.supervisor/api/services.py (1)
28-28
:❓ Verification inconclusive
Excellent rename to avoid shadowing Python built-in.
Renaming the method from
list
tolist_services
avoids shadowing the built-inlist
type and makes the method's purpose more explicit.
🏁 Script executed:
#!/bin/bash # Check if all references to the renamed method have been updated rg -A 2 "api_services\.list\(" --glob "*.py"Length of output: 46
Action Required: Verify Manual References to the Updated Method Name
The renaming of the method to
list_services
insupervisor/api/services.py
(line 28) is excellent as it avoids shadowing Python's built-inlist
and clarifies the method's purpose. However, the automated search (rg -A 2 "api_services\.list\("
) produced no output, which might indicate that no lingering calls to the old name exist—but the absence of output also raises concerns about the search’s coverage. Please manually verify that all references have been correctly updated across the repository.
- Location:
supervisor/api/services.py
(line 28:async def list_services(self, request):
)- Action: Manually check the codebase for any instances of
list
used onapi_services
to ensure the old method is not referenced.supervisor/store/data.py (1)
182-184
: Good refactoring to use method call instead of direct assignment.Using
add_unhealthy_reason()
method instead of directly assigning to the property is a better approach as it encapsulates the logic and provides a consistent interface for setting unhealthy reasons throughout the codebase.supervisor/resolution/evaluations/source_mods.py (1)
54-56
: Improved error handling with proper method callThis change properly replaces direct attribute assignment with a method call to
add_unhealthy_reason()
, which follows better encapsulation principles. This is a good improvement for type safety and is aligned with the PR goal of enabling mypy.supervisor/hardware/monitor.py (1)
43-43
: Properly encapsulating unhealthy state managementGood refactoring to replace direct property assignment with a method call. This change enhances type safety and encapsulation, which aligns with enabling mypy in the codebase.
tests/resolution/fixup/test_fixup.py (1)
31-33
: Improved test structure with proper method callThe modification correctly updates the test to use
add_suggestion()
rather than directly assigning to thesuggestions
property. This improves encapsulation and makes the test more robust against internal implementation changes.supervisor/os/manager.py (1)
240-242
: Enhanced error handling through proper method usageThis change correctly replaces direct property assignment with a method call to
add_unhealthy_reason()
. This follows the same pattern seen in other files, providing better encapsulation and type safety for mypy.tests/jobs/test_job_decorator.py (1)
53-53
: Method call replaces direct property assignment for improved type safetyThe code now uses
add_unhealthy_reason()
instead of directly assigning to theunhealthy
property. This method likely provides better encapsulation and allows for more structured handling of unhealthy states, supporting multiple reasons simultaneously.supervisor/resolution/evaluations/container.py (1)
104-104
: Method call replaces direct property assignment for improved type safetyThe code now uses
add_unhealthy_reason()
instead of directly assigning to theunhealthy
property. This method likely provides better type handling, validation, and potentially allows tracking multiple unhealthy reasons simultaneously.supervisor/resolution/evaluations/base.py (1)
26-26
: Method call replaces direct property assignment for improved type safetyThe code now uses
add_unsupported_reason()
instead of directly assigning to theunsupported
property. This provides better encapsulation and aligns with the pattern seen in other resolution-related classes where direct property assignments are replaced with method calls.supervisor/resolution/evaluate.py (1)
70-70
: Method call replaces direct property assignment for improved type safetyChanged from directly setting the
unhealthy
property to using theadd_unhealthy_reason()
method. This is consistent with similar changes in other files and improves type safety while potentially allowing for more sophisticated handling of multiple unhealthy reasons.supervisor/addons/build.py (4)
7-7
: Type import enhancementThe addition of
Any
from typing improves the code's type annotation capabilities for the dict inget_docker_args
.
26-26
: Import path refinementChanging the import source of
AnyAddon
from relative.
to more specific.manager
improves code clarity and organization.
129-129
: Dict type annotation addedAdding the explicit type annotation
dict[str, Any]
to theargs
variable improves code clarity and enables better static type checking.
66-66
:❓ Verification inconclusive
Architecture matching parameter update
Changed
self.sys_arch.match
to accept a list of architectures rather than a single value. This aligns with mypy type checking requirements and ensures that thematch
function receives the expected parameter type.
🏁 Script executed:
#!/bin/bash # Verify the sys_arch.match method signature and usage pattern # Check definition of the match method rg -A 5 "def match" | grep -A 10 "sys_arch"Length of output: 43
Please manually verify the updated architecture matching parameter
The change in
supervisor/addons/build.py
—updating the call toreturn self.sys_arch.match([self.addon.arch])—is intended to ensure that the
match
method receives a list of architectures (as required by mypy type checking). However, our initial automated search for the definition ofsys_arch.match
did not yield any output. Please manually confirm that thematch
method’s signature indeed expects a list rather than a single value.Action items:
- Verify the definition of
sys_arch.match
(possibly in its module, e.g.,supervisor/sys_arch.py
) to ensure it accepts a list.- Confirm that all consumers of
sys_arch.match
are updated accordingly to match the new parameter requirement.supervisor/plugins/audio.py (2)
97-99
: Improved unhealthy state managementChanged from direct assignment to a method call for adding unhealthy reasons. This encapsulates the state change logic and provides a single point of control for managing system health.
116-118
: Consistent unhealthy state managementSimilar to the previous change, this updates the error handling to use the
add_unhealthy_reason
method instead of direct assignment, maintaining consistency with the system health management pattern.supervisor/api/supervisor.py (2)
214-214
: Return type generalizationChanged return type from
Awaitable[None]
to the more generalAwaitable
, which is more accurate as the method now returns an awaitable that resolves to the result ofasyncio.gather()
.
216-220
: Simplified asynchronous operationReplaced previous implementation with a cleaner approach using
asyncio.gather()
to run multiple coroutines concurrently, with each protected from cancellation usingasyncio.shield()
. This reduces code complexity while maintaining the same functionality.supervisor/api/host.py (5)
6-6
: Added typing importThe addition of
Any
from typing module enables proper type annotations in the file.
199-199
: Type annotation added to params dictionaryAdding explicit type annotation
dict[str, Any]
for theparams
variable improves code clarity and enables better static type checking.
203-203
: Defensive dictionary accessChanged from direct dictionary access
request.match_info[IDENTIFIER]
to.get()
method with a default empty string. This preventsKeyError
exceptions when the identifier is not present in the match info.
211-211
: Consistent defensive dictionary accessSimilar to the previous change, this uses the
.get()
method with a default empty string when accessing theBOOTID
key, preventing potentialKeyError
exceptions.
245-245
: Defensive headers accessUsing the
.get()
method with a default empty string when accessing theRANGE
header ensures that the code won't raise exceptions if the header is missing.supervisor/supervisor.py (1)
177-179
: Improved error handling with method-based approachThe change from directly setting the unhealthy reason to using the
add_unhealthy_reason()
method is a better approach that likely allows for maintaining multiple unhealthy reasons simultaneously rather than overwriting a previous state.tests/resolution/fixup/test_system_clear_full_backup.py (1)
20-22
: Enhanced encapsulation with method-based suggestion managementReplacing direct assignment with the
add_suggestion()
method improves type safety and encapsulation by properly managing the addition of suggestions through a dedicated API rather than directly manipulating the underlying collection.tests/resolution/fixup/test_system_create_full_backup.py (1)
20-22
: Enhanced encapsulation with method-based suggestion managementUsing the
add_suggestion()
method instead of direct assignment improves type safety and encapsulation, consistent with the mypy enablement objective of this PR.tests/resolution/fixup/test_system_execute_integrity.py (2)
25-28
: Improved state management with method-based approachUsing
add_suggestion()
andadd_issue()
methods instead of direct assignments enhances type safety and provides better encapsulation of the resolution system's state management.
51-54
: Consistent method-based state managementThis change maintains consistency with the pattern established earlier in the file, using method calls instead of direct property assignments for better type safety and encapsulation.
tests/resolution/fixup/test_system_execute_reboot.py (1)
23-26
: Improved encapsulation with method calls instead of direct assignmentThe refactoring from direct assignment to method calls improves encapsulation and will provide better type checking support for mypy, which aligns with the PR's goal of enabling mypy. This change follows a consistent pattern applied across the codebase.
supervisor/backups/manager.py (4)
199-201
: Improved encapsulation for unhealthy reason managementRefactoring from direct assignment to using the
add_unhealthy_reason
method improves type safety and encapsulation. This is consistent with the PR's mypy enablement goals.
355-357
: Consistent pattern for managing unhealthy statesThis refactoring follows the same pattern as other changes in this file, using the
add_unhealthy_reason
method instead of direct assignment.
411-413
: Consistent unhealthy reason managementThis change maintains consistency with the other similar changes in this file and across the codebase.
454-456
: Consistent use of add_unhealthy_reason methodThe consistent application of this pattern across all error handlers in this file shows a systematic approach to improving type safety.
tests/resolution/fixup/test_addon_execute_remove.py (1)
18-31
: Improved encapsulation with method calls for suggestion and issue managementRefactoring from direct assignment to method calls (
add_suggestion
andadd_issue
) enhances type safety and encapsulation. The indentation and formatting also improves readability.tests/resolution/fixup/test_store_execute_remove.py (1)
19-28
: Consistent pattern for managing suggestions and issuesThis change follows the same pattern as seen in other test files, using method calls instead of direct assignment for better type safety and encapsulation.
supervisor/core.py (2)
117-117
: Good refactoring to useadd_unhealthy_reason
methodThis change improves code encapsulation by using the dedicated method rather than directly assigning to the unhealthy state. This approach allows for better tracking of multiple unhealthy reasons simultaneously.
180-180
: Good refactoring to useadd_unhealthy_reason
methodSimilar to the previous instance, this change properly uses the dedicated method instead of direct assignment to manage unhealthy states during setup errors.
tests/resolution/fixup/test_store_execute_reset.py (2)
21-23
: Good refactoring to useadd_suggestion
methodThis change properly updates the test to use the new method-based approach for adding suggestions rather than direct assignment. This maintains better encapsulation and is more type-safe.
24-26
: Good refactoring to useadd_issue
methodSimilar to the suggestion change, this refactoring properly updates the test to use the dedicated method for adding issues. This is consistent with the overall refactoring approach across the codebase.
tests/resolution/fixup/test_store_execute_reload.py (2)
18-20
: Good refactoring to useadd_suggestion
methodThis change properly updates the test to use the new method-based approach for adding suggestions, consistent with the changes in other test files.
21-23
: Good refactoring to useadd_issue
methodThis refactoring properly updates the test to use the dedicated method for adding issues, maintaining consistency across the codebase.
tests/misc/test_filter_data.py (2)
99-99
: Good refactoring to useadd_unsupported_reason
methodThis change improves the test by using the dedicated method rather than direct assignment to the unsupported state.
218-218
: Good refactoring to useadd_unhealthy_reason
methodThis change properly updates the test to use the dedicated method for adding unhealthy reasons, consistent with the overall refactoring pattern.
tests/resolution/fixup/test_system_adopt_data_disk.py (8)
88-92
: Good refactoring to use method calls rather than direct assignment.Converting direct assignments to method calls improves encapsulation and type safety, which aligns with the mypy enablement objective.
93-95
: Appropriate use of add_issue method.The switch from direct property assignment to the method call pattern is consistent with good OOP practices and improves code maintainability.
129-133
: Consistent application of encapsulation pattern.Good consistency in applying the same method-based approach across multiple test functions.
134-136
: Well-executed refactoring for issue handling.The refactoring maintains the same functionality while improving code structure.
166-170
: Consistent pattern application throughout the file.The systematic replacement of direct property assignments with method calls enhances type safety.
171-173
: Proper encapsulation of issue addition.This change follows the same pattern established throughout the file, maintaining consistency.
218-222
: Appropriate use of method encapsulation pattern in final test case.The consistent application of the new pattern makes the code more maintainable and type-safe.
223-225
: Consistent implementation of the add_issue pattern.This final instance completes the consistent refactoring throughout the test file.
supervisor/plugins/dns.py (4)
159-162
: Good refactoring of error handling for improved type safety.Replacing direct assignment to
unhealthy
with theadd_unhealthy_reason
method call improves encapsulation and makes the code more mypy-friendly.
170-173
: Consistent application of the unhealthy reason pattern.This change follows the same pattern established earlier in the file, maintaining consistency in error handling.
350-353
: Proper error handling pattern in write_hosts method.The consistent use of
add_unhealthy_reason
rather than direct assignment improves encapsulation and type safety.
441-444
: Consistent implementation of error handling pattern.The final instance maintains the same error handling pattern throughout the file, enhancing code maintainability.
tests/resolution/fixup/test_system_rename_data_disk.py (6)
46-50
: Well-implemented method-based approach for suggestion handling.Replacing direct assignment with the
add_suggestion
method call improves encapsulation and type safety.
51-53
: Good refactoring for issue handling.The switch to
add_issue
follows proper OOP practices and will help with mypy type checking.
78-82
: Consistent application of suggestion handling pattern.The refactoring maintains a consistent approach across different test functions.
83-85
: Proper issue handling consistent with the established pattern.This change follows the same pattern established earlier in the file.
105-109
: Maintains consistency in the final test function.The same pattern is correctly applied to the final test function, ensuring consistent code structure.
110-112
: Clean implementation of the issue handling pattern.The consistent application of
add_issue
completes the refactoring of the test file.tests/api/test_resolution.py (7)
30-33
: Good refactoring to use dedicated methods for resolution management.Converting direct assignments to method calls (
add_unsupported_reason
,add_suggestion
) improves encapsulation and type safety.
50-52
: Well-structured variable assignment in method call.The assignment of the returned suggestion to a variable (
clear_backup :=
) is done cleanly within the method call.
64-71
: Good implementation of multiple suggestion additions.The consistent use of
add_suggestion
with variable assignments maintains clean code structure and improves type safety.
94-96
: Proper implementation of issue handling with assignment.The variable assignment within the method call pattern is consistent with earlier examples.
106-107
: Effective use of unhealthy reason handling method.The switch to
add_unhealthy_reason
maintains the same encapsulation pattern seen throughout the PR.
147-149
: Consistent implementation of issue handling pattern.The method-based approach with variable assignment is maintained consistently.
156-165
: Well-structured implementation of multiple suggestion additions.The consistent pattern of adding suggestions via method calls with variable assignments maintains clean code structure throughout the test file.
supervisor/api/addons.py (6)
145-150
: Good addition of TypedDict for improved type safety.Adding the
OptionsValidateResponse
TypedDict provides explicit typing for the API response structure, which will improve code readability and help catch potential type errors during development.
158-158
: Good defensive programming to prevent None values.Using an empty string as default value for
addon_slug
instead of potentially returningNone
helps prevent potentialNoneType
errors in downstream code.
176-176
: Improved method naming for clarity.Renaming
list
tolist_addons
makes the method name more descriptive and avoids potential confusion with Python's built-inlist
function. This change aligns with the naming conventions seen in other modules.
346-346
: Enhanced return type annotations.The method now correctly specifies its return type as
OptionsValidateResponse
instead ofNone
, which improves type-safety and makes the function's contract clearer.
349-350
: Improved response initialization using TypedDict.Using the TypedDict constructor to initialize the response with default values ensures the response has the correct structure and all required fields are present.
358-381
: Direct dictionary access is clear and consistent.Using direct string keys in dictionary operations rather than constants makes the code more readable. The conditions for setting validity based on pwned status are now easier to follow.
supervisor/addons/addon.py (6)
319-319
: Enhanced type safety with AwesomeVersion.Changed return types from
str | None
toAwesomeVersion
for version-related properties to ensure consistent version handling throughout the codebase.Also applies to: 467-468
677-678
: Improved URL validation in watchdog_application.Enhanced validation of watchdog URLs by properly checking both conditions before proceeding. This prevents potential errors when working with invalid URLs.
780-782
: Added guard clause to prevent installation errors.Adding an early check for
addon_store
availability before attempting installation prevents potential errors when trying to install an addon that doesn't exist in the store.
886-888
: Consistent error handling for update operation.Similar to the install method, this guard clause prevents update errors for addons missing from the store. This ensures consistent error handling across related operations.
945-947
: Conditional update based on addon_store availability.The rebuild method now checks if the addon_store is available before attempting to update from it. This prevents potential errors when working with addons that don't have a store reference.
1607-1609
: Consistent path cache refresh logic.Updated the path cache refresh logic to be consistent with other methods by checking both detached status and addon_store availability.
supervisor/resolution/module.py (3)
95-113
: Improved method design with add_suggestion.Replacing the setter with an explicit
add_suggestion
method is a better design that prevents accidental replacement of the entire collection. It also centralizes the duplicate checking and event notification logic.
119-127
: Improved design for unsupported reason management.The
add_unsupported_reason
method provides a more explicit and controlled way to manage unsupported reasons, with clear logic for avoiding duplicates and triggering appropriate notifications.
187-197
: Improved issue handling.Simplified the issue handling logic by moving the duplicate check, logging, and event notification directly into the
add_issue
method. This makes the code more maintainable and ensures consistent behavior when adding issues.supervisor/api/__init__.py (4)
85-86
: Improved initialization of api_host.Directly initializing
_api_host
as anAPIHost
instance and setting itscoresys
attribute is cleaner than the previous approach of setting it toNone
and initializing it later.
527-527
: Improved method naming in route registration.Changed from
api_addons.list
to the more descriptiveapi_addons.list_addons
, which aligns with the implementation in theaddons.py
file and avoids confusion with Python's built-inlist
function.
595-597
: Enhanced flexibility for ingress handler.Changed from
web.view
toweb.route(hdrs.METH_ANY, ...)
to explicitly specify that any HTTP method is allowed. This improves code clarity and makes the API's behavior more explicit.
635-635
: Consistent method naming improvements.Renamed endpoint handlers from general
list
to more specificlist_services
andlist_discovery
, improving clarity and consistency with the rest of the codebase.Also applies to: 649-649
tests/resolution/test_resolution_manager.py (15)
25-25
: Method-based approach for adding unsupported reasonsThe code has been updated to use
add_unsupported_reason()
instead of direct property assignment. This change improves encapsulation and is part of a larger refactoring to use methods for state management.
33-33
: Method-based approach for adding unhealthy reasonsSimilar to the unsupported reasons change, this uses
add_unhealthy_reason()
instead of direct property assignment, improving encapsulation.
40-42
: Updated suggestion creation to use method-based approachThe code now uses
add_suggestion()
with the walrus operator to both create and add the suggestion in a single expression, replacing direct property assignment.
55-62
: Structured suggestion creation for multiple suggestionsUsing the
add_suggestion()
method with the walrus operator for multiple suggestions improves code consistency and maintainability.
85-87
: Method-based approach for adding issuesUsing
add_issue()
instead of direct property assignment is consistent with the other state management improvements in this file.
118-118
: Consistent usage of add_unsupported_reasonThe change to use
add_unsupported_reason()
is applied consistently throughout the test file.
129-133
: Method-based issue creation with improved readabilityThe walrus operator combined with
add_issue()
creates cleaner code while maintaining the ability to reference the created issue.
136-141
: Consistent method usage for unrelated suggestionsThese changes continue the pattern of using
add_suggestion()
instead of direct assignment, maintaining consistency throughout the codebase.
146-155
: Method-based creation for related suggestionsContinues the consistent pattern of using
add_suggestion()
for creating and storing suggestions.
172-175
: Improved issue management with method-based approachUsing
add_issue()
for both single-line and multi-line issue creation improves code consistency.
180-187
: Consistent method-based approach for related issuesThe use of
add_issue()
with the walrus operator continues the pattern throughout the test file.
241-245
: Method-based suggestion creation in event testsConsistent application of the method-based approach for suggestion management in the event-related tests.
287-301
: Method-based approach in multiple suggestion testsThe refactoring to use
add_suggestion()
is applied consistently across the test file, even in complex test scenarios with multiple suggestions.
317-317
: Consistent unsupported reason management in event testsAll instances of unsupported reason management have been updated to use the method-based approach, maintaining consistency throughout the test file.
Also applies to: 329-329, 335-335
381-381
: Method-based unhealthy reason management in event testsThe refactoring to use
add_unhealthy_reason()
has been applied consistently throughout the unhealthy state tests.Also applies to: 393-393, 399-399
supervisor/api/discovery.py (11)
4-4
: Added cast for type safetyAdded
cast
import from typing module, which will be used later for proper type handling.
6-6
: Improved import statementUpdated the import style for
web
from aiohttp to be more explicit, which is good for readability and maintainability.
21-21
: Direct Message type importNow directly importing the
Message
type from the discovery module, making the code more explicit about its dependencies.
38-38
: Added type annotations to _extract_messageImproved method signature with proper type annotations, specifying that it takes a
web.Request
and returns aMessage
object.
40-40
: Minor code consistency improvementUpdated the variable name matching pattern to be more explicit, though the functionality remains the same.
47-47
: Renamed method and added type annotationsChanged
list
tolist_discovery
to avoid conflict with Python's built-inlist
type and added proper return type annotation.
58-64
: Enhanced type safety with castImproved the condition in the list comprehension to use
cast
for ensuring proper type safety when checking the addon state.
67-67
: Added type annotation for services variableExplicitly defined the type of
services
asdict[str, list[str]]
, improving code readability and type safety.
75-75
: Added return type annotation to set_discoveryAdded proper return type annotation to the
set_discovery
method, specifying it returns adict[str, str]
.
99-99
: Added return type annotation to get_discoveryAdded proper return type annotation to the
get_discovery
method, specifying it returns adict[str, Any]
.
111-111
: Changed return type and removed return statementUpdated the
del_discovery
method to specify it returnsNone
and removed an unnecessary return statement.
Proposed change
On a quest to enable mypy in CI to help us catch more issues before they become bugs. As we've had it off for so long there are quite a few issues so this will take several PRs. This PR covers the
addons
andapi
modules.Type of change
Additional information
Checklist
ruff format supervisor tests
)If API endpoints or add-on configuration are added/changed:
Summary by CodeRabbit
Refactor
Chore