Skip to content

Format and lint#27

Merged
leynos merged 3 commits intomainfrom
codex/run-ruff-to-format-and-fix-lint-errors
Jul 7, 2025
Merged

Format and lint#27
leynos merged 3 commits intomainfrom
codex/run-ruff-to-format-and-fix-lint-errors

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 7, 2025

Summary

  • run ruff format for consistent formatting
  • tighten ruff linting across action scripts and tests
  • clean up shell stub implementation
  • improve test utilities
  • fix argument forwarding bug in run_rust.py

Testing

  • ruff check
  • pytest -q

https://chatgpt.com/codex/tasks/task_e_686c1dc5bcac832282d77c26e347ad8f

Summary by Sourcery

Apply consistent code formatting and linting, refactor stub framework, tighten typing in tests, update action scripts, and fix a run_rust argument forwarding bug.

Bug Fixes:

  • Fix argument forwarding in run_rust.py by enforcing keyword-only with_default parameter

Enhancements:

  • Apply ruff format and tighten linting across all scripts and tests
  • Refactor shellstub module to reorganize imports, adopt dataclasses alias, and simplify variant parsing
  • Enhance test utilities by adding TYPE_CHECKING guards, docstrings, and simplifying pytest fixtures
  • Standardize Typer option definitions and use forward annotations in coverage and ratchet coverage scripts

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 7, 2025

Reviewer's Guide

This PR applies ruff-based formatting and stricter linting across modules, refactors the shell stub framework for clearer type handling and list processing, enhances test utilities with TYPE_CHECKING guards and fixture cleanup, and standardizes CI action scripts—consolidating Option definitions and fixing argument forwarding in run_rust.py.

Sequence diagram for argument forwarding fix in run_rust.py

sequenceDiagram
    participant User as actor User
    participant run_rust as run_rust.py
    participant get_cargo_coverage_cmd as get_cargo_coverage_cmd
    participant cargo as cargo

    User->>run_rust: invoke main(..., with_default=...)
    run_rust->>get_cargo_coverage_cmd: call with fmt, out, features, with_default=with_default
    get_cargo_coverage_cmd-->>run_rust: return args
    run_rust->>cargo: cargo[args].run()
    cargo-->>run_rust: retcode, stdout, stderr
    run_rust-->>User: process result
Loading

Class diagram for refactored shell stub framework

classDiagram
    class Call {
        +str cmd
        +list[str] argv
        +str cwd
        +str timestamp
    }
    class Variant {
        +Sequence[str] match
        +str stdout
        +str stderr
        +int exit_code
    }
    class StubSpec {
        +list[Variant] variants
        +Callable[[Sequence[str]], int] func
    }
    class StubManager {
        +Path dir
        +register(name, variants, ...)
        +calls_of(name)
        +env
    }
    StubSpec --> Variant : contains
    StubManager --> StubSpec : manages
    StubManager --> Call : records
Loading

File-Level Changes

Change Details Files
Refactored the shellstub implementation for consistency and type safety
  • Moved future import below module docstring and grouped imports using typing aliases
  • Switched to dc.dataclass for annotations and wrapped type-only imports in TYPE_CHECKING guards
  • Replaced manual loop with list comprehension when parsing variants
  • Removed redundant blank lines and unified JSON write formatting
shellstub.py
Cleaned up test utilities and fixtures
  • Added module-level docstrings to clarify purpose
  • Introduced TYPE_CHECKING guards around StubManager imports
  • Converted pytest fixture from yield-based to return-based
  • Consolidated environment-variable setup and removed extra blank lines
  • Added noqa comments to suppress lint warnings in tests
.github/actions/generate-coverage/tests/conftest.py
.github/actions/generate-coverage/tests/test_scripts.py
Standardized formatting, tightened lint rules, and fixed run_rust argument forwarding in CI scripts
  • Prefixed each script with a module docstring and future annotations
  • Extracted repeated typer.Option declarations into top-level constants
  • Reordered and cleaned up imports (ElementTree, enum.StrEnum, TYPE_CHECKING guards)
  • Applied consistent whitespace, trailing commas, and noqa where needed
  • In run_rust.py: set WITH_DEFAULT_OPT default, added '*' to signature, and passed with_default as a keyword
.github/actions/generate-coverage/scripts/*.py
.github/actions/ratchet-coverage/scripts/*.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!

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 7, 2025

Summary by CodeRabbit

  • Style

    • Improved code readability and consistency through formatting adjustments and import reorganisation.
    • Enhanced type hinting and annotations for greater clarity.
    • Added and updated module-level docstrings for better documentation.
  • Refactor

    • Updated function signatures to use named option constants and keyword-only arguments in several scripts, improving clarity and maintainability.
  • Tests

    • Refined test utilities and fixtures for improved readability and type hinting without altering test logic.

Summary by CodeRabbit

  • Refactor

    • Improved code readability and maintainability through import restructuring, enhanced type hinting, and formatting adjustments across scripts and test files.
    • Updated function signatures to use keyword-only arguments and module-level option constants for greater clarity in several scripts.
    • Added module-level docstrings for improved documentation and code understanding.
    • Minor stylistic changes made to test utilities and script outputs without affecting functionality.
  • Style

    • Improved code readability and consistency through import restructuring, formatting adjustments, and enhanced type hinting across scripts and tests.
  • Refactor

    • Updated several function signatures to use keyword-only arguments and extracted option definitions for clarity and maintainability.
  • Documentation

    • Added module-level docstrings to multiple scripts and test files for better context and understanding.

Walkthrough

This update refactors several scripts and test files in the coverage utility actions. The changes focus on import style improvements, use of from __future__ import annotations, extraction of Typer option definitions into constants, function signature updates for clarity, enhanced type hinting, and formatting adjustments. No core logic or control flow is altered.

Changes

File(s) Change Summary
.github/actions/generate-coverage/scripts/detect.py,
.github/actions/generate-coverage/scripts/run_python.py,
.github/actions/generate-coverage/scripts/run_rust.py,
.github/actions/generate-coverage/scripts/ratchet_coverage.py,
.github/actions/ratchet-coverage/scripts/ratchet_coverage.py,
.github/actions/ratchet-coverage/scripts/run_coverage.py
Added from __future__ import annotations, improved import styles, extracted Typer option constants, updated function signatures for clarity.
.github/actions/generate-coverage/scripts/merge_cobertura.py Reformatted Typer option declarations and exception handling for readability; no logic changes.
.github/actions/generate-coverage/tests/conftest.py,
.github/actions/generate-coverage/tests/test_scripts.py
Added module docstrings, improved type hinting via conditional imports, simplified fixture and assertion formatting.
.github/actions/ratchet-coverage/scripts/install_cargo_llvm_cov.py Added a module-level docstring; no other changes.
shellstub.py Refactored imports, improved type hinting, reformatted dataclass usage, and made minor formatting changes.

Possibly related PRs

  • leynos/shared-actions#23: Adds the initial detect.py script, which is directly affected by the import style changes in this PR.

Poem

A rabbit hopped through lines of code,
Tidying imports on the road.
Typer options now stand tall,
With docstrings greeting one and all.
No logic changed, just style anew—
🐇✨ Clean code for me and you!

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/run-ruff-to-format-and-fix-lint-errors

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests 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
Copy Markdown
Contributor

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

Hey @leynos - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `shellstub.py:28` </location>
<code_context>
     """Possible behaviour for a stub based on its arguments."""

-    match: Sequence[str] | None
+    match: cabc.Sequence[str] | None
     stdout: str = ""
     stderr: str = ""
</code_context>

<issue_to_address>
Using cabc.Sequence in dataclass field type may cause runtime issues.

Referencing cabc.Sequence at runtime may raise a NameError since cabc is only imported under TYPE_CHECKING. Use t.Sequence or import cabc unconditionally if runtime usage is needed.
</issue_to_address>

### Comment 2
<location> `shellstub.py:39` </location>
<code_context>

     variants: list[Variant]
-    func: Callable[[Sequence[str]], int] | None = None
+    func: cabc.Callable[[cabc.Sequence[str]], int] | None = None


</code_context>

<issue_to_address>
Potential NameError for cabc.Callable in StubSpec if not imported at runtime.

Referencing cabc.Callable at runtime will cause a NameError if cabc is only imported under TYPE_CHECKING. Use t.Callable or import cabc unconditionally.
</issue_to_address>

### Comment 3
<location> `shellstub.py:5` </location>
<code_context>

+from __future__ import annotations
+
+import dataclasses as dc
 import json
 import os
</code_context>

<issue_to_address>
Consider removing import aliases and using direct imports for dataclasses and type hints to simplify the code.

```suggestion
# Simplify imports and type‐hints: remove `dc`, `t`, `cabc` aliases and use direct imports.

- Replace:
    ```python
    import dataclasses as dc
    import typing as t

    if t.TYPE_CHECKING:
        import collections.abc as cabc

    @dc.dataclass
    class Variant:
        match: cabc.Sequence[str] | None
    ...
    func: cabc.Callable[[cabc.Sequence[str]], int] | None
    ```
  With:
    ```python
    from dataclasses import dataclass
    from collections.abc import Callable, Sequence

    @dataclass
    class Variant:
        match: Sequence[str] | None
    ...
    func: Callable[[Sequence[str]], int] | None
    ```

- Remove the `if TYPE_CHECKING` block entirely (thanks to `from __future__ import annotations`, the hints won’t be evaluated at runtime).

This restores clarity without changing any behavior.
</issue_to_address>

### Comment 4
<location> `.github/actions/generate-coverage/scripts/run_python.py:14` </location>
<code_context>
 from pathlib import Path

-import defusedxml.ElementTree as ET
+import defusedxml.ElementTree as ElementTree
 import typer
 from plumbum import FG
</code_context>

<issue_to_address>
Use 'as ET' for ElementTree import to avoid confusion and maintain consistency with previous code.

The previous code used 'import defusedxml.ElementTree as ET', and the function 'percent_from_xml' still refers to 'ET'. Changing the alias to 'ElementTree' may cause confusion or break code that expects 'ET'. Please revert to 'as ET' unless you update all references accordingly.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread shellstub.py
"""Possible behaviour for a stub based on its arguments."""

match: Sequence[str] | None
match: cabc.Sequence[str] | None
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.

issue (bug_risk): Using cabc.Sequence in dataclass field type may cause runtime issues.

Referencing cabc.Sequence at runtime may raise a NameError since cabc is only imported under TYPE_CHECKING. Use t.Sequence or import cabc unconditionally if runtime usage is needed.

Comment thread shellstub.py

variants: list[Variant]
func: Callable[[Sequence[str]], int] | None = None
func: cabc.Callable[[cabc.Sequence[str]], int] | None = None
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.

issue (bug_risk): Potential NameError for cabc.Callable in StubSpec if not imported at runtime.

Referencing cabc.Callable at runtime will cause a NameError if cabc is only imported under TYPE_CHECKING. Use t.Callable or import cabc unconditionally.

Comment thread shellstub.py

from __future__ import annotations

import dataclasses as dc
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.

issue (complexity): Consider removing import aliases and using direct imports for dataclasses and type hints to simplify the code.

Suggested change
import dataclasses as dc
# Simplify imports and type‐hints: remove `dc`, `t`, `cabc` aliases and use direct imports.
- Replace:
```python
import dataclasses as dc
import typing as t
if t.TYPE_CHECKING:
import collections.abc as cabc
@dc.dataclass
class Variant:
match: cabc.Sequence[str] | None
...
func: cabc.Callable[[cabc.Sequence[str]], int] | None
```
With:
```python
from dataclasses import dataclass
from collections.abc import Callable, Sequence
@dataclass
class Variant:
match: Sequence[str] | None
...
func: Callable[[Sequence[str]], int] | None
```
- Remove the `if TYPE_CHECKING` block entirely (thanks to `from __future__ import annotations`, the hints wont be evaluated at runtime).
This restores clarity without changing any behavior.

from pathlib import Path

import defusedxml.ElementTree as ET
import defusedxml.ElementTree as ElementTree
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.

issue (review_instructions): Use 'as ET' for ElementTree import to avoid confusion and maintain consistency with previous code.

The previous code used 'import defusedxml.ElementTree as ET', and the function 'percent_from_xml' still refers to 'ET'. Changing the alias to 'ElementTree' may cause confusion or break code that expects 'ET'. Please revert to 'as ET' unless you update all references accordingly.

Review instructions:

Path patterns: **/*

