Skip to content

Add pre-commiy hook: pyupgrade#616

Closed
myakove wants to merge 2 commits intomainfrom
pre-commit-pyupgrade
Closed

Add pre-commiy hook: pyupgrade#616
myakove wants to merge 2 commits intomainfrom
pre-commit-pyupgrade

Conversation

@myakove
Copy link
Copy Markdown
Collaborator

@myakove myakove commented Nov 9, 2024

Summary by CodeRabbit

  • New Features

    • Updated pre-commit hooks for improved functionality and performance.
    • Added a new repository for pyupgrade to enhance code modernization.
  • Bug Fixes

    • Improved type hinting across various functions, enhancing code clarity and maintainability.
    • Simplified the installation process of the uv package in the Dockerfile.
  • Documentation

    • Enhanced documentation for updated methods and their parameters to reflect new type hints.

@myakove-bot
Copy link
Copy Markdown
Collaborator

Report bugs in Issues

The following are automatically added:

  • Add reviewers from OWNER file (in the root of the repository) under reviewers section.
  • Set PR size label.
  • New issue is created for the PR. (Closed when PR is merged/closed)
  • Run pre-commit if .pre-commit-config.yaml exists in the repo.

Available user actions:

  • To mark PR as WIP comment /wip to the PR, To remove it from the PR comment /wip cancel to the PR.
  • To block merging of PR comment /hold, To un-block merging of PR comment /hold cancel.
  • To mark PR as verified comment /verified to the PR, to un-verify comment /verified cancel to the PR.
    verified label removed on each new commit push.
  • To cherry pick a merged PR comment /cherry-pick <target branch to cherry-pick to> in the PR.
    • Multiple target branches can be cherry-picked, separated by spaces. (/cherry-pick branch1 branch2)
    • Cherry-pick will be started when PR is merged
  • To build and push container image command /build-and-push-container in the PR (tag will be the PR number).
    • You can add extra args to the Podman build command
      • Example: /build-and-push-container --build-arg OPENSHIFT_PYTHON_WRAPPER_COMMIT=<commit_hash>
  • To add a label by comment use /<label name>, to remove, use /<label name> cancel
  • To assign reviewers based on OWNERS file use /assign-reviewers
  • To check if PR can be merged use /check-can-merge
Supported /retest check runs
  • /retest tox: Retest tox
  • /retest build-container: Retest build-container
  • /retest python-module-install: Retest python-module-install
  • /retest pre-commit: Retest pre-commit
  • /retest all: Retest all
Supported labels
  • hold
  • verified
  • wip
  • lgtm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 9, 2024

Walkthrough

The pull request modifies the .pre-commit-config.yaml file by updating the versions of existing repositories and adding a new repository for pyupgrade. It also includes updates to type annotations in github_api.py and helpers.py, transitioning from older typing conventions to modern Python types. These changes enhance type hinting consistency across the codebase while maintaining existing functionality.

Changes

