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

style: format code with Ruff Formatter #14

Open
wants to merge 2 commits into
base: develop-ng
Choose a base branch
from

Conversation

deepsource-autofix[bot]
Copy link

@deepsource-autofix deepsource-autofix bot commented Jan 31, 2025

This commit fixes the style issues introduced in 9badcb6 according to the output
from Ruff Formatter.

Details: None

Summary by Sourcery

Enhancements:

  • Reformat code across multiple test files to improve readability and maintainability by consolidating multi-line statements into single lines where possible.

This commit fixes the style issues introduced in 9badcb6 according to the output
from Ruff Formatter.

Details: None
Copy link

korbit-ai bot commented Jan 31, 2025

By default, I don't review pull requests opened by bots. If you would like me to review this pull request anyway, you can request a review via the /korbit-review command in a comment.

Copy link

evolua-app bot commented Jan 31, 2025

Welcome @deepsource-autofix[bot]! 🎉

Great PR! I've analyzed your code changes for:

  • 🔒 Security vulnerabilities
  • ✨ Code quality improvements
  • 🎯 Best practices alignment

Ready to see the full review?
Head over to https://evolua.io to:

  • Create your free account
  • Get detailed insights
  • Unlock automated PR reviews
  • Ensure high-quality code

Let's make your code even better together! 🚀

Copy link

coderabbitai bot commented Jan 31, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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.

Copy link

sourcery-ai bot commented Jan 31, 2025

Reviewer's Guide by Sourcery

The pull request applies code style formatting using Ruff Formatter across multiple test and source files. It primarily involves reformatting function parameters, assertion methods, import statements, and class attribute definitions to improve consistency and readability.

Flow diagram of code formatting changes

graph TD
    A[Source Code] -->|Ruff Formatter| B[Formatted Code]
    subgraph Changes
    C[Import Statement Formatting]
    D[Function Parameter Formatting]
    E[Class Attribute Formatting]
    end
    B --> C
    B --> D
    B --> E
    style B fill:#90EE90
    style C fill:#FFE4B5
    style D fill:#FFE4B5
    style E fill:#FFE4B5
Loading

File-Level Changes

Change Details Files
Reformatting of test function parameters and assertions for consistency and readability.
  • Reformatted function parameters to be on a single line where possible.
  • Reformatted assertion methods to be on a single line where possible.
tests/test_cli.py
tests/test_style.py
tests/test_ini.py
tests/test_json.py
tests/test_yaml_pre_commit.py
tests/test_yaml_github_workflows.py
tests/test_yaml_old_pre_commit.py
tests/test_builtin.py
tests/test_project.py
tests/test_toml.py
tests/test_yaml.py
Reformatting of import statements for consistency.
  • Reformatted import statements to be on a single line where possible.
src/nitpick/core.py
src/nitpick/style.py
Reformatting of class attribute definitions for consistency.
  • Reformatted class attribute definitions to be on a single line where possible.
src/nitpick/violations.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

We have skipped reviewing this pull request. It seems to have been created by a bot (hey, deepsource-autofix[bot]!). We assume it knows what it's doing!

Copy link

deepsource-io bot commented Jan 31, 2025

Here's the code health analysis summary for commits 754acfa..5c41201. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource Python LogoPython✅ SuccessView Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

Applied Ruff Formatter across multiple Python files to standardize code formatting, focusing on consistent style and improved readability.

  • Consolidated multi-line method chains into single lines in test files for better conciseness
  • Removed unnecessary trailing commas and line breaks throughout the codebase
  • Reformatted NO_ROOT_DIR violation message in violations.py from multi-line to single line
  • Simplified function calls and parameter alignments while maintaining functionality
  • Standardized import statements by consolidating related imports into single lines

💡 (1/5) You can manually trigger the bot by mentioning @greptileai in a comment!

15 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings | Greptile

Comment on lines 310 to +312
for tag, rows in library.items():
lines.extend(["", tag, "~" * len(tag), ""])
lines.extend(
rst_table(
(
"Style URL",
"Description",
),
rows,
)
)
lines.extend(rst_table(("Style URL", "Description"), rows))

Choose a reason for hiding this comment

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

The repeated calls to rst_table within the loop for each tag can lead to performance issues, especially if the number of tags is large. Each call to rst_table processes and formats the table, which could be inefficient.

Recommendation: Consider restructuring the code to accumulate all necessary data first and then make a single call to rst_table outside the loop. This would reduce the overhead of repeated function calls and improve performance.

Comment on lines 309 to 313
lines = []
for tag, rows in library.items():
lines.extend(["", tag, "~" * len(tag), ""])
lines.extend(
rst_table(
(
"Style URL",
"Description",
),
rows,
)
)
lines.extend(rst_table(("Style URL", "Description"), rows))
return lines

Choose a reason for hiding this comment

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

The function _build_library directly manipulates list operations like extend within the loop to build the final list of lines. This approach is tightly coupled with the data structure and formatting details, which can hinder maintainability and readability.

Recommendation: Abstract these operations into a more cohesive function or use a higher-level data structure that encapsulates these details. This would make the code easier to read, maintain, and modify in the future.

Comment on lines 803 to 809
if library_dir:
# Style in a directory
from_resources_root = without_suffix.relative_to(library_dir)
bis = BuiltinStyle(
formatted=str(without_suffix),
path_from_resources_root=from_resources_root.as_posix(),
)
bis = BuiltinStyle(formatted=str(without_suffix), path_from_resources_root=from_resources_root.as_posix())
else:
# Style from the built-in library
package_path = resource_path.relative_to(builtin_resources_root().parent.parent)

Choose a reason for hiding this comment

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

The code lacks error handling for the relative_to method, which can raise a ValueError if resource_path is not a subpath of library_dir or builtin_resources_root(). This can lead to uncaught exceptions that disrupt the execution flow.

Recommended Solution:
Add error handling around the relative_to calls to manage the potential ValueError, possibly logging an error and skipping the current iteration or providing a fallback mechanism.

formatted=str(without_suffix),
path_from_resources_root=from_resources_root.as_posix(),
)
bis = BuiltinStyle(formatted=str(without_suffix), path_from_resources_root=from_resources_root.as_posix())
else:
# Style from the built-in library

Choose a reason for hiding this comment

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

The function builtin_resources_root() is called twice in close succession within the same block of code. Since the result of this function is cached, it's more efficient to call it once and store the result in a variable if it's used multiple times in the same scope.

Recommended Solution:
Store the result of builtin_resources_root() in a variable and use this variable instead of calling the function repeatedly.

Comment on lines 75 to 81
class ProjectViolations(ViolationEnum):
"""Project initialization violations."""

NO_ROOT_DIR = (
101,
f"No root directory detected.{CONFIG_RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY}",
)
NO_ROOT_DIR = (101, f"No root directory detected.{CONFIG_RUN_NITPICK_INIT_OR_CONFIGURE_STYLE_MANUALLY}")
NO_PYTHON_FILE = (102, "No Python file was found on the root dir and subdir of {root!r}")
MISSING_FILE = (103, " should exist{extra}")
FILE_SHOULD_BE_DELETED = (104, " should be deleted{extra}")

Choose a reason for hiding this comment

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

Uniqueness of Error Codes

The error codes defined in ProjectViolations (101, 102, 103, 104) need to be unique not only within this enum but across the entire application to avoid conflicts. If there are other enums or systems that define error codes, it's crucial to ensure that these codes do not overlap with others.

Recommendation: Implement a centralized system or registry to manage all error codes across different modules or classes to prevent duplication and ensure each code is unique.