Instructions:
Create code-review comments for ALL issues. Avoid making general observations or non-specific feedback if at all possible.

Copy link
Copy Markdown
Contributor

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1bf794a and 15204a4.

📒 Files selected for processing (11)
  • .github/actions/generate-coverage/scripts/detect.py (1 hunks)
  • .github/actions/generate-coverage/scripts/merge_cobertura.py (2 hunks)
  • .github/actions/generate-coverage/scripts/ratchet_coverage.py (2 hunks)
  • .github/actions/generate-coverage/scripts/run_python.py (3 hunks)
  • .github/actions/generate-coverage/scripts/run_rust.py (3 hunks)
  • .github/actions/generate-coverage/tests/conftest.py (1 hunks)
  • .github/actions/generate-coverage/tests/test_scripts.py (2 hunks)
  • .github/actions/ratchet-coverage/scripts/install_cargo_llvm_cov.py (1 hunks)
  • .github/actions/ratchet-coverage/scripts/ratchet_coverage.py (2 hunks)
  • .github/actions/ratchet-coverage/scripts/run_coverage.py (2 hunks)
  • shellstub.py (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`.github/actions/*/tests/**/*`: Contract tests must validate that declared inputs/outputs round-trip correctly

.github/actions/*/tests/**/*: Contract tests must validate that declared inputs/outputs round-trip correctly

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • .github/actions/generate-coverage/tests/test_scripts.py
  • .github/actions/generate-coverage/tests/conftest.py
🧬 Code Graph Analysis (2)
.github/actions/generate-coverage/tests/test_scripts.py (1)
shellstub.py (2)
  • StubManager (42-156)
  • env (101-106)
.github/actions/generate-coverage/tests/conftest.py (1)
shellstub.py (1)
  • StubManager (42-156)
🔇 Additional comments (33)
.github/actions/ratchet-coverage/scripts/install_cargo_llvm_cov.py (1)

6-6: Excellent documentation improvement!

The added module-level docstring clearly describes the script's purpose and aligns with the PR's code quality objectives.

.github/actions/generate-coverage/scripts/detect.py (2)

8-8: Good addition of future import for modern Python type hinting.

The from __future__ import annotations import enables postponed evaluation of type annotations, which is beneficial for Python 3.12+ and aligns with the project's modernisation efforts.


10-10: Import style improvement enhances code clarity.

The change from from enum import StrEnum to import enum and corresponding usage as enum.StrEnum improves code readability by making the module origin explicit.

Also applies to: 17-17

.github/actions/generate-coverage/scripts/ratchet_coverage.py (3)

6-6: Excellent documentation and future import addition.

The module-level docstring clearly describes the script's purpose, and the future import enables modern Python type hinting practices.

Also applies to: 8-8


14-17: Good refactoring to extract typer options into constants.

Extracting the typer.Option definitions into named constants improves code maintainability and readability by centralising the configuration.


30-33: Excellent API improvement with keyword-only parameter.

Making the current parameter keyword-only prevents accidental positional argument mistakes and makes the function calls more explicit and readable.

.github/actions/generate-coverage/scripts/run_rust.py (4)

8-8: Good modernisation with future import and linting compliance.

The future import enables modern type hinting, and the noqa comment appropriately addresses the linter concern about the Path import used at runtime.

Also applies to: 11-11


19-19: Clearer option definition with explicit default value.

Explicitly specifying default=True instead of relying on positional arguments improves code clarity and maintainability.


26-26: Excellent API improvement with keyword-only parameters.

Making the with_default parameter keyword-only in both functions prevents accidental positional argument mistakes and makes the function signatures more explicit.

Also applies to: 54-55


66-66: Critical bug fix for argument forwarding.

The change to pass with_default as a keyword argument fixes the argument forwarding issue mentioned in the PR summary, ensuring the parameter is correctly passed to the function.

.github/actions/generate-coverage/scripts/merge_cobertura.py (2)

14-27: Improved readability with better formatting.

The reformatted typer.Option declarations with arguments on separate lines enhance code readability whilst maintaining the same functionality.


40-43: Consistent formatting improvement.

The reformatted typer.echo call with the err=True argument on a new line improves consistency and readability.

.github/actions/generate-coverage/tests/test_scripts.py (4)

1-2: Good addition of module docstring.

The descriptive docstring improves code documentation and follows Python conventions.


6-10: Appropriate use of conditional import for type hints.

Moving the StubManager import under TYPE_CHECKING reduces runtime import overhead whilst preserving type annotations. This aligns with modern Python typing practices.


117-118: Improved assertion clarity.

Splitting the combined assertion into two separate assertions improves test readability and provides more specific failure information when tests fail.


18-18: Subprocess security suppression justified in test context

The # noqa: S603 is scoped to .github/actions/generate-coverage/tests/test_scripts.py:18, where run_script lives entirely within a controlled test harness. Key points:

  • This helper is only used by tests under .github/actions/generate-coverage/tests/.
  • Inputs (tmp_path, static --script flag, and any *args) come from fixtures or test code—not external sources.
  • A StubManager intercepts the actual uv run invocation, eliminating injection risks.

Suppressing the Bandit warning here is appropriate.

.github/actions/generate-coverage/scripts/run_python.py (6)

8-9: Good addition of future annotations.

The from __future__ import annotations import enables modern type hinting and aligns with the project's Python 3.12+ requirement.


11-11: Appropriate typing import.

Adding typing as t provides access to TYPE_CHECKING for conditional imports whilst maintaining concise code.


14-14: Improved import alias clarity.

Changing from ET to ElementTree makes the code more readable and explicit about the imported module.


20-22: Correct use of conditional import for type hints.

Moving BoundCommand import under TYPE_CHECKING reduces runtime overhead whilst preserving type annotations for the return type in line 29.


48-48: Consistent with import alias change.

The function call correctly uses ElementTree.parse to match the updated import alias.


64-66: Improved formatting of multi-line function call.

The reformatted typer.echo call with err=True on a separate line improves readability and follows consistent formatting practices.

.github/actions/ratchet-coverage/scripts/ratchet_coverage.py (3)

6-9: Excellent documentation and typing improvements.

The module docstring clearly describes the script's purpose, and the future annotations import enables modern type hinting practices.


25-30: Good extraction of Option constants.

Extracting the typer.Option definitions into named constants improves code organisation and makes the options more reusable and maintainable.


31-35: Appropriate use of keyword-only arguments.

Making current a keyword-only argument improves the function signature clarity and prevents accidental positional argument usage.

.github/actions/generate-coverage/tests/conftest.py (4)

1-2: Good addition of module docstring.

The docstring clearly describes the file's purpose as common test utilities for coverage scripts.


7-13: Appropriate conditional import for type hints.

Moving StubManager import under TYPE_CHECKING reduces runtime overhead whilst preserving type annotations for the fixture return type.


21-21: Simplified error message is adequate.

The error message change from a formatted string to just the start path string is simpler and still provides the necessary information for debugging.


31-40: Appropriate fixture implementation change.

Moving the StubManager import inside the fixture function and returning the manager directly instead of yielding is correct since no cleanup is needed. The fixture properly configures the environment and global manager.

.github/actions/ratchet-coverage/scripts/run_coverage.py (4)

6-9: Good documentation and typing improvements.

The module docstring clearly describes the script's functionality, and the future annotations import enables modern type hinting.


12-12: Appropriate noqa comment for runtime usage.

The # noqa: TC003 comment correctly suppresses the type checker warning since Path is indeed used at runtime in the function signature.


28-31: Excellent extraction of Option constants.

Extracting the typer.Option definitions into named constants improves code organisation and makes the configuration more maintainable.


32-36: Appropriate use of keyword-only arguments.

Making both arguments keyword-only improves the function signature clarity and prevents accidental positional argument usage, which is especially important for CLI scripts.

Comment thread shellstub.py Outdated
Comment thread shellstub.py Outdated
Copy link
Copy Markdown
Contributor

@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 (1)
shellstub.py (1)

31-37: Alias style unchanged – see earlier discussion

The switch to dc.dataclass / cabc.* aliases keeps the original indirection that was previously suggested for removal. Re-iterating here for completeness.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15204a4 and 56e5d6e.

📒 Files selected for processing (2)
  • .github/actions/generate-coverage/scripts/run_python.py (2 hunks)
  • shellstub.py (4 hunks)
🔇 Additional comments (5)
.github/actions/generate-coverage/scripts/run_python.py (3)

8-12: Future-style annotations & typing alias look good
Using from __future__ import annotations together with import typing as t keeps runtime imports minimal and avoids circular-import surprises.


14-14: Alias ET restored – resolves prior confusion
Re-introducing as ET preserves the expected identifier across the codebase and matches earlier review feedback.


64-66: Minor echo-formatting tweak clears Ruff NQA warnings
Breaking the typer.echo arguments onto separate lines is fine and keeps line length in check.

shellstub.py (2)

5-6: Runtime-safe import looks good

Importing collections.abc unconditionally removes the earlier NameError risk flagged in previous reviews.
No further action needed.


81-81: 👍 Switched to dc.asdict for serialisation

Using dataclasses.asdict instead of __dict__ is safer and fully addresses the prior nitpick.

Comment thread .github/actions/generate-coverage/scripts/run_python.py
Comment thread shellstub.py
Comment on lines +69 to +77
parsed = [
Variant(
match=v["match"],
stdout=v.get("stdout", ""),
stderr=v.get("stderr", ""),
exit_code=v.get("exit_code", 0),
)
for v in variants
]
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.

⚠️ Potential issue

Possible KeyError when user-supplied variant omits match

v["match"] assumes every dict contains a match key. A caller passing e.g.
{"stdout": "hi"} will cause a crash.

-            Variant(
-                match=v["match"],
+            Variant(
+                match=v.get("match"),

Also consider tightening the variants param type to list[dict[str, t.Any]] (or a TypedDict) so static checkers can spot missing keys.

📝 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
parsed = [
Variant(
match=v["match"],
stdout=v.get("stdout", ""),
stderr=v.get("stderr", ""),
exit_code=v.get("exit_code", 0),
)
for v in variants
]
parsed = [
Variant(
match=v.get("match"),
stdout=v.get("stdout", ""),
stderr=v.get("stderr", ""),
exit_code=v.get("exit_code", 0),
)
for v in variants
]
🤖 Prompt for AI Agents
In shellstub.py around lines 69 to 77, the code accesses v["match"] directly,
which can cause a KeyError if the 'match' key is missing in any variant
dictionary. To fix this, use v.get("match") with appropriate handling for a
missing 'match' key, such as raising a clear error or providing a default.
Additionally, update the type annotation for the variants parameter to
list[dict[str, Any]] or define a TypedDict to ensure static type checkers can
detect missing keys early.

Copy link
Copy Markdown
Contributor

@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: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 56e5d6e and 616a99e.

📒 Files selected for processing (1)
  • .github/actions/generate-coverage/scripts/run_python.py (2 hunks)
🔇 Additional comments (1)
.github/actions/generate-coverage/scripts/run_python.py (1)

15-15: Retaining the ET alias keeps downstream code intact – good decision
Re-introducing the as ET alias prevents accidental breakage where ET is referenced elsewhere and maintains consistency with the other coverage scripts.

Comment thread .github/actions/generate-coverage/scripts/run_python.py
@leynos leynos merged commit 688ce00 into main Jul 7, 2025
1 check passed
@leynos leynos deleted the codex/run-ruff-to-format-and-fix-lint-errors branch July 7, 2025 21:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant