Skip to content
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

Restructure config flow #271

Merged
merged 4 commits into from
Dec 16, 2024
Merged

Conversation

jschlyter
Copy link
Contributor

@jschlyter jschlyter commented Dec 14, 2024

Add better error handling and credentials testing when adding a new account

Summary by CodeRabbit

  • New Features

    • Enhanced user configuration flow for the Polestar EV platform with improved error handling and user input validation.
    • New error messages added for better user feedback regarding authentication and vehicle identification issues in both English and Swedish.
  • Bug Fixes

    • Updated error messages for API connection issues to provide clearer feedback.

@jschlyter jschlyter marked this pull request as ready for review December 14, 2024 21:57
Copy link
Contributor

coderabbitai bot commented Dec 14, 2024

Walkthrough

The pull request introduces substantial modifications to the configuration flow of the Polestar API within Home Assistant. Key changes include the addition of two new exception classes for error handling, a shift from the _create_entry method to the async_step_user method for improved user input management, and the introduction of a _test_credentials method for validating user credentials. Additionally, the translation files are updated to enhance error messaging, providing clearer feedback for various failure scenarios.

Changes

File Change Summary
custom_components/polestar_api/config_flow.py - Added NoCarsFoundException and VinNotFoundException classes
- Replaced _create_entry with enhanced async_step_user
- Introduced _test_credentials method for credential validation
- Improved error handling for various exceptions
custom_components/polestar_api/translations/en.json - Added new error messages in error section
- Updated existing error messages in abort section
- Capitalized "API" in error descriptions
custom_components/polestar_api/translations/sv.json - Added new error messages in the "config" section for Swedish translations

Poem

🚗 A Polestar config, once plain and bare,
Now dances with errors, with nuanced flair!
Exceptions leap high, messages clear,
No more confusion, integration's cheer!
A rabbit's delight, smooth setup's embrace 🐰

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@jschlyter jschlyter requested a review from a team as a code owner December 14, 2024 21:57
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (3)
custom_components/polestar_api/config_flow.py (2)

18-23: Consider adding error messages to custom exceptions

The custom exception classes NoCarsFoundException and VinNotFoundException currently do not include any messages. Providing meaningful error messages can enhance debugging and make logging outputs more informative.


44-58: Ensure consistent logging levels for exceptions

There is inconsistent use of logging levels in the exception handling blocks. Some exceptions use _LOGGER.error, while others use _LOGGER.warning. Consider standardizing the logging levels based on the severity of each exception to maintain consistency.

custom_components/polestar_api/translations/en.json (1)

25-25: Minor wording improvement

Consider updating the error message from "Unknown error occurred." to "An unknown error occurred." for better readability and a more user-friendly tone.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d814211 and 9264632.

📒 Files selected for processing (2)
  • custom_components/polestar_api/config_flow.py (1 hunks)
  • custom_components/polestar_api/translations/en.json (1 hunks)

custom_components/polestar_api/config_flow.py Outdated Show resolved Hide resolved
@jschlyter jschlyter force-pushed the config_flow_refactor branch from 9264632 to 74683fe Compare December 15, 2024 10:06
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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)
custom_components/polestar_api/config_flow.py (2)

33-78: LGTM! Well-structured configuration flow with comprehensive error handling

The implementation provides clear error handling paths and appropriate user feedback. Consider defining the error dictionary as a class constant to improve maintainability:

class FlowHandler(config_entries.ConfigFlow):
    VERSION = 1
    CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
+
+    ERROR_MAPPING = {
+        NoCarsFoundException: "no_cars_found",
+        VinNotFoundException: "vin_not_found",
+        PolestarAuthException: "auth_failed",
+        PolestarApiException: "api",
+    }

Then simplify the error handling:

try:
    await self._test_credentials(username, password, vin)
except tuple(self.ERROR_MAPPING.keys()) as exc:
    _LOGGER.error(exc)
    _errors["base"] = self.ERROR_MAPPING[type(exc)]

81-102: Add type hint for found_vins

The implementation looks good, but could benefit from explicit type hinting for better code maintainability.

-        found_vins = api_client.vins
+        found_vins: list[str] = api_client.vins
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9264632 and 74683fe.

📒 Files selected for processing (2)
  • custom_components/polestar_api/config_flow.py (1 hunks)
  • custom_components/polestar_api/translations/en.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • custom_components/polestar_api/translations/en.json
🔇 Additional comments (3)
custom_components/polestar_api/config_flow.py (3)

18-24: LGTM! Well-structured exception classes

The new exception classes are well-defined and follow Python naming conventions. They serve specific error cases which improves error handling granularity.


56-58: Avoid catching the base Exception

Catching the base Exception can mask unexpected errors. Consider catching specific exceptions or removing this catch-all block.


33-78: Verify translation keys exist

Let's ensure all error keys used in the config flow have corresponding translations.

✅ Verification successful

All error keys have corresponding translations in en.json

After checking the error keys used in the config flow:

  • "no_cars_found"
  • "vin_not_found"
  • "auth_failed"
  • "api"
  • "unknown"

All these error keys are properly defined in the English translation file (en.json) under the "config.error" section with appropriate messages:

"error": {
  "auth_failed": "Invalid username/password.",
  "no_cars_found": "No cars found for Polestar ID.",
  "vin_not_found": "Specified VIN not found for Polestar ID.",
  "api": "Error connecting to Polestar API.",
  "unknown": "Unknown error occurred."
}
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify translation keys exist for all error messages used in config flow

# Extract error keys from the code
ERROR_KEYS=$(rg -o '"base"\s*:\s*"([^"]+)"' | cut -d'"' -f4 | sort -u)

# Check if these keys exist in the translation file
for key in $ERROR_KEYS; do
  echo "Checking key: $key"
  rg "\"$key\":" custom_components/polestar_api/translations/
done

Length of output: 75


Script:

#!/bin/bash
# Let's try a different approach to find the error keys and translation files

# First, let's find all translation files
echo "=== Translation files ==="
fd "translations" custom_components/polestar_api/

# Now let's extract error keys from the config flow file directly
echo -e "\n=== Error keys in config_flow.py ==="
rg "_errors\[\"base\"\] = \".*?\"" custom_components/polestar_api/config_flow.py

# Let's also check the content of any translation files if they exist
echo -e "\n=== Content of translation files ==="
fd "translations" custom_components/polestar_api/ --exec cat {}

Length of output: 775


Script:

#!/bin/bash
# Let's check the content of translation files in the translations directory

# Look for English translations (en.json)
echo "=== English translations ==="
fd "en.json" custom_components/polestar_api/translations/ --exec cat {}

# Also check for any other json files in translations
echo -e "\n=== All translation files ==="
fd ".json$" custom_components/polestar_api/translations/ --exec echo "=== {} ===" \; --exec cat {}

Length of output: 29886

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (1)
custom_components/polestar_api/config_flow.py (1)

33-75: Good error handling structure, but consider minor improvements.

The error handling is well-organized with appropriate exception catching and logging. However, consider these improvements:

  1. Move the _errors = {} initialization closer to the error handling block
  2. Add more context to error logs, such as including the username in the error messages

Here's a suggested improvement for the error handling section:

     async def async_step_user(self, user_input: dict | None = None) -> ConfigFlowResult:
         """User initiated config flow."""
-        _errors = {}
 
         if user_input is not None:
             username = user_input[CONF_USERNAME]
             password = user_input[CONF_PASSWORD]
             vin = user_input.get(CONF_VIN)
 
+            _errors = {}
             try:
                 await self._test_credentials(username, password, vin)
             except NoCarsFoundException as exc:
-                _LOGGER.error(exc)
+                _LOGGER.error("No cars found for user %s: %s", username, exc)
                 _errors["base"] = "no_cars_found"
             except VinNotFoundException as exc:
-                _LOGGER.error(exc)
+                _LOGGER.error("VIN not found for user %s: %s", username, exc)
                 _errors["base"] = "vin_not_found"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 74683fe and 63f919e.

📒 Files selected for processing (1)
  • custom_components/polestar_api/config_flow.py (1 hunks)
🔇 Additional comments (1)
custom_components/polestar_api/config_flow.py (1)

18-23: LGTM! Well-structured exception classes.

The new exception classes are focused, descriptive, and follow Python naming conventions. They appropriately extend the base Exception class and provide clear semantics for specific error cases.

custom_components/polestar_api/config_flow.py Outdated Show resolved Hide resolved
@jschlyter jschlyter requested a review from BJReplay December 15, 2024 10:34
@BJReplay
Copy link

Another one I had a look at earlier, so just reviewing changes since this morning.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

♻️ Duplicate comments (1)
custom_components/polestar_api/config_flow.py (1)

78-98: 🛠️ Refactor suggestion

Enhance error handling and documentation in _test_credentials

The method needs improvements in error handling and documentation, as mentioned in previous reviews.

     async def _test_credentials(
         self, username: str, password: str, vin: str | None
     ) -> None:
-        """Validate credentials and return VINs of found cars."""
+        """Validate credentials and verify VIN availability.
+
+        Args:
+            username: Polestar account username
+            password: Polestar account password
+            vin: Optional VIN to validate
+
+        Raises:
+            PolestarAuthException: If authentication fails
+            PolestarApiException: If API communication fails
+            NoCarsFoundException: If no cars are found for the account
+            VinNotFoundException: If the specified VIN is not found
+        """

         api_client = PolestarApi(
             username=username,
             password=password,
             client_session=get_async_client(self.hass),
         )
-        await api_client.async_init()
+        try:
+            await api_client.async_init()
+        except PolestarApiException as exc:
+            _LOGGER.error("Failed to initialize API client for %s: %s", username, exc)
+            raise
🧹 Nitpick comments (1)
custom_components/polestar_api/config_flow.py (1)

56-66: Fix inconsistent empty line formatting

There's an extra empty line between the config entry creation and the form display.

             else:
                 return self.async_create_entry(
                     title=f"Polestar EV for {username}",
                     data={
                         CONF_USERNAME: username,
                         CONF_PASSWORD: password,
                         CONF_VIN: vin,
                     },
                 )
-
         return self.async_show_form(
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 63f919e and 72fbbb0.

📒 Files selected for processing (3)
  • custom_components/polestar_api/config_flow.py (1 hunks)
  • custom_components/polestar_api/translations/en.json (1 hunks)
  • custom_components/polestar_api/translations/sv.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • custom_components/polestar_api/translations/en.json
🔇 Additional comments (4)
custom_components/polestar_api/translations/sv.json (1)

21-25: LGTM! Clear and well-structured error messages

The new error messages are well-written, user-friendly, and properly aligned with the error handling scenarios in the config flow.

custom_components/polestar_api/config_flow.py (3)

18-23: LGTM! Well-defined custom exceptions

The custom exceptions are appropriately defined for specific error scenarios, following Python naming conventions.


33-63: LGTM! Well-structured config flow with comprehensive error handling

The implementation follows Home Assistant's config flow patterns with appropriate error handling and logging levels for different scenarios.


66-76: LGTM! Well-defined form schema

The form schema correctly defines the required and optional fields using voluptuous.

@jschlyter jschlyter merged commit a86f906 into pypolestar:main Dec 16, 2024
5 checks passed
@jschlyter jschlyter deleted the config_flow_refactor branch December 16, 2024 06:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants