Skip to content

Conversation

@bouwew
Copy link
Contributor

@bouwew bouwew commented Apr 18, 2025

Summary by CodeRabbit

  • Chores
    • Improved script flexibility by allowing selection of the Home Assistant core branch for testing and development.
    • Enhanced virtual environment setup and cleanup processes.
    • Updated dependency installation and testing commands for better reliability.
    • Refined quality checks and log messages for clearer output.
    • Added new pre-commit hooks for core testing preparation, dependency installation, and quality checks.
    • Replaced the prettier hook with an improved biome-lint hook for code formatting.

@bouwew bouwew requested a review from a team as a code owner April 18, 2025 09:28
@coderabbitai
Copy link

coderabbitai bot commented Apr 18, 2025

Walkthrough

The script core-testing.sh has been updated to default to the 'master' branch of the Home Assistant core repository, with the option to override this via the BRANCH environment variable. The script now sources external setup scripts for virtual environment management instead of handling this internally. The cloning and updating process for the HA-core repository has been improved to support reusing existing clones and performing thorough cleanups before switching branches. Dependency installation now uses the uv wrapper for pip commands, and the testing and quality check steps have been updated to reflect these changes, including adjustments to command flags and disabling mypy. Additionally, the pre-commit configuration was enhanced with new local hooks for core testing workflows and replaced the prettier hook with biome-lint for improved code formatting.

Changes

File(s) Change Summary
scripts/core-testing.sh Refactored to default to 'master' branch, allow branch override, source external setup scripts, improve repo cleanup and branch switching, use uv for pip installs, update test and quality check commands, and revise log messages.
.pre-commit-config.yaml Added new local hooks for core testing phases (test-core-prep, test-pip-prep, quality), modified existing testing hook to use core-testing.sh, expanded ci skip list, and replaced prettier hook with biome-lint including updated dependencies and description.

Possibly related PRs

  • Codespell fixes #226: Minor wording fixes in echo messages within core-testing.sh without changing logic or control flow, related to the main script refactor here.

Poem

In the warren of code, a script takes a leap,
Now 'master' it follows, no longer asleep.
With branches that flex and commands that are new,
It cleans and it checks, with a streamlined view.
So here’s to the helpers that hop through the night—
Testing made nimble, and everything right!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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.

Copy link

@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: 2

🔭 Outside diff range comments (1)
scripts/core-testing.sh (1)

262-269: 🛠️ Refactor suggestion

Unquoted file paths and backup artifacts
Variables ${src_manifest} and ${dst_manifest} are unquoted in the jq and tee calls, which can break on paths containing spaces. Additionally, sed -i".sedbck" leaves .sedbck backup files behind. Please:

- jq 'del(.version)' ${src_manifest} | tee ${dst_manifest}
+ jq 'del(.version)' "${src_manifest}" | tee "${dst_manifest}"

And avoid backup files:

- sed -i".sedbck" 's/...//g' …
+ sed -i 's/...//g' …
♻️ Duplicate comments (5)
scripts/core-testing.sh (5)

81-81: Repeated redundant set +u
This set +u mirrors the one at line 63. Apply the same cleanup: either remove both or introduce set -u/set +u around only the blocks that need it.


169-174: Repeated block – venv activation and set +u
This block is essentially the same pattern noted above: disabling nounset and sourcing/activating the venv. Please consolidate these into shared logic.


204-210: Repeated virtualenv activation
Again the pattern of disabling nounset and sourcing the venv is repeated here. Consolidate this into a function to make the script more maintainable.


224-227: Repeated virtualenv activation
Yet another instance of sourcing and activating the venv. Extract into a single helper to eliminate duplication.


251-254: Repeated virtualenv activation
The copy-back section also redoes the venv activation—this is the fifth occurrence. Consolidate into a single function.

🧹 Nitpick comments (11)
scripts/core-testing.sh (11)

63-63: Redundant set +u
The script never enables nounset (set -u), so set +u has no effect. Consider removing it to avoid confusion or enable set -u at the top if you intend to guard against unbound variables.


