Skip to content

chore(linters): Apply ruff linter semi-automatic linting fixes#863

Merged
MaxymVlasov merged 12 commits intomasterfrom
ruff_lint
Mar 26, 2025
Merged

chore(linters): Apply ruff linter semi-automatic linting fixes#863
MaxymVlasov merged 12 commits intomasterfrom
ruff_lint

Conversation

@MaxymVlasov
Copy link
Copy Markdown
Collaborator

Description of your changes

Subset of #831

Apply next for each violation:

repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
  rev: v0.8.4
  hooks:
  - id: ruff
    args:
      - --fix
      - --unsafe-fixes
      - --select=<rulename>
  - id: ruff-format

and commit as separate commit

with same ruff.toml as in #831, except 2 last lines which enable ignore of deprecated hooks (https://github.com/antonbabenko/pre-commit-terraform/blob/948a36d52d36270c329028bd27f7a3e999c899ff/ruff.toml)

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 26, 2025

📝 Walkthrough

Summary by CodeRabbit

  • Refactor

    • Streamlined internal handling for command-line operations to ensure consistent and reliable processing.
  • Tests

    • Refined error handling and validation checks to maintain robust and predictable CLI performance.

Walkthrough

The changes modify several CLI-related modules and their tests. In the core modules, import statements are split for clarity, and type casting is adjusted to use string representations rather than direct type references. Minor formatting improvements, such as adding trailing commas, have been made. Test files now include updated error handling, assertion syntax, and revised exception raising. Overall, the modifications refine the code style and consistency across the CLI invocation functions and their tests without altering functionality.

Changes

Files Change Summary
src/.../__main__.py, src/.../_cli_parsing.py Formatting adjustments: Split combined import in __main__.py into separate statements and added a trailing comma in _cli_parsing.py for consistency.
src/.../_cli.py, src/.../terraform_docs_replace.py Type casting & argument handling: Updated cast_to calls from direct type references to string representations (e.g., 'CLIAppEntryPointCallableType', 'list[str]', 'bool'). In terraform_docs_replace.py, added a stacklevel=1 parameter to warnings and refactored list extension for process arguments.
tests/.../_cli_test.py, tests/.../terraform_docs_replace_test.py Test assertion refinements: Restored and adjusted imports, modified assertions to explicitly compare return codes, and updated exception raising by introducing intermediary variables. Additionally, a subprocess alias import was added in the terraform docs replace tests.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between 5dfea37 and 3132f17.

📒 Files selected for processing (1)
  • src/pre_commit_terraform/terraform_docs_replace.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pre_commit_terraform/terraform_docs_replace.py

Note

🎁 Summarized by CodeRabbit Free

Your organization has reached its limit of developer seats under the Pro Plan. For new users, CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please add seats to your subscription by visiting https://app.coderabbit.ai/login.If you believe this is a mistake and have available seats, please assign one to the pull request author through the subscription management page using the link above.

🪧 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 plan to trigger planning for file edits and PR creation.
  • @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.

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: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03ab152 and 9206bca.