File Path Change Summary
.pre-commit-config.yaml - Updated ruff-pre-commit from v0.7.2 to v0.7.3
- Updated renovatebot/pre-commit-hooks from 39.0.0 to 39.8.0
- Added pyupgrade repository with version v3.19.0
webhook_server_container/libs/github_api.py - Updated type hints from Dict, List, and Optional to dict, list, and union types (`
webhook_server_container/utils/helpers.py - Updated type hints from Dict and Tuple to dict and tuple in function signatures, including get_value_from_dicts, run_command, and others.
Dockerfile - Removed UV_INSTALL_DIR environment variable
- Added installation command for uv package using pip instead of a script.

Possibly related issues

Possibly related PRs

Suggested labels

size/S, verified, can-be-merged, approved-myakove

Suggested reviewers

  • rnetser

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 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
Copy Markdown

@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

🧹 Outside diff range and nitpick comments (4)
.pre-commit-config.yaml (1)

66-69: LGTM: Well-configured pyupgrade hook addition.

The addition of pyupgrade aligns with the PR objective and will help modernize Python syntax, particularly type annotations. The chosen version (v3.19.0) is stable and recent.

Consider documenting the minimum Python version targeted by pyupgrade in a comment. This helps maintain consistency across the codebase. For example:

  - repo: https://github.com/asottile/pyupgrade
    rev: v3.19.0
    hooks:
-     - id: pyupgrade
+     - id: pyupgrade
+       # Target Python 3.8+ syntax
+       args: ["--py38-plus"]
webhook_server_container/utils/helpers.py (2)

126-127: Fix typo in function name

The type annotations are correctly updated to use built-in collection types. However, there's a typo in the function name: get_apis_and_tokes_from_config should be get_apis_and_tokens_from_config.

-def get_apis_and_tokes_from_config(config: Config, repository_name: str = "") -> list[tuple[Github, str]]:
+def get_apis_and_tokens_from_config(config: Config, repository_name: str = "") -> list[tuple[Github, str]]:

204-204: Consider enhancing docstring with type information

While the type annotation update is correct, consider improving the docstring to better document the expected return type of the futures' results.

 def get_future_results(futures: list[Future]) -> None:
     """
-    result must return Tuple[bool, str, Callable] when the Callable is Logger function (LOGGER.info, LOGGER.error, etc)
+    Process a list of futures and handle their results.
+
+    Args:
+        futures: List of futures where each future's result is expected to be
+                tuple[bool, str, Callable] where Callable is a logger function
+                (e.g., logger.info, logger.error)
     """
webhook_server_container/libs/github_api.py (1)

13-13: Excellent modernization of type hints

The systematic update of type hints from typing.Dict/List/Tuple to their built-in equivalents (dict/list/tuple) throughout the file:

  1. Aligns with PEP 585
  2. Makes the code more maintainable
  3. Prepares the codebase for future Python versions
  4. Maintains consistent type hint style

Consider adding a pre-commit hook for pyupgrade to automatically handle such type hint modernizations in the future. This would ensure consistency across the codebase and reduce manual effort.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7dfecc6 and fc56af8.

📒 Files selected for processing (3)
  • .pre-commit-config.yaml (2 hunks)
  • webhook_server_container/libs/github_api.py (46 hunks)
  • webhook_server_container/utils/helpers.py (9 hunks)
🔇 Additional comments (21)
.pre-commit-config.yaml (2)

39-39: LGTM: Safe version bump for ruff-pre-commit.

The update from v0.7.2 to v0.7.3 is a patch version change, indicating backward-compatible bug fixes.


62-62: LGTM: Compatible version update for renovate hooks.

The version bump from 39.0.0 to 39.8.0 maintains the same major version, suggesting backward compatibility.

webhook_server_container/utils/helpers.py (6)

7-7: LGTM! Simplified typing imports

The reduction of typing imports to only Any aligns well with the migration to built-in type annotations.


31-31: LGTM! Enhanced type safety with explicit annotations

Good addition of type annotation for repo_data and modernized optional type syntax.

Also applies to: 34-34


46-46: LGTM! Good use of yield from for recursive iteration

The type annotation updates are consistent, and the use of yield from improves code efficiency in recursive dictionary traversal.

Also applies to: 52-52, 55-55


67-67: LGTM! Clear return type annotation

The updated parameter and return type annotations follow modern Python typing conventions while maintaining clear type safety.

Also applies to: 71-71


142-142: LGTM! Clear nullable type annotations

Good use of explicit | None union types for nullable variables, improving code clarity and type safety.

Also applies to: 155-156, 158-158


18-19: LGTM! Modern type annotations applied correctly

The updates to use built-in generics (dict[Any, Any]) and union types (Any | None) follow modern Python typing practices (PEP 585 and PEP 604).

Also applies to: 21-21

✅ Verification successful

Modern type annotations require Python 3.9+ which is satisfied

The project's pyproject.toml specifies requires-python = ">=3.9", which supports both the built-in generics (PEP 585) and union types (PEP 604) used in the code. The type annotation changes are safe to use with the project's minimum Python version requirement.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify minimum Python version requirement is specified
rg -l "python_requires.*>=.*3.10" .

Length of output: 37


Script:

#!/bin/bash
# Check for setup.py, pyproject.toml, or other Python packaging files
fd -e py -e toml -e cfg "setup|pyproject|requirements" -x cat {}

# Also check for Python version in GitHub workflow files
fd -e yml -e yaml "workflow" .github/ -x cat {}

Length of output: 1911

webhook_server_container/libs/github_api.py (13)

90-90: LGTM: Updated type hint to use built-in dict type

The change from Dict to dict aligns with PEP 585 and modern Python type hinting practices.


98-98: LGTM: Consistently updated type hints to use built-in collection types

The changes from Dict to dict and List to list maintain consistency with PEP 585 across the class initialization.

Also applies to: 107-107, 110-110


594-595: LGTM: Updated return type and variable annotations

The changes consistently use built-in list type for annotations throughout the reviewers property.

Also applies to: 597-597


605-605: LGTM: Updated return type annotations for dictionary properties

The changes consistently use built-in dict type for the return type annotations of both properties.

Also applies to: 613-613


1610-1610: LGTM: Updated Future list type annotation

The change consistently uses built-in list type for the Future collection.


1759-1759: LGTM: Updated return type annotation

The change consistently uses built-in list type for the return type annotation.


1770-1770: LGTM: Updated list type annotations

The changes consistently use built-in list type for both return type and variable annotations.

Also applies to: 1774-1774


1830-1831: LGTM: Updated list type annotations in cherry-pick command handling

The changes consistently use built-in list type for all string list annotations.

Also applies to: 1848-1848


1867-1870: LGTM: Updated collection type annotations in retest command handling

The changes consistently use built-in list and dict types for all collection annotations.


2042-2043: LGTM: Updated list type annotations in supported retest property

The changes consistently use built-in list type for both return type and variable annotations.


2068-2068: LGTM: Updated tuple return type annotation

The change consistently uses built-in tuple type for the return type annotation.


1649-1651: LGTM: Updated dictionary type annotations in check run status

The changes consistently use built-in dict type for both optional output and kwargs annotations.


1682-1682: LGTM: Proper return type annotation for contextmanager

The Generator[None] return type correctly indicates this is a contextmanager that yields None.

Copy link
Copy Markdown

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fc56af8 and 05b1ba6.

📒 Files selected for processing (1)
  • Dockerfile (1 hunks)
🔇 Additional comments (1)
Dockerfile (1)

38-38: Verify uv version compatibility with uv.lock.

Please ensure that the installed version of uv is compatible with the version that generated the uv.lock file to maintain dependency consistency.

✅ Verification successful

Let me verify the uv.lock file contents and check if there are any compatibility issues.

Based on the uv.lock file contents shown in the output, I can see that:

  1. The lock file exists and is valid
  2. It specifies Python version requirements: ">=3.9"
  3. It contains proper dependency resolution markers and package specifications
  4. The lock file format is version 1, which is compatible with current uv versions

No version compatibility issues found between uv and uv.lock

The uv.lock file follows the standard format and there are no indicators of version incompatibility issues. The file is properly structured and contains all the necessary information for reproducible dependency installation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check uv.lock file for version compatibility

# Test: Check if uv.lock exists and examine its contents
if [ -f uv.lock ]; then
    echo "uv.lock contents:"
    cat uv.lock
else
    echo "Warning: uv.lock not found"
fi

Length of output: 177075

Comment thread Dockerfile
RUN curl -sSL https://astral.sh/uv/install.sh -o /tmp/uv-installer.sh \
&& sh /tmp/uv-installer.sh \
&& rm /tmp/uv-installer.sh
RUN python3 -m pip install uv
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance the uv installation command with best practices.

The pip installation command should follow Docker best practices:

  1. Pin the package version for reproducible builds
  2. Use --no-cache-dir to reduce image size
  3. Use --user flag when installing as non-root user

Apply this diff:

-RUN python3 -m pip install uv
+RUN python3 -m pip install --no-cache-dir --user uv==0.1.13
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
RUN python3 -m pip install uv
RUN python3 -m pip install --no-cache-dir --user uv==0.1.13

@myakove myakove closed this Nov 9, 2024
@myakove myakove deleted the pre-commit-pyupgrade branch April 6, 2025 08:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants