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

chore: Use ruff for linting and formatting #242

Merged
merged 5 commits into from
Apr 5, 2024

Conversation

mansenfranzen
Copy link
Owner

@mansenfranzen mansenfranzen commented Apr 5, 2024

Type

enhancement, bug_fix


Description

  • Refactored and updated configuration model and edge case tests for improved readability and consistency.
  • Enhanced directive options management in composites.py with type annotations and simplified logic.
  • Fixed minor issues in test cases and added coverage for additional edge cases.

Changes walkthrough

Relevant files
Tests
test_configuration_model.py
Refactor and Update Configuration Model Tests                       

tests/test_configuration_model.py

  • Refactored test cases to use simplified syntax and removed redundant
    comments.
  • Updated test cases to reflect changes in the handling of configuration
    options.
  • Improved readability and consistency across test cases.
  • +549/-464
    test_edgecases.py
    Update and Enhance Edge Case Tests                                             

    tests/test_edgecases.py

  • Updated test cases to use new syntax and conventions.
  • Fixed minor issues and improved clarity in test descriptions.
  • Added new test cases to cover additional edge cases.
  • +425/-377
    Enhancement
    composites.py
    Enhance Directive Options Management with Type Annotations

    sphinxcontrib/autodoc_pydantic/directives/options/composites.py

  • Introduced type annotations and future annotations import for better
    type checking.
  • Simplified option handling logic in directive options management.
  • Enhanced readability and maintainability of the code.
  • +56/-53 

    PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    @github-actions github-actions bot added enhancement New feature or request bug_fix labels Apr 5, 2024
    Copy link
    Contributor

    github-actions bot commented Apr 5, 2024

    PR Description updated to latest commit (4d30328)

    Copy link
    Contributor

    github-actions bot commented Apr 5, 2024

    PR Review

    ⏱️ Estimated effort to review [1-5]

    5, due to the extensive changes across multiple files, including updates to tests, documentation, and core functionality. The modifications involve both enhancements and bug fixes, which require careful review to ensure compatibility and correctness.

    🧪 Relevant tests

    Yes

    🔍 Possible issues

    Possible Bug: The changes in handling inherited members and validators might introduce issues with documentation generation or runtime behavior, especially with edge cases like identical function names or models as class attributes.

    Performance Concern: The modifications in the way JSON error strategies are handled could potentially affect the performance or error handling behavior during documentation generation.

    🔒 Security concerns

    No

    Code feedback:
    relevant filesphinxcontrib/autodoc_pydantic/directives/options/definition.py
    suggestion      

    Consider adding type annotations to the global dictionaries (OPTIONS_FIELD, OPTIONS_VALIDATOR, OPTIONS_MERGED, OPTIONS_MODEL, OPTIONS_SETTINGS) for better code readability and type checking. [medium]

    relevant lineOPTIONS_FIELD = {

    relevant filetests/test_edgecases.py
    suggestion      

    For the test_json_error_strategy_raise and similar tests, it might be beneficial to add more specific assertions to check for the type or content of the raised exception to ensure the error handling behaves as expected. [medium]

    relevant linedef test_json_error_strategy_raise(test_app):

    relevant filesphinxcontrib/autodoc_pydantic/directives/autodocumenters.py
    suggestion      

    In the PydanticModelDocumenter and other documenters, consider implementing caching mechanisms for expensive operations, such as introspection or file operations, to improve performance during documentation generation. [medium]

    relevant lineclass PydanticModelDocumenter(Documenter):

    relevant filesphinxcontrib/autodoc_pydantic/directives/options/validators.py
    suggestion      

    For options validators like option_default_true, ensure there's adequate error handling for unexpected input types to prevent runtime errors during the Sphinx documentation generation process. [medium]

    relevant linedef option_default_true(argument):


    ✨ Review tool usage guide:

    Overview:
    The review tool scans the PR code changes, and generates a PR review which includes several types of feedbacks, such as possible PR issues, security threats and relevant test in the PR. More feedbacks can be added by configuring the tool.

    The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.

    • When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:
    /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
    
    [pr_reviewer]
    some_config1=...
    some_config2=...
    

    See the review usage page for a comprehensive guide on using this tool.

    @mansenfranzen mansenfranzen merged commit 461be30 into main Apr 5, 2024
    35 of 37 checks passed
    @mansenfranzen mansenfranzen deleted the incorporate_ruff_linter_formatter branch April 5, 2024 12:16
    @github-actions github-actions bot mentioned this pull request Apr 5, 2024
    Copy link
    Contributor

    github-actions bot commented Apr 5, 2024

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Best practice
    Use append instead of insert for adding paths to sys.path.

    Instead of manually managing the insertion order for sys.path, consider using append for
    adding paths that should be searched after the already defined paths. This enhances
    readability and maintainability.

    docs/source/conf.py [21-22]

    -sys.path.insert(0, str(path.parent))
    -sys.path.insert(0, str(path_examples))
    +sys.path.append(str(path.parent))
    +sys.path.append(str(path_examples))
     
    Use str.partition for safer string splitting.

    To ensure the robustness of string manipulation, especially when dealing with external
    inputs or configurations, consider using more explicit and safer methods like
    str.partition or str.rpartition which handle cases where the delimiter is not found.

    docs/source/extensions/directives.py [14]

    -key, value = option.split('=')
    +key, value = option.partition('=')[::2]
     
    Use explicit imports for clarity and to avoid conflicts.

    Use explicit imports instead of wildcard imports for better code clarity and to avoid
    potential namespace conflicts.

    sphinxcontrib/autodoc_pydantic/init.py [27-31]

    -from sphinxcontrib.autodoc_pydantic.directives.options.enums import (
    -    OptionsFieldDocPolicy,
    -    OptionsJsonErrorStrategy,
    -    OptionsSummaryListOrder,
    -)
    +from sphinxcontrib.autodoc_pydantic.directives.options.enums import OptionsFieldDocPolicy
    +from sphinxcontrib.autodoc_pydantic.directives.options.enums import OptionsJsonErrorStrategy
    +from sphinxcontrib.autodoc_pydantic.directives.options.enums import OptionsSummaryListOrder
     
    Ensure alias option is not empty before adding it to signode in add_alias_or_name.

    To ensure the alias option is effectively utilized, add a check to ensure it's not an
    empty string before adding it to the signode in add_alias_or_name method.

    sphinxcontrib/autodoc_pydantic/directives/directives.py [135-142]

     if self.pyautodoc.is_true('field-swap-name-and-alias'):
         prefix = 'name'
         value = self.get_field_name(sig)
     else:
         prefix = 'alias'
         value = self.options.get('alias')
    +    if not value:  # Ensure alias is not empty
    +        return
     
    Use Union for type hints involving multiple possible types for clarity.

    Consider using a more explicit type hint for parent in the init method to ensure
    clarity and maintainability. The current union type hint with Documenter | Directive is
    concise but might benefit from using Union[Documenter, Directive] from the typing module
    for consistency with other type hints throughout the codebase.

    sphinxcontrib/autodoc_pydantic/directives/options/composites.py [36]

    -def __init__(self, parent: Documenter | Directive) -> None:
    +from typing import Union
    +def __init__(self, parent: Union[Documenter, Directive]) -> None:
     
    Remove unnecessary lint suppression comments to improve code cleanliness.

    To avoid potential future bugs, consider removing the unnecessary # noqa: ANN401 comments.
    These comments suppress specific linting warnings, but it's not clear why they are needed
    here. If there's a specific reason for their presence that's not immediately obvious,
    consider documenting it; otherwise, removing them could improve code cleanliness.

    sphinxcontrib/autodoc_pydantic/directives/options/composites.py [82]

    -def get_app_cfg_by_name(self, name: str) -> Any:  # noqa: ANN401
    +def get_app_cfg_by_name(self, name: str) -> Any:
     
    Readability
    Break complex list comprehensions into multiple lines for better readability.

    To improve the readability of list comprehensions and conditional expressions, consider
    breaking them into multiple lines. This is especially useful when the expression becomes
    complex.

    docs/source/extensions/directives.py [43]

    -configs = [x for x in self.env.config.values.keys() if x.startswith(startswith)]
    +configs = [
    +    x for x in self.env.config.values.keys()
    +    if x.startswith(startswith)
    +]
     
    Robustness
    Add error handling to string manipulation functions.

    When defining helper functions that manipulate strings or lists, consider adding error
    handling or checks to ensure that the input meets the expected format. This can prevent
    runtime errors and make the code more robust.

    docs/source/extensions/helper.py [14]

    -key, value = option.split('=')
    +if '=' in option:
    +    key, value = option.split('=')
    +else:
    +    key, value = option, ''
     
    Consistency
    Use consistent string quoting style throughout the code.

    For consistency and to avoid potential issues with string manipulation, consider using the
    same string quoting style (single or double quotes) throughout your code. This PR mixes
    single and double quotes.

    docs/source/extensions/directives.py [230]

    -self.arguments[0] = self.options.get('language') or 'python'
    +self.arguments[0] = self.options.get("language") or "python"
     
    Enhancement
    Use pathlib for path manipulation.

    Consider using pathlib.Path operations for path manipulation instead of string formatting
    for better readability and reliability.

    sphinxcontrib/autodoc_pydantic/init.py [80]

    -add(f'{stem}settings_show_json', True, True, bool)
    +add(stem + "settings_show_json", True, True, bool)
     
    Handle missing module version more gracefully.

    To ensure compatibility and avoid potential errors, handle the ModuleNotFoundError for
    importlib.metadata more gracefully by setting a fallback version string if the module is
    not found.

    sphinxcontrib/autodoc_pydantic/init.py [34]

    -__version__ = version('autodoc_pydantic')
    +try:
    +    __version__ = version('autodoc_pydantic')
    +except ModuleNotFoundError:
    +    __version__ = "unknown"
     
    Add specific exception handling around logger warning in swap_name_and_alias method.

    Consider using a more specific exception handling around the logger warning in
    swap_name_and_alias method to ensure that the warning is only logged for the expected
    issues. This improves the robustness of the code.

    sphinxcontrib/autodoc_pydantic/directives/directives.py [179-182]

    -logger.warning(
    -    "Field's `desc_name` node can't be located to " 'swap name with alias.',
    -    location='autodoc_pydantic',
    -)
    +try:
    +    # Code that might fail to find the `desc_name` node
    +except SpecificException as e:
    +    logger.warning(
    +        "Field's `desc_name` node can't be located to swap name with alias. Error: {}".format(e),
    +        location='autodoc_pydantic',
    +    )
     
    Simplify list initialization and extension into a single statement for clarity.

    To improve code readability and maintainability, consider using a list comprehension
    directly in the pass_through.extend() call instead of initializing pass_through with a
    single element and then extending it. This approach reduces the number of lines and makes
    the code more concise.

    sphinxcontrib/autodoc_pydantic/directives/options/composites.py [279-281]

    -pass_through = ['__doc_disable_except__']
     specific = getattr(self.parent, 'pyautodoc_pass_to_directive', [])
    -pass_through.extend(specific)
    +pass_through = ['__doc_disable_except__', *specific]
     
    Maintainability
    Reduce code duplication with a loop for adding configuration values.

    Use a loop to add multiple configuration values with similar parameters to reduce code
    duplication.

    sphinxcontrib/autodoc_pydantic/init.py [80-82]

    -add(f'{stem}settings_show_json', True, True, bool)
    -add(f'{stem}settings_show_json_error_strategy', json_strategy, True, str)
    -add(f'{stem}settings_show_config_summary', True, True, bool)
    +config_values = [
    +    ("settings_show_json", True, True, bool),
    +    ("settings_show_json_error_strategy", json_strategy, True, str),
    +    ("settings_show_config_summary", True, True, bool),
    +]
    +for name, default, rebuild, types in config_values:
    +    add(f'{stem}{name}', default, rebuild, types)
     
    Use a guard clause in swap_name_and_alias method for better readability.

    To enhance code readability and maintainability, consider using a guard clause in
    swap_name_and_alias method to return early if the condition is not met, instead of nesting
    the main logic inside an if statement.

    sphinxcontrib/autodoc_pydantic/directives/directives.py [172-173]

    -if not self.pyautodoc.get_value('field-swap-name-and-alias'):
    -    return
    +if self.pyautodoc.get_value('field-swap-name-and-alias'):
    +    # Main logic here
     
    Extract logic for adding field references to a separate method in PydanticValidator.

    To improve code maintainability, consider extracting the logic for adding field references
    to a separate method in PydanticValidator class. This will make replace_return_node method
    more concise and easier to understand.

    sphinxcontrib/autodoc_pydantic/directives/directives.py [248-255]

    -signode += self.get_field_href_from_mapping(
    -    inspector=inspector, mapping=mappings[0]
    -)
    -for mapping in mappings[1:]:
    -    signode += desc_annotation('', ', ')
    -    signode += self.get_field_href_from_mapping(
    -        inspector=inspector, mapping=mapping
    -    )
    +def add_field_references(self, signode, inspector, mappings):
    +    signode += ', '.join([self.get_field_href_from_mapping(inspector=inspector, mapping=mapping) for mapping in mappings])
     
    +# In replace_return_node method
    +self.add_field_references(signode, inspector, mappings)
    +
    Possible issue
    Check file existence before reading to prevent errors.

    Ensure that path_css exists before attempting to read from it to prevent potential
    FileNotFoundError.

    sphinxcontrib/autodoc_pydantic/init.py [49-50]

    -content = path_css.read_text()
    -(static_path / filename).write_text(content)
    +if path_css.exists():
    +    content = path_css.read_text()
    +    (static_path / filename).write_text(content)
    +else:
    +    print(f"Warning: {path_css} does not exist.")
     
    Performance
    Optimize string concatenation in handle_signature method of PydanticValidator.

    For better performance and readability, consider using a list comprehension with join
    instead of concatenating strings in a loop in the handle_signature method of
    PydanticValidator.

    sphinxcontrib/autodoc_pydantic/directives/directives.py [252-255]

    -for mapping in mappings[1:]:
    -    signode += desc_annotation('', ', ')
    -    signode += self.get_field_href_from_mapping(
    -        inspector=inspector, mapping=mapping
    -    )
    +signode += ', '.join([self.get_field_href_from_mapping(inspector=inspector, mapping=mapping) for mapping in mappings[1:]])
     
    Bug
    Correct the isinstance check to use the variable instead of a string.

    To ensure that the check for isinstance('value', set) works as intended, replace the
    string 'value' with the variable value. The current implementation mistakenly checks the
    type of the string 'value' instead of the variable value.

    sphinxcontrib/autodoc_pydantic/directives/options/composites.py [300]

    -if isinstance('value', set):
    +if isinstance(value, set):
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.

    • When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:
    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    
    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    

    See the improve usage page for a comprehensive guide on using this tool.

    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.

    1 participant