115-117: Duplicate reset logic after initial clone
Lines 115–117 repeat the early "reset & checkout" steps (lines 92–94). Consider factoring this into a helper function to DRY up the code and ease future maintenance.


123-128: Overly aggressive Git cleanup
The stash, stash drop, and git clean -fd steps will irreversibly delete untracked files and dropped stashes. If that’s intended, add a comment warning users. Otherwise, consider limiting cleanup (e.g., git clean -fdX or selectively removing only certain files).


141-147: Repeated virtualenv activation
The script sources python-venv.sh and then activates the venv again here. This pattern appears multiple times. Extract this into a ensure_venv function to avoid duplication and reduce the chance of divergence.


148-151: Bootstrapping pip components via shell pipe
Using grep | sed | sh works but can be brittle if script/bootstrap changes format. Consider a more robust approach (e.g., parsing script/bootstrap or using a small Python snippet) to avoid accidental code execution.


178-184: Hidden errors in translation fetch
Redirecting both stdout and stderr to /dev/null in script.translations silences any failures. For better observability, consider redirecting only stdout and letting errors surface:

- python3 -m script.translations develop --all > /dev/null 2>&1
+ python3 -m script.translations develop --all > /dev/null

188-193: Duplicate uv pip install of the editable package
The uv pip install -e . ... with constraints appears in both bootstrap (line 150) and here (line 193). You likely only need to install the editable package once. DRY this out to speed up runs and reduce confusion.


218-218: Quote variables in pytest invocation
Unquoted expansions (${subject}, ${basedir}) can break if arguments contain spaces or glob characters. Either quote them or build an array of args:

pytest "${debug_params}" "${subject}" "tests/components/plugwise_usb/${basedir}"

234-239: Clean up disabled mypy block
You’ve commented out the mypy invocation and replaced it with a note. If mypy is truly deprecated here, remove the dead code or add a TODO with a plan to re-enable or remove this in the near future.


271-276: Remove legacy commented-out flags
The commented-out --requirements flag and its historical notes add noise. If it's no longer needed, delete these lines or consolidate the rationale in a single comment.


288-288: Consider safer pre-commit invocation
Running git add -A; pre-commit mutates the working directory. For pre-commit checks, you can use:

pre-commit run --all-files

This avoids unintended staging of files and aligns with common pre-commit usage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f0dec5 and 66ac8e6.

📒 Files selected for processing (1)
  • scripts/core-testing.sh (8 hunks)
🔇 Additional comments (3)
scripts/core-testing.sh (3)

56-61: Sourcing external setup scripts
The environment setup scripts (setup.sh and python-venv.sh) are sourced correctly and SC1091 is properly disabled. No concerns here.


78-78: Definition of manualdir
Introducing manualdir for caching a manual clone is clear and works as intended. No issues found.


293-293: No actionable change on the closing fi.

echo ""
pip install --upgrade -q --disable-pip-version-check "${module}"
uv pip install --upgrade "${module}"
fi # pip_prep
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improper iteration of manifest requirements
module=$(jq '.requirements[]' ...) may output multiple lines, but uv pip install "${module}" treats the entire block as a single argument. This will fail when there’s more than one requirement. Consider:

jq -r '.requirements[]' ../custom_components/plugwise_usb/manifest.json \
  | xargs -L1 uv pip install --upgrade

@sonarqubecloud
Copy link

Copy link

@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: 2

♻️ Duplicate comments (2)
scripts/core-testing.sh (1)

196-200: 🛠️ Refactor suggestion

⚠️ Potential issue

Fix iteration over manifest requirements
The current code assigns all entries to a single module variable and runs one install command. If there are multiple requirements, this will fail. Instead, install each requirement individually:

-module=$(jq '.requirements[]' ../custom_components/plugwise_usb/manifest.json | tr -d '"')
-uv pip install --upgrade "${module}"
+jq -r '.requirements[]' ../custom_components/plugwise_usb/manifest.json \
+  | xargs -L1 uv pip install --upgrade
.pre-commit-config.yaml (1)

90-96: Mirror path resolution improvements in test-pip-prep
Apply the same simplifications from the test-core-prep hook to test-pip-prep to ensure consistency in how the script is invoked.

🧹 Nitpick comments (10)
scripts/core-testing.sh (9)

43-46: Update or clarify the comment referencing plugwise-beta
The comment “Cloned/adjusted code from plugwise-beta” and the note about not using the venv may be outdated now that you source and activate it later. Consider clarifying or removing stale commentary to avoid confusion.


56-61: Modularize virtual environment setup
Sourcing external scripts (setup.sh and python-venv.sh) is a solid step toward modularity. Ensure these helper scripts:

  • Exit with non-zero on failures.
  • Document their expected state changes (e.g., creation vs. activation of the venv).

63-74: Clarify use of set +u and argument parsing
Disabling -u globally suppresses unset-variable errors. Instead, consider:

  • Explicitly checking for undefined variables.
  • Using [[ $# -eq 2 ]] or [[ -n $VAR ]] for robust argument checks.
  • Quoting variables in assignments to avoid word-splitting.

77-79: Consider leveraging git worktree instead of manual copy
Maintaining a separate manual_clone_ha directory duplicates repository data and complicates syncing. Using git worktree could streamline branch checkouts without full copies and reduce disk usage.


81-102: DRY up initial clone and reuse logic
The logic for cloning and rebasing HA-core repeats the reset/checkout steps in both the first-time clone and reuse paths. Extract common sequences (e.g., git reset --hard, git checkout, git pull) into a function to reduce duplication and simplify future maintenance.


141-147: Remove redundant venv sourcing
You source python-venv.sh and then immediately source ./venv/bin/activate. If python-venv.sh already activates the venv, the second step may be redundant. Consolidate to a single activation step to avoid confusion.


148-150: Switch to uv for bootstrap pip installs
Great improvement using uv pip install for the HA-core bootstrap. To catch failures within the pipeline, consider enabling pipefail (e.g., set -o pipefail) so errors in grep|sed|sh propagate correctly.


224-244: Re-enable or document mypy status
mypy is currently disabled with a note. If re-enabling isn’t possible immediately, consider adding a TODO or comment explaining why it’s skipped and when it should be brought back to maintain type safety.


248-261: Streamline non-CI copy-back and manifest edits
The copy-back steps and JSON/Sed operations for non-GitHub Actions could be consolidated or moved to a helper function. Additionally, the -i".sedbck" backup files may clutter the tree—consider cleaning them up after editing.

.pre-commit-config.yaml (1)

83-90: Refine test-core-prep hook entry
The current entry hardcodes scripts/core-testing.sh via bash -c. For readability and maintainability, you can simplify to:

entry: bash scripts/core-testing.sh core_prep

This relies on the hook’s language: script context and removes the extra -c 'exec env …' wrapper.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 66ac8e6 and 5d9e160.

📒 Files selected for processing (2)
  • .pre-commit-config.yaml (3 hunks)
  • scripts/core-testing.sh (8 hunks)
🔇 Additional comments (4)
.pre-commit-config.yaml (4)

5-5: Skip HA core testing hooks in CI as intended
Excluding test-core-prep, test-pip-prep, testing, and quality ensures pre-commit.ci doesn’t run these long-running steps, while still preserving them for local workflows.


64-67: Validate biome-lint dependency specification
Switching from prettier to biome-lint is a solid improvement. Confirm that @biomejs/biome@1.8.3 is the correct npm package and version for this hook to function as expected.


98-104: Confirm exit behavior for testing hook
The testing hook runs scripts/core-testing.sh testing under GITHUB_ACTIONS=1. Verify that pytest failures properly propagate exit codes so the hook fails on test errors as intended.


104-110: Approve quality hook configuration
The quality hook is correctly set to pass_filenames: false and invokes the updated script. It aligns with the other HA-core testing hooks and fits the local workflow.

Comment on lines +204 to 219
set +u
cd "${coredir}" || exit
echo ""
echo "Ensure HA-core venv"
# shellcheck disable=SC1091
source "./venv/bin/activate"
echo ""
echo "Test commencing ..."
echo ""
debug_params=""
if [ ! "${DEBUG}" == "" ] ; then
debug_params="-rpP --log-cli-level=DEBUG"
fi
# shellcheck disable=SC2086
pytest ${debug_params} ${subject} --cov=homeassistant/components/plugwise_usb/ --cov-report term-missing -- "tests/components/plugwise_usb/${basedir}" || exit
pytest ${debug_params} ${subject} tests/components/plugwise_usb/${basedir} --snapshot-update --cov=homeassistant/components/plugwise_usb/ --cov-report term-missing || exit
fi # testing
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve test invocation robustness

  • Replace [ ! "$DEBUG" == "" ] with [[ -n "$DEBUG" ]] for clarity.
  • Quote expansions in the pytest command to prevent word-splitting:
-	if [ ! "${DEBUG}" == "" ] ; then 
-        	debug_params="-rpP --log-cli-level=DEBUG"
-	fi
-	pytest ${debug_params} ${subject} tests/... --snapshot-update ...
+	if [[ -n "${DEBUG}" ]]; then
+        	debug_params=(-rpP --log-cli-level=DEBUG)
+	fi
+	pytest "${debug_params[@]}" "${subject}" tests/... --snapshot-update ...

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +4 to +16
# By default assumes running against 'master' branch of Core-HA
# as requested by @bouwew for on-par development with the releases
# version of HA
#
# Override by setting BRANCH environment variable to run against
# a different branch of core
#
# Github flows are run against both 'dev' and 'master'
core_branch="master"
if [ "x${BRANCH}" != "x" ]; then
core_branch="${BRANCH}"
fi
echo "Working on HA-core branch ${core_branch}"
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify default branch and refine override variable
Using master as the default HA-core branch works today, but many repositories (including Home Assistant) are migrating to main. To avoid breakage if master ever disappears, consider:

  • Verifying master exists and falling back to main.
  • Renaming the generic BRANCH variable to something more specific like HA_CORE_BRANCH to prevent collisions.

🏁 Script executed:

#!/usr/bin/env bash
# Verify whether 'master' or 'main' exists on the remote
if git ls-remote --heads https://github.com/home-assistant/core.git master | grep -q master; then
  echo "master exists"
elif git ls-remote --heads https://github.com/home-assistant/core.git main | grep -q main; then
  echo "main exists"
else
  echo "Neither 'master' nor 'main' found on remote"
  exit 1
fi

Length of output: 127


Ensure robust branch selection and avoid variable collisions
To future‑proof against a migration from master to main and prevent accidental overrides from other scripts, I recommend:

  1. Detect which default branch actually exists (master → main)
  2. Rename the generic BRANCH env var to HA_CORE_BRANCH

Suggested patch in scripts/core-testing.sh (lines 4–16):

- # By default assumes running against 'master' branch of Core-HA
- core_branch="master"
- if [ "x${BRANCH}" != "x" ]; then
-   core_branch="${BRANCH}"
- fi
+ # Determine default HA core branch: prefer 'master', fallback to 'main'
+ if git ls-remote --heads https://github.com/home-assistant/core.git master \
+     | grep -q master; then
+  default_branch="master"
+ elif git ls-remote --heads https://github.com/home-assistant/core.git main \
+     | grep -q main; then
+  default_branch="main"
+ else
+  echo "Error: neither 'master' nor 'main' found on remote"
+  exit 1
+ fi
+
+ # Allow override via HA_CORE_BRANCH (instead of generic BRANCH)
+ core_branch="${HA_CORE_BRANCH:-$default_branch}"
 
- echo "Working on HA-core branch ${core_branch}"
+ echo "Working on HA-core branch ${core_branch}"

• Update CI/docs to use HA_CORE_BRANCH instead of BRANCH.
• Verify downstream jobs/configs set the new variable name accordingly.

@bouwew bouwew merged commit 513decb into async Apr 18, 2025
8 checks passed
@bouwew bouwew deleted the rebase-fixes branch April 18, 2025 09:45
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