Comment on lines 153 to 159
age: 27
from: Liverpool
""",
),
)
).assert_file_contents(filename, datadir / "jmes-list-key-expected.yaml")
project.api_check().assert_violations()

Choose a reason for hiding this comment

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

The nested YAML structure defined in the test is complex and could affect readability and maintainability. Simplifying these structures or breaking them down into smaller, more manageable components could improve the clarity and maintainability of the test code. Consider refactoring to reduce complexity and enhance readability.

Comment on lines 31 to 38
- name: Install tox
run: python -m pip install tox
""",
),
).assert_file_contents(
filename, datadir / "dict-search-by-key-expected.yaml"
).api_check().assert_violations()
)
).assert_file_contents(filename, datadir / "dict-search-by-key-expected.yaml").api_check().assert_violations()


def test_list_of_scalars_only_add_elements_that_do_not_exist(tmp_path, datadir):

Choose a reason for hiding this comment

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

The test function test_list_of_dicts_search_missing_element_by_key_and_change_add_element_individually lacks direct assertions within the test body, which could lead to unclear test outcomes. It's important for test functions to include assertions that directly relate to the expected outcomes to ensure clarity and effectiveness of the tests.

Recommendation:
Include assertions within the test function to check that the workflow steps are correctly modified or added as expected. This will make the test outcomes more transparent and easier to understand.

Comment on lines 130 to +133
uses: actions/replacing-duplicated-element@v2
""",
)
).assert_file_contents(
filename, datadir / "same-key-expected.yaml"
).api_check().assert_violations()
).assert_file_contents(filename, datadir / "same-key-expected.yaml").api_check().assert_violations()

Choose a reason for hiding this comment

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

The test test_more_than_one_element_with_the_same_key_only_first_one_will_be_considered checks for duplicated keys but does not handle or report duplicates beyond the first occurrence. This might not reflect the actual behavior needed in workflows where multiple occurrences of the same key could lead to issues.

Recommendation:
Enhance the test to handle and assert the behavior or errors when multiple occurrences of the same key are present. This will ensure the test is robust and reflects more realistic scenarios.

Comment on lines 171 to 177
- hooks:
- id: whatever
"""
).api_check_then_fix(
Fuss(True, PRE_COMMIT_CONFIG_YAML, 368, " has missing values:", "fail_fast: true")
)
).api_check_then_fix(Fuss(True, PRE_COMMIT_CONFIG_YAML, 368, " has missing values:", "fail_fast: true"))


def test_missing_repo_key(tmp_path):

Choose a reason for hiding this comment

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

The test test_missing_repos uses a typo 'grepos' instead of 'repos'. If this is intended to simulate an error condition, it would be beneficial to add a comment explaining that this is intentional to avoid confusion for future maintainers. If it's an actual mistake, correcting it to 'repos' would be necessary to ensure the test's validity.

Comment on lines 434 to 442
[tool.nitpick]
style = ["root", "mypy", "pre-commit/python", "pre-commit/bash"]
"""
).pre_commit(
datadir / "2-untouched-pre-commit.yaml"
).api_check_then_fix(
partial_names=[PRE_COMMIT_CONFIG_YAML],
).assert_file_contents(
PRE_COMMIT_CONFIG_YAML, datadir / "2-untouched-pre-commit.yaml"
)
).pre_commit(datadir / "2-untouched-pre-commit.yaml").api_check_then_fix(
partial_names=[PRE_COMMIT_CONFIG_YAML]
).assert_file_contents(PRE_COMMIT_CONFIG_YAML, datadir / "2-untouched-pre-commit.yaml")


def test_pre_commit_section_without_dot_deprecated(tmp_path):

Choose a reason for hiding this comment

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

The test in lines 434-442 checks that the pre-commit configuration file remains unchanged after loading multiple styles. To enhance this test, consider verifying specific properties or settings within the file to ensure that all configurations from the multiple styles are applied correctly. This would provide a more robust test of the system's ability to handle multiple configurations.

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.

1 participant