📒 Files selected for processing (6)
  • src/pre_commit_terraform/__main__.py (1 hunks)
  • src/pre_commit_terraform/_cli.py (1 hunks)
  • src/pre_commit_terraform/_cli_parsing.py (1 hunks)
  • src/pre_commit_terraform/terraform_docs_replace.py (2 hunks)
  • tests/pytest/_cli_test.py (3 hunks)
  • tests/pytest/terraform_docs_replace_test.py (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
tests/pytest/terraform_docs_replace_test.py (4)
tests/pytest/_cli_test.py (4)
  • invoke_cli_app (61-62)
  • invoke_cli_app (91-93)
  • populate_argument_parser (55-59)
  • populate_argument_parser (85-89)
src/pre_commit_terraform/terraform_docs_replace.py (2)
  • invoke_cli_app (49-89)
  • populate_argument_parser (14-46)
src/pre_commit_terraform/_types.py (2)
  • invoke_cli_app (26-28)
  • populate_argument_parser (20-24)
src/pre_commit_terraform/_cli.py (1)
  • invoke_cli_app (16-53)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: 🧹 Linters / pre-commit@🐍3.13@ubuntu-latest
  • GitHub Check: pre-commit
🔇 Additional comments (15)
src/pre_commit_terraform/_cli_parsing.py (1)

26-26: Trailing comma added

Adding a trailing comma in multi-line function calls is a good practice that improves version control diffs and makes it easier to add parameters in the future.

src/pre_commit_terraform/__main__.py (1)

3-4: Split import statements for better readability

Splitting the import of argv and exit into separate lines follows Python best practices of one import per line, making the code more maintainable and readable.

src/pre_commit_terraform/_cli.py (1)

26-26:

Details

✅ Verification successful

String literal for type casting

Using a string literal ('CLIAppEntryPointCallableType') instead of direct type reference is aligned with the FIXME comment above that references a Stack Overflow solution for typing issues. This approach helps avoid potential circular import issues in typing.


🏁 Script executed:

#!/bin/bash
# Check if this pattern is consistently applied across the codebase
echo "Checking for other instances of cast_to in the codebase..."
rg "cast_to\(" --type py -A 1 -B 1

Length of output: 1327


Consistent String Literal Usage for Type Casting is Verified

The use of the string literal 'CLIAppEntryPointCallableType' for type casting in src/pre_commit_terraform/_cli.py is confirmed to be consistent with other instances (e.g., in src/pre_commit_terraform/terraform_docs_replace.py). This approach, aligned with the referenced FIXMEs and Stack Overflow solution, effectively avoids circular import issues in typing. No further changes are required.

tests/pytest/terraform_docs_replace_test.py (4)

8-9: Standalone pytest import

Moving pytest to its own import line follows Python styling conventions of one import per line.


13-16: Separate import blocks for better organization

Splitting the imports from the same module into separate blocks enhances readability and organization. This is a good practice that helps visualize different functional groups of imports.


87-87: Assertion order improvement

Changed the assertion order to follow the conventional pattern of assert actual == expected rather than assert expected == actual. This improves readability and matches common testing conventions.


122-122: Assertion order improvement

Same improvement as above - changed to the conventional assert actual == expected pattern, which provides more intuitive error messages when tests fail.

src/pre_commit_terraform/terraform_docs_replace.py (4)

56-56: Good addition of stacklevel parameter to warning

Adding stacklevel=2 to the warning is a proper practice that will ensure the warning points to the caller's code rather than this function. This helps users identify where in their code the deprecated hook is being used.


60-60: Improved type annotation format

Changing from direct type reference cast_to(list[str], ...) to string representation cast_to('list[str]', ...) aligns with modern Python practices for postponed evaluation of annotations (PEP 563). This is a good update.


72-72: Improved type annotation format

Similar to the previous change, using string representation for type annotations is the preferred approach in modern Python.


74-84: Code refactoring for cleaner argument building

Using procArgs.extend() with a tuple is a cleaner approach than multiple append calls. This improves code maintainability.

tests/pytest/_cli_test.py (4)

5-5: Import format update

The import formatting for pytest has been standardized, which improves code consistency.


10-10: Restored necessary import

Good restoration of PreCommitTerraformExit import, which is used in the test_app_exit function.


70-70: Improved assertion syntax

The assertion has been updated to use a more explicit equality check, which better conveys the intent of the test.


92-93: Enhanced readability with variable introduction

Introducing a variable msg before raising the exception improves readability. It's also a more maintainable approach if the message needs to be reused or built from multiple parts in the future.

'>',
'./{dir}/{dest}'.format(
dir=dir,
dest=cast_to('bool', parsed_cli_args.dest),
Copy link
Copy Markdown

@coderabbitai coderabbitai bot Mar 26, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect type casting

There's a bug in this line. You're casting parsed_cli_args.dest to 'bool' when it should be a string (default is 'README.md' as defined in line 23).

-                        dest=cast_to('bool', parsed_cli_args.dest),
+                        dest=cast_to('str', parsed_cli_args.dest),
📝 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
dest=cast_to('bool', parsed_cli_args.dest),
dest=cast_to('str', parsed_cli_args.dest),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we have this rectified please? I mean accepting coderabbit's code suggestion?

This comment was marked as off-topic.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This comment was marked as off-topic.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we have this rectified please? I mean accepting coderabbit's code suggestion?

FWIW, this is not really related to the linting violations that are being fixed in this PR. It might be better to do this separately.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Your organization has reached its limit of developer seats under the Pro Plan. In order to use the Chat feature, you need to buy additional seats

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

FWIW, this is not really related to the linting violations that are being fixed in this PR. It might be better to do this separately.

Let's do it one way or another. Coderabbit is crying and I also don't think the confusing expression is worth of keeping in code once we've found it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Your organization has reached its limit of developer seats under the Pro Plan. In order to use the Chat feature, you need to buy additional seats

yermulnik
yermulnik previously approved these changes Mar 26, 2025
@yermulnik
Copy link
Copy Markdown
Collaborator

I guess @webknjaz suggests (even insists) we make no manual changes to such PRs as their merge commits are meant to go into blame ignore file, right?
Maybe it is worth of mentioning this in PR description so that I don't even think of suggesting to rectify that incorrect casting of string to bool 😄

@webknjaz
Copy link
Copy Markdown
Contributor

@yermulnik no, these changes must not go into blame ignore at all. It's not formatting. The fact that these changes were generated by ruff does not mean that they are any less of linting fixes with runtime impact more often than not. Such patches shouldn't be hidden. Only real mass formatting should be.

@webknjaz
Copy link
Copy Markdown
Contributor

Maybe it is worth of mentioning this in PR description so that I don't even think of suggesting to rectify that incorrect casting of string to bool 😄

FWIW, once in the f-string, that entire cast_to() call might not even be necessary at all. Although, I haven't checked what MyPy reports.

@webknjaz
Copy link
Copy Markdown
Contributor

In general, it's okay to add fixes here that relate directly to fixing the rule violations. Especially, since one 55009e6 broke the CI and mandates an additional change in the tests to make it work.

Comment thread tests/pytest/_cli_test.py Outdated
@MaxymVlasov MaxymVlasov changed the title chore(linters): Apply ruff linter autofixes chore(linters): Apply ruff linter autofixes and fixes that fixes changes after autofixes Mar 26, 2025
Co-authored-by: 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко) <webknjaz@redhat.com>
Comment thread src/pre_commit_terraform/terraform_docs_replace.py Outdated
Comment thread src/pre_commit_terraform/terraform_docs_replace.py Outdated
@MaxymVlasov MaxymVlasov changed the title chore(linters): Apply ruff linter autofixes and fixes that fixes changes after autofixes chore(linters): Apply ruff linter semi-automatic linting fixes Mar 26, 2025
Comment thread src/pre_commit_terraform/terraform_docs_replace.py Outdated
@codecov
Copy link
Copy Markdown

codecov bot commented Mar 26, 2025

Codecov Report

Attention: Patch coverage is 95.23810% with 1 line in your changes missing coverage. Please review.

Project coverage is 98.44%. Comparing base (03ab152) to head (5dfea37).

Files with missing lines Patch % Lines
src/pre_commit_terraform/terraform_docs_replace.py 90.90% 1 Missing ⚠️

❌ Your patch check has failed because the patch coverage (95.23%) is below the target coverage (100.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #863   +/-   ##
=======================================
  Coverage   98.44%   98.44%           
=======================================
  Files          28       28           
  Lines         578      578           
  Branches       17       17           
=======================================
  Hits          569      569           
  Misses          9        9           
Flag Coverage Δ
CI-GHA 98.44% <95.23%> (ø)
MyPy 91.43% <85.71%> (+0.13%) ⬆️
OS-Linux 94.71% <85.71%> (+0.02%) ⬆️
OS-Windows 100.00% <100.00%> (ø)
OS-macOS 100.00% <ø> (ø)
Py-3.10.11 100.00% <100.00%> (ø)
Py-3.10.16 100.00% <ø> (ø)
Py-3.11.11 100.00% <ø> (ø)
Py-3.11.9 100.00% <100.00%> (ø)
Py-3.12.9 100.00% <100.00%> (ø)
Py-3.13.2 98.44% <95.23%> (ø)
Py-3.9.13 100.00% <100.00%> (ø)
Py-3.9.21 100.00% <ø> (ø)
VM-macos-13 100.00% <ø> (ø)
VM-macos-14 100.00% <ø> (ø)
VM-ubuntu-24.04 100.00% <ø> (ø)
VM-ubuntu-latest 91.43% <85.71%> (+0.13%) ⬆️
VM-windows-2025 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@MaxymVlasov MaxymVlasov marked this pull request as ready for review March 26, 2025 19:56
@MaxymVlasov MaxymVlasov requested a review from yermulnik March 26, 2025 19:56
@yermulnik
Copy link
Copy Markdown
Collaborator

@yermulnik no, these changes must not go into blame ignore at all. It's not formatting. The fact that these changes were generated by ruff does not mean that they are any less of linting fixes with runtime impact more often than not. Such patches shouldn't be hidden. Only real mass formatting should be.

Ah, okay, I've gone lost in the amount of these auto-semi-fixes =)

In general, it's okay to add fixes here that relate directly to fixing the rule violations. Especially, since one 55009e6 broke the CI and mandates an additional change in the tests to make it work.

@MaxymVlasov Let's get this fixed then.

FWIW, once in the f-string, that entire cast_to() call might not even be necessary at all. Although, I haven't checked what MyPy reports.

And meanwhile it's for sure isn't worthwhile to keep that incorrect casting I guess as it introduces confusion of why casting string to boolean.

@MaxymVlasov
Copy link
Copy Markdown
Collaborator Author

In general, it's okay to add fixes here that relate directly to fixing the rule violations. Especially, since one 55009e6 broke the CI and mandates an additional change in the tests to make it work.

@MaxymVlasov Let's get this fixed then.

Already fixed

@webknjaz
Copy link
Copy Markdown
Contributor

webknjaz commented Mar 26, 2025

FWIW, once in the f-string, that entire cast_to() call might not even be necessary at all. Although, I haven't checked what MyPy reports.

And meanwhile it's for sure isn't worthwhile to keep that incorrect casting I guess as it introduces confusion of why casting string to boolean.

It doesn't introduce the problem as a part of the linting fixes. It's pre-existing and would be better to address separately.

Making additional changes to an arbitrary number of places that fall out of the narrow scope of this PR will cause the same problems we're seeing in #831. Let's not contribute to unnecessary merge delays.

@yermulnik
Copy link
Copy Markdown
Collaborator

In general, it's okay to add fixes here that relate directly to fixing the rule violations. Especially, since one 55009e6 broke the CI and mandates an additional change in the tests to make it work.

@MaxymVlasov Let's get this fixed then.

Already fixed

For me it's still there 😕
image

@yermulnik
Copy link
Copy Markdown
Collaborator

yermulnik commented Mar 26, 2025

Let's not contribute to unnecessary merge delays.

I'm ok to approve and will do it now, though the delay is because we can't agree on the most greatest way to fix this single bit of obviously wrong code bit 🤷🏻 Get this fixed and, while you both are on it, you'll catch if any part of the code relies upon this incorrect bit of code (as opposite to postponing this to a separate PR that who knows whether we won't miss to create).

@webknjaz
Copy link
Copy Markdown
Contributor

For me it's still there 😕

It's not the same thing you're quoting.

@webknjaz
Copy link
Copy Markdown
Contributor

Get this fixed and, while you both are on it, you catch if any part of the code relies upon this incorrect bit of code.

That cast only influences MyPy runs. It exists to make MyPy interpret things as certain types, as a hack. It doesn't have any effect in runtime whatsoever.

@yermulnik
Copy link
Copy Markdown
Collaborator

For me it's still there 😕

It's not the same thing you're quoting.

I'm not following you. My point is about that odd cast from string to bool. I'm talking about it and only it. So I just can't be quoting something else 🤷🏻

Get this fixed and, while you both are on it, you catch if any part of the code relies upon this incorrect bit of code.

That cast only influences MyPy runs. It exists to make MyPy interpret things as certain types, as a hack. It doesn't have any effect in runtime whatsoever.

Honestly, I don't really care what that cast is for. It is confusing and I'd like this fixed.
Nothing else. Just a fix while you both are working on this.

@MaxymVlasov
Copy link
Copy Markdown
Collaborator Author

@yermulnik please create follow-up PR that will fix this cast. Tnx

@MaxymVlasov MaxymVlasov merged commit 4366a73 into master Mar 26, 2025
40 checks passed
@MaxymVlasov MaxymVlasov deleted the ruff_lint branch March 26, 2025 20:47
@yermulnik
Copy link
Copy Markdown
Collaborator

@yermulnik please create follow-up PR that will fix this cast. Tnx

#864

@antonbabenko
Copy link
Copy Markdown
Owner

This PR is included in version 1.98.1 🎉

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.

4 participants