Skip to content

Extend rendering semaphore and restore verbose shim#14

Merged
leynos merged 11 commits intomainfrom
codex/address-code-review-comments
Aug 8, 2025
Merged

Extend rendering semaphore and restore verbose shim#14
leynos merged 11 commits intomainfrom
codex/address-code-review-comments

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 7, 2025

Summary

  • enforce semaphore for full diagram rendering
  • restore deprecated verbose parameter with warning
  • log missing CLI via logger.error

Testing

  • make lint
  • make typecheck
  • make test

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

Summary by Sourcery

Enforce semaphore locking throughout the diagram rendering process, reinstate the deprecated verbose parameter with logging-based warnings, replace print-based error reports with logger.exception calls, and update the CLI and documentation to reflect these changes.

New Features:

  • Restore the deprecated verbose parameter in render_block for backward compatibility, enabling INFO-level logging of the underlying mermaid-cli commands when set
  • Allow the --verbose CLI flag to set the nixie.cli logger to INFO instead of adjusting basicConfig

Bug Fixes:

  • Use logger.exception to report missing mermaid-cli (FileNotFoundError) and runtime errors instead of printing to stderr

Enhancements:

  • Rename the sem parameter to semaphore in _render_diagram and enforce its lock across both process creation and waiting
  • Default CLI logging level to WARNING and adjust only the nixie.cli logger for verbosity

Documentation:

  • Update README and add a changelog entry to document the revised verbose flag behavior

Tests:

  • Add unit tests for verbose logging, silent mode, and missing CLI error logging

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 7, 2025

Reviewer's Guide

This PR enforces concurrency control on Mermaid CLI invocations via an asyncio semaphore, reintroduces the deprecated verbose flag with a logger shim, overhauls error handling to use logger.exception instead of prints, and updates tests and documentation to reflect these behaviors.

Sequence diagram for diagram rendering with enforced semaphore and improved error handling

sequenceDiagram
    participant User
    participant render_block
    participant _render_diagram
    participant logger
    User->>render_block: call render_block(..., semaphore, verbose)
    alt verbose is True
        render_block->>logger: setLevel(INFO)
    end
    render_block->>_render_diagram: await _render_diagram(..., semaphore, ...)
    _render_diagram->>semaphore: acquire (async with)
    _render_diagram->>CLI: invoke mermaid-cli
    _render_diagram->>semaphore: release
    alt FileNotFoundError
        render_block->>logger: logger.exception("CLI not found")
        render_block-->>User: return False
    else RuntimeError
        render_block->>logger: logger.exception("Runtime error")
        render_block-->>User: return False
    else Other Exception
        render_block->>logger: logger.exception("Unexpected error")
        render_block-->>User: return False
    else Success
        render_block-->>User: return True
    end
Loading

Class diagram for updated render_block and _render_diagram functions

classDiagram
    class render_block {
        +async render_block(block, tmpdir, cfg_path, path, idx, semaphore, timeout=30.0, verbose=None) bool
    }
    class _render_diagram {
        +async _render_diagram(block, tmpdir, cfg_path, path, idx, semaphore, timeout) None
    }
    render_block --> _render_diagram : calls

    note for render_block "Now accepts 'verbose' (deprecated) and logs errors via logger.exception."
    note for _render_diagram "Uses 'semaphore' for concurrency control."
Loading

File-Level Changes

Change Details Files
Add semaphore locking around CLI execution to limit concurrent renders
  • Rename semaphore parameter and use async with semaphore in _render_diagram
  • Indent wait_for_proc call within semaphore context
  • Assert semaphore.locked() in rendering tests
nixie/cli.py
nixie/unittests/test_render_diagram.py
Restore deprecated verbose parameter and CLI flag with logging shim
  • Add optional verbose argument to render_block that sets logger level to INFO
  • Adjust parse_args and cli() to always default to WARNING then raise to INFO on --verbose
  • Update README and add CHANGELOG entry for verbose behavior
nixie/cli.py
README.md
docs/CHANGELOG.md
nixie/unittests/test_verbose.py
Replace stderr prints with structured logging for missing or runtime errors
  • Catch FileNotFoundError, RuntimeError, and generic Exception in render_block
  • Log missing CLI and other errors via logger.exception
  • Return False on FileNotFoundError instead of printing to stderr
nixie/cli.py
nixie/unittests/test_verbose.py
Revise and extend unit tests for verbose and error scenarios
  • Standardize test function params by prefixing unused args with underscores
  • Add test for render_block(verbose=True) logging behavior
  • Add test for missing CLI FileNotFoundError logging and return value
nixie/unittests/test_verbose.py

Possibly linked issues


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 Aug 7, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Summary by CodeRabbit

  • New Features

    • Added a changelog documenting recent updates.
    • Improved CLI documentation for the --verbose flag, clarifying its logging behaviour.
  • Bug Fixes

    • Enhanced error handling and logging in the CLI, with clearer messages for missing dependencies and unexpected errors.
  • Refactor

    • Deprecated the verbose parameter in the render_block function; users should now configure logging directly.
    • Improved concurrency control and logging consistency in the CLI.
    • Updated parameter names for clarity.
  • Documentation

    • Updated README and added a changelog for better user guidance.
  • Chores

    • Improved Makefile to avoid redundant virtual environment setup.
    • Refined linting configuration for better test and documentation handling.
  • Tests

    • Added and improved tests for verbose logging, error handling, and deprecated parameters.

Walkthrough

Introduce the deprecated verbose parameter to the render_block function in nixie/cli.py, issuing a warning when used. Switch error reporting for missing CLI executables from stderr printing to logging. Adjust semaphore usage in diagram rendering. Update and add unittests to assert semaphore behaviour and verify error logging.

Changes

Cohort / File(s) Change Summary
Verbose Logging & CLI Improvements
nixie/cli.py
Add optional verbose parameter to render_block that sets logger level; remove traceback import; indent await wait_for_proc inside semaphore; switch error reporting to logging; update CLI logging setup and --verbose help text.
Semaphore Lock Assertions in Tests
nixie/unittests/test_render_diagram.py
Add assertions in async test helpers to confirm semaphore is locked during simulated subprocess execution; rename unused parameters with underscores.
Verbose & Error Logging Tests
nixie/unittests/test_verbose.py
Add async tests verifying verbose logging sets logger level and logs commands; test error logging when CLI executable is missing; rename unused parameters with underscores.
Documentation Updates
README.md, docs/CHANGELOG.md
Clarify --verbose flag description to specify logger and INFO level; add changelog entry documenting verbose logging and render_block changes.
Build Environment Setup Guard
Makefile
Modify build target to check for existing virtual environment before running setup commands, skipping if present.
Lint Configuration Refinement
pyproject.toml
Replace single-line per-file ignores with explicit table; add ignores for test files and conftest.py; add global ignore for D205 rule.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant render_block
    participant Logger
    participant Subprocess
    participant Semaphore

    User->>render_block: Call with verbose parameter (optional)
    alt verbose is set
        render_block->>Logger: Set logger level to INFO
    end
    render_block->>Semaphore: Acquire semaphore
    render_block->>Subprocess: Create subprocess for mermaid-cli
    alt subprocess creation fails (FileNotFoundError)
        render_block->>Logger: Log error "CLI executable not found"
        render_block-->>User: Return False
    else subprocess created
        render_block-->>User: Return True after rendering
    end
    render_block->>Semaphore: Release semaphore
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Poem

Verbose now whispers, logs in sight,
Semaphore guards the tasks just right.
Errors once silent, now loudly told,
Missing CLI’s tale unfolds.
Tests confirm the logging’s might—
Progress shines in clearer light! ✨🐇

✨ 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/address-code-review-comments

🪧 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.
  • 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.

Support

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

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 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 found some issues that need to be addressed.

  • Ensure that _render_diagram actually acquires the semaphore (e.g., via async with semaphore:) before invoking the CLI, since tests expect the semaphore to be locked during execution.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider adding a test to assert that passing the deprecated `verbose` parameter to `render_block` emits a `DeprecationWarning`.
- Ensure that `_render_diagram` actually acquires the semaphore (e.g., via `async with semaphore:`) before invoking the CLI, since tests expect the semaphore to be locked during execution.

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.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0cad73c and 881977f.

📒 Files selected for processing (3)
  • nixie/cli.py (4 hunks)
  • nixie/unittests/test_render_diagram.py (2 hunks)
  • nixie/unittests/test_verbose.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit Inference Engine (AGENTS.md)

For Python files: Pass all relevant unit and behavioral tests, pass lint checks (ruff check), adhere to formatting standards (ruff format), and pass type checking (pyright).

**/*.py: Use snake_case.py for file names, naming files for their contents (e.g., http_client.py, task_queue.py)
Use PascalCase for class names in Python files
Use snake_case for variable and function names in Python files
Use UPPER_SNAKE_CASE for module-level constants in Python files
Prefix private/internal helpers or APIs with a single underscore (_) in Python files
Use typing everywhere and maintain full static type coverage in Python files; use Pyright for type-checking
Use TypedDict or Dataclass for structured data where appropriate; for internal-only usage, prefer @DataClass(slots=True)
Avoid Any in type annotations; use Unknown, generics, or cast() when necessary, and always document why Any is acceptable if used
Be explicit with return types in public functions and class methods (e.g., use -> None, -> str, etc.)
Favor immutability in Python files; prefer tuples over lists, and frozendict or types.MappingProxyType where appropriate
Enable Ruff for linting and formatting; use Ruff to lint for performance, security, consistency, and style issues, and let Ruff handle whitespace and formatting entirely
Enforce strict mode in Pyright and treat all Pyright warnings as CI errors; use # pyright: ignore sparingly and with explanation
Avoid side effects at import time in Python modules; modules should not modify global state or perform actions on import
Use docstrings to document public functions, classes, and modules using NumPy format
Explain tricky code with inline comments for non-obvious logic or decisions in Python files

**/*.py: Use context managers to encapsulate setup and teardown logic cleanly and safely, especially for resource management (files, locks, connections, etc.), instead of manual try/finally blocks.
Use @contextmanager from contextlib for straightforward proce...

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/unittests/test_verbose.py
  • nixie/cli.py

⚙️ CodeRabbit Configuration File

**/*.py: How about the following?

- Keep cyclomatic complexity ≤ 12
- Follow single responsibility and CQRS (command/query segregation)
- Docstrings must follow the `numpy` style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
- Move conditionals with >2 branches to predicate/helper functions
- Avoid `eval`, `exec`, `pickle`, monkey-patching, `ctypes`, unsafe shell
- Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
- Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
- Lint suppressions:
  - Blanket `# noqa`, file-level skips, and categories are **forbidden**
  - Only narrow in-line disables (`# noqa: XYZ`) are permitted, and must be accompanied by `FIXME:` or a ticket link, and used only as a last resort.
- Use `pytest` fixtures for shared setup (`conftest.py` or `fixtures/`)
- Replace duplicate tests with `@pytest.mark.parametrize`
- Prefer `pytest-mock` or `unittest.mock` for stubs/mocks
- Use `assert …, "message"` over bare asserts
- Reflect all API/behaviour changes in `docs/` and update roadmap on completion
- Files must not exceed 400 logical lines:
  - Decompose large modules into subpackages
  - Split large `match/case` or dispatch tables by domain and collocate with targets if appropriate
  - Move bulky data (fixtures, templates) to external files for parsing at runtime
- Mutable defaults and shadowed built-ins are forbidden
- All code must have clear type hints using modern style (`A | B`, `list[str]`, `class Foo[A]:`, `type Bar = int`, etc.), with ABC imports drawn from the correct stdlib module.

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/unittests/test_verbose.py
  • nixie/cli.py
**/unittests/test_*.py

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

Colocate unit tests with code using a unittests subdirectory and a test_ prefix for test files

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/unittests/test_verbose.py
**/test_*.py

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

**/test_*.py: Use pytest idioms in test files: prefer fixtures over setup/teardown methods, parametrize broadly, and avoid unnecessary mocks
Group related tests using class with method names prefixed by test_ in test files

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/unittests/test_verbose.py
🪛 Ruff (0.12.2)
nixie/unittests/test_verbose.py

99-99: Unused function argument: kwargs

(ARG001)

🔇 Additional comments (4)
nixie/cli.py (2)

173-174: Hold the semaphore for the full subprocess lifecycle. LGTM.

Await wait_for_proc under async with sem: to cap concurrent CLI processes reliably. This fixes an oversubscription window. Tests asserting semaphore.locked() back this up.


27-27: Restore verbose shim with proper deprecation signalling.

Import warnings, add keyword-only verbose: bool | None = None, and warn when provided (including False). Use stacklevel=2 to point at the caller. This is API-safe and clear.

Also applies to: 192-193, 212-217

nixie/unittests/test_render_diagram.py (1)

30-31: Assert semaphore locking at the right time. LGTM.

Verify semaphore.locked() within fake_wait_for_proc to ensure the semaphore guards the entire subprocess lifecycle. This directly tests the concurrency fix.

Also applies to: 63-64

nixie/unittests/test_verbose.py (1)

88-111: Exercise logging path for missing CLI. LGTM.

Simulate FileNotFoundError, assert False is returned, and check ERROR log contains “not found” on the "nixie.cli" logger. This validates the new logging-based error handling.

Comment thread nixie/cli.py Outdated
Comment thread nixie/cli.py Outdated
Comment thread nixie/unittests/test_verbose.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: 16

🔭 Outside diff range comments (1)
nixie/cli.py (1)

112-118: Avoid printing on timeout; propagate the reason up.

Stop writing to stderr in wait_for_proc and return a useful message so _render_diagram/render_block remain the single place logging happens.

-    except asyncio.TimeoutError:
+    except asyncio.TimeoutError:
         proc.kill()
         await proc.wait()
-        print(f"{path}: diagram {idx} timed out", file=sys.stderr)
-        return (False, b"")
+        msg = f"{path}: diagram {idx} timed out after {timeout:.1f}s"
+        return (False, msg.encode("utf-8"))
♻️ Duplicate comments (1)
nixie/cli.py (1)

205-207: Document deprecation timeline and migration path for verbose.

Spell out removal timeframe/version and instruct to configure logging instead.

-        verbose: If ``True``, set the ``nixie.cli`` logger to ``INFO`` to
-            emit command lines. Preserved for backward compatibility.
+        verbose: Deprecated. If ``True``, set the ``nixie.cli`` logger to
+            ``INFO`` to emit command lines. This shim will be removed in a
+            future release; configure the ``nixie.cli`` logger level instead.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 881977f and 2c751d0.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • docs/CHANGELOG.md (1 hunks)
  • nixie/cli.py (5 hunks)
  • nixie/unittests/test_render_diagram.py (2 hunks)
  • nixie/unittests/test_verbose.py (4 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

For Markdown files (.md only): Pass lint checks (markdownlint filename.md).

Files:

  • README.md
  • docs/CHANGELOG.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Paragraphs and bullets must be wrapped to 80 columns, except where a long URL would prevent this (in which case, silence MD013 for that line)
  • Code blocks should be wrapped to 120 columns.
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • README.md
  • docs/CHANGELOG.md
{**/README.md,**/docs/**}

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

Colocate documentation by keeping README.md or docs/ near reusable packages and include usage examples

Files:

  • README.md
  • docs/CHANGELOG.md
**/*.py

📄 CodeRabbit Inference Engine (AGENTS.md)

For Python files: Pass all relevant unit and behavioral tests, pass lint checks (ruff check), adhere to formatting standards (ruff format), and pass type checking (pyright).

**/*.py: Use snake_case.py for file names, naming files for their contents (e.g., http_client.py, task_queue.py)
Use PascalCase for class names in Python files
Use snake_case for variable and function names in Python files
Use UPPER_SNAKE_CASE for module-level constants in Python files
Prefix private/internal helpers or APIs with a single underscore (_) in Python files
Use typing everywhere and maintain full static type coverage in Python files; use Pyright for type-checking
Use TypedDict or Dataclass for structured data where appropriate; for internal-only usage, prefer @DataClass(slots=True)
Avoid Any in type annotations; use Unknown, generics, or cast() when necessary, and always document why Any is acceptable if used
Be explicit with return types in public functions and class methods (e.g., use -> None, -> str, etc.)
Favor immutability in Python files; prefer tuples over lists, and frozendict or types.MappingProxyType where appropriate
Enable Ruff for linting and formatting; use Ruff to lint for performance, security, consistency, and style issues, and let Ruff handle whitespace and formatting entirely
Enforce strict mode in Pyright and treat all Pyright warnings as CI errors; use # pyright: ignore sparingly and with explanation
Avoid side effects at import time in Python modules; modules should not modify global state or perform actions on import
Use docstrings to document public functions, classes, and modules using NumPy format
Explain tricky code with inline comments for non-obvious logic or decisions in Python files

**/*.py: Use context managers to encapsulate setup and teardown logic cleanly and safely, especially for resource management (files, locks, connections, etc.), instead of manual try/finally blocks.
Use @contextmanager from contextlib for straightforward proce...

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/cli.py
  • nixie/unittests/test_verbose.py

⚙️ CodeRabbit Configuration File

**/*.py: How about the following?

- Keep cyclomatic complexity ≤ 12
- Follow single responsibility and CQRS (command/query segregation)
- Docstrings must follow the `numpy` style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
- Move conditionals with >2 branches to predicate/helper functions
- Avoid `eval`, `exec`, `pickle`, monkey-patching, `ctypes`, unsafe shell
- Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
- Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
- Lint suppressions:
  - Blanket `# noqa`, file-level skips, and categories are **forbidden**
  - Only narrow in-line disables (`# noqa: XYZ`) are permitted, and must be accompanied by `FIXME:` or a ticket link, and used only as a last resort.
- Use `pytest` fixtures for shared setup (`conftest.py` or `fixtures/`)
- Replace duplicate tests with `@pytest.mark.parametrize`
- Prefer `pytest-mock` or `unittest.mock` for stubs/mocks
- Use `assert …, "message"` over bare asserts
- Reflect all API/behaviour changes in `docs/` and update roadmap on completion
- Files must not exceed 400 logical lines:
  - Decompose large modules into subpackages
  - Split large `match/case` or dispatch tables by domain and collocate with targets if appropriate
  - Move bulky data (fixtures, templates) to external files for parsing at runtime
- Mutable defaults and shadowed built-ins are forbidden
- All code must have clear type hints using modern style (`A | B`, `list[str]`, `class Foo[A]:`, `type Bar = int`, etc.), with ABC imports drawn from the correct stdlib module.

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/cli.py
  • nixie/unittests/test_verbose.py
**/unittests/test_*.py

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

Colocate unit tests with code using a unittests subdirectory and a test_ prefix for test files

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/unittests/test_verbose.py
**/test_*.py

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

**/test_*.py: Use pytest idioms in test files: prefer fixtures over setup/teardown methods, parametrize broadly, and avoid unnecessary mocks
Group related tests using class with method names prefixed by test_ in test files

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/unittests/test_verbose.py
🧬 Code Graph Analysis (2)
nixie/unittests/test_render_diagram.py (1)
nixie/unittests/test_verbose.py (7)
  • fake_create_subprocess_exec (33-34)
  • fake_create_subprocess_exec (66-67)
  • fake_create_subprocess_exec (102-103)
  • fake_create_subprocess_exec (135-136)
  • fake_wait_for_proc (36-39)
  • fake_wait_for_proc (69-72)
  • fake_wait_for_proc (105-108)
nixie/unittests/test_verbose.py (2)
nixie/unittests/test_render_diagram.py (4)
  • fake_create_subprocess_exec (24-25)
  • fake_create_subprocess_exec (57-58)
  • fake_wait_for_proc (27-31)
  • fake_wait_for_proc (60-64)
nixie/cli.py (2)
  • render_block (184-232)
  • get_mmdc_cmd (74-91)
🪛 LanguageTool
docs/CHANGELOG.md

[style] ~6-~6: Consider using the typographical ellipsis character here instead.
Context: ...nderlying mermaid-cli commands. The render_block(verbose=...) parameter mirrors this behaviour.

(ELLIPSIS)

🪛 Ruff (0.12.2)
nixie/unittests/test_render_diagram.py

24-24: Unused function argument: cmd

(ARG001)


28-28: Trailing comma missing

Add trailing comma

(COM812)


57-57: Unused function argument: cmd

(ARG001)


61-61: Trailing comma missing

Add trailing comma

(COM812)

nixie/cli.py

220-223: Use logging.exception instead of logging.error

Replace with exception

(TRY400)


225-225: Use logging.exception instead of logging.error

Replace with exception

(TRY400)


228-228: Trailing comma missing

Add trailing comma

(COM812)

nixie/unittests/test_verbose.py

33-33: Unused function argument: cmd

(ARG001)


37-37: Trailing comma missing

Add trailing comma

(COM812)


66-66: Unused function argument: cmd

(ARG001)


70-70: Trailing comma missing

Add trailing comma

(COM812)


82-82: Trailing comma missing

Add trailing comma

(COM812)


102-102: Unused function argument: cmd

(ARG001)


106-106: Trailing comma missing

Add trailing comma

(COM812)

🔇 Additional comments (4)
nixie/cli.py (2)

168-175: Hold the semaphore across process wait.

Keep await wait_for_proc(...) inside async with sem: to ensure end‑to‑end limiting of concurrent CLI invocations. This aligns with the PR objective and the new tests.


320-326: Initialise logging predictably in CLI entrypoint.

Initialising at WARNING and elevating the module logger on --verbose is appropriate for a CLI.

README.md (1)

50-51: Align verbose description with implementation.

Keep this phrasing; it accurately reflects the logger‑based emission of commands.

nixie/unittests/test_verbose.py (1)

135-137: Silence ARG001 by prefixing unused var.

Rename *cmd to *_cmd.

-    async def fake_create_subprocess_exec(*cmd: str, **_kwargs: object) -> object:
+    async def fake_create_subprocess_exec(*_cmd: str, **_kwargs: object) -> object:
         raise FileNotFoundError(2, "No such file or directory", cmd[0])

Likely an incorrect or invalid review comment.

Comment thread docs/CHANGELOG.md Outdated
Comment thread nixie/cli.py
Comment thread nixie/cli.py Outdated
Comment thread nixie/cli.py Outdated
Comment thread nixie/unittests/test_render_diagram.py Outdated
Comment thread nixie/unittests/test_verbose.py
Comment thread nixie/unittests/test_verbose.py Outdated
Comment thread nixie/unittests/test_verbose.py Outdated
Comment thread nixie/unittests/test_verbose.py Outdated
Comment thread nixie/unittests/test_verbose.py
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 8, 2025

@sourcery-ai review

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 found some issues that need to be addressed.

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

### Comment 1
<location> `nixie/cli.py:214` </location>
<code_context>
     Notes:
         The command line used for rendering is logged at ``INFO`` level.
     """
+    if verbose:
+        logging.getLogger(__name__).setLevel(logging.INFO)
     try:
</code_context>

<issue_to_address>
Setting the logger level inside the function may cause side effects in concurrent or multi-invocation scenarios.

This approach can cause race conditions or inconsistent logging if render_block is called concurrently with different verbose values. It's better to configure logging at the CLI entry point or ensure thread safety when changing logger state.

Set the log level once (at command start-up), rather than passing around the `verbose` flag.
</issue_to_address>

### Comment 2
<location> `nixie/cli.py:226` </location>
<code_context>
+        )
+    except RuntimeError:
+        logging.getLogger(__name__).exception("Runtime error while rendering diagram")
+    except Exception:
+        logging.getLogger(__name__).exception(
+            "%s: unexpected error in diagram %s",
+            path,
+            idx,
         )
-    except RuntimeError as exc:
</code_context>

<issue_to_address>
Catching bare Exception may mask programming errors or system exit signals.

Catching Exception can suppress important errors like KeyboardInterrupt or SystemExit. Please catch only specific exceptions or re-raise unexpected ones after logging.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    except Exception:
        logging.getLogger(__name__).exception(
            "%s: unexpected error in diagram %s",
            path,
            idx,
        )
=======
    except Exception as exc:
        if isinstance(exc, (KeyboardInterrupt, SystemExit)):
            raise
        logging.getLogger(__name__).exception(
            "%s: unexpected error in diagram %s",
            path,
            idx,
        )
>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `nixie/unittests/test_verbose.py:33` </location>
<code_context>
     block = "A-->B"

-    async def fake_create_subprocess_exec(*cmd: str, **kwargs: object) -> object:
+    async def fake_create_subprocess_exec(*_cmd: str, **_kwargs: object) -> object:
         return object()

</code_context>

<issue_to_address>
No test for unexpected exceptions in render_block.

Please add tests to cover unexpected exceptions (e.g., Exception, RuntimeError) in render_block, verifying they are logged and the function returns False.

Suggested implementation:

```python
    async def fake_wait_for_proc(
        _proc: object, _path: Path, _idx: int, _timeout: float
    ) -> tuple[bool, bytes]:
        return True, b""

import pytest
import logging

@pytest.mark.asyncio
async def test_render_block_unexpected_exception(monkeypatch, caplog):
    from nixie.verbose import render_block

    # Patch something in render_block to raise an unexpected exception
    def raise_exception(*args, **kwargs):
        raise RuntimeError("unexpected error")

    # Example: patch a function render_block calls, e.g., create_subprocess_exec
    monkeypatch.setattr("nixie.verbose.create_subprocess_exec", raise_exception)

    caplog.set_level(logging.ERROR)
    result = await render_block(
        block="A-->B",
        path="dummy_path",
        idx=0,
        semaphore=asyncio.Semaphore(1),
        timeout=1.0,
    )
    assert result is False
    assert any("unexpected error" in message for message in caplog.text)

```

- Adjust the monkeypatch target (`nixie.verbose.create_subprocess_exec`) to match the actual function or method in `render_block` that should raise the exception.
- Ensure `render_block` is imported from the correct module.
- If `render_block` is not async, remove `@pytest.mark.asyncio` and `await`.
- If the logging level or logger is different, adjust `caplog.set_level`.
</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 nixie/cli.py Outdated
Comment thread nixie/cli.py Outdated
Comment thread nixie/unittests/test_verbose.py
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 8, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 8, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

♻️ Duplicate comments (5)
docs/CHANGELOG.md (1)

5-8: State deprecation removal window and migration path explicitly.

Add the removal version/timeframe for render_block(verbose=…) and keep a clear instruction to configure the nixie.cli logger.

- - `--verbose` now sets the `nixie.cli` logger to INFO, logging the underlying
-    `mermaid-cli` commands. The `render_block(verbose=...)` parameter is
-    deprecated and has no effect; configure the `nixie.cli` logger directly
-    instead.
+ - `--verbose` now sets the `nixie.cli` logger to INFO, logging the underlying
+    `mermaid-cli` commands.
+ - `render_block(verbose=…)` is deprecated and will be removed in vX.Y (or within N releases);
+    configure the `nixie.cli` logger directly instead.
nixie/unittests/test_render_diagram.py (2)

27-29: Add trailing comma in multiline signature (COM812).

Satisfy Ruff COM812 for the function signature.

-    async def fake_wait_for_proc(
-        _proc: object, _path: Path, _idx: int, _timeout: float
-    ) -> tuple[bool, bytes]:
+    async def fake_wait_for_proc(
+        _proc: object, _path: Path, _idx: int, _timeout: float,
+    ) -> tuple[bool, bytes]:

61-64: Add trailing comma in multiline signature (COM812).

Apply the same trailing comma fix here.

-    async def fake_wait_for_proc(
-        _proc: object, _path: Path, _idx: int, _timeout: float
-    ) -> tuple[bool, bytes]:
+    async def fake_wait_for_proc(
+        _proc: object, _path: Path, _idx: int, _timeout: float,
+    ) -> tuple[bool, bytes]:
nixie/unittests/test_verbose.py (2)

103-109: Add trailing comma in multiline signature (COM812).

-    async def fake_wait_for_proc(
-        _proc: object, _path: Path, _idx: int, _timeout: float
-    ) -> tuple[bool, bytes]:
+    async def fake_wait_for_proc(
+        _proc: object, _path: Path, _idx: int, _timeout: float,
+    ) -> tuple[bool, bytes]:

37-39: Add trailing comma in multiline signature (COM812).

-    async def fake_wait_for_proc(
-        _proc: object, _path: Path, _idx: int, _timeout: float
-    ) -> tuple[bool, bytes]:
+    async def fake_wait_for_proc(
+        _proc: object, _path: Path, _idx: int, _timeout: float,
+    ) -> tuple[bool, bytes]:
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c751d0 and 33efdf7.

📒 Files selected for processing (4)
  • docs/CHANGELOG.md (1 hunks)
  • nixie/cli.py (8 hunks)
  • nixie/unittests/test_render_diagram.py (2 hunks)
  • nixie/unittests/test_verbose.py (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • docs/CHANGELOG.md
**/*.py

⚙️ CodeRabbit Configuration File

**/*.py: How about the following?

- Keep cyclomatic complexity ≤ 12
- Follow single responsibility and CQRS (command/query segregation)
- Docstrings must follow the `numpy` style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
- Move conditionals with >2 branches to predicate/helper functions
- Avoid `eval`, `exec`, `pickle`, monkey-patching, `ctypes`, unsafe shell
- Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
- Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
- Lint suppressions:
  - Blanket `# noqa`, file-level skips, and categories are **forbidden**
  - Only narrow in-line disables (`# noqa: XYZ`) are permitted, and must be accompanied by `FIXME:` or a ticket link, and used only as a last resort.
- Use `pytest` fixtures for shared setup (`conftest.py` or `fixtures/`)
- Replace duplicate tests with `@pytest.mark.parametrize`
- Prefer `pytest-mock` or `unittest.mock` for stubs/mocks
- Use `assert …, "message"` over bare asserts
- Reflect all API/behaviour changes in `docs/` and update roadmap on completion
- Files must not exceed 400 logical lines:
  - Decompose large modules into subpackages
  - Split large `match/case` or dispatch tables by domain and collocate with targets if appropriate
  - Move bulky data (fixtures, templates) to external files for parsing at runtime
- Mutable defaults and shadowed built-ins are forbidden
- All code must have clear type hints using modern style (`A | B`, `list[str]`, `class Foo[A]:`, `type Bar = int`, etc.), with ABC imports drawn from the correct stdlib module.

Files:

  • nixie/unittests/test_render_diagram.py
  • nixie/cli.py
  • nixie/unittests/test_verbose.py
🧬 Code Graph Analysis (2)
nixie/unittests/test_render_diagram.py (1)
nixie/unittests/test_verbose.py (7)
  • fake_create_subprocess_exec (33-34)
  • fake_create_subprocess_exec (66-67)
  • fake_create_subprocess_exec (103-104)
  • fake_create_subprocess_exec (136-137)
  • fake_wait_for_proc (36-39)
  • fake_wait_for_proc (69-72)
  • fake_wait_for_proc (106-109)
nixie/unittests/test_verbose.py (2)
nixie/unittests/test_render_diagram.py (4)
  • fake_create_subprocess_exec (24-25)
  • fake_create_subprocess_exec (57-58)
  • fake_wait_for_proc (27-31)
  • fake_wait_for_proc (60-64)
nixie/cli.py (2)
  • render_block (185-243)
  • get_mmdc_cmd (75-92)
🪛 LanguageTool
docs/CHANGELOG.md

[style] ~6-~6: Consider using the typographical ellipsis character here instead.
Context: ...derlying mermaid-cli commands. The render_block(verbose=...) parameter is deprecated and has no...

(ELLIPSIS)

🪛 Ruff (0.12.2)
nixie/unittests/test_render_diagram.py

28-28: Trailing comma missing

Add trailing comma

(COM812)


61-61: Trailing comma missing

Add trailing comma

(COM812)

nixie/cli.py

231-231: Trailing comma missing

Add trailing comma

(COM812)


234-234: Use X | Y in isinstance call instead of (X, Y)

Convert to X | Y

(UP038)

nixie/unittests/test_verbose.py

37-37: Trailing comma missing

Add trailing comma

(COM812)


70-70: Trailing comma missing

Add trailing comma

(COM812)


80-81: Use a single with statement with multiple contexts instead of nested with statements

(SIM117)


80-80: pytest.warns(DeprecationWarning) is too broad, set the match parameter or use a more specific warning

(PT030)


83-83: Trailing comma missing

Add trailing comma

(COM812)


107-107: Trailing comma missing

Add trailing comma

(COM812)


186-186: Create your own exception

(TRY002)


186-186: Avoid specifying long messages outside the exception class

(TRY003)

🔇 Additional comments (7)
nixie/unittests/test_render_diagram.py (1)

27-31: Assert-and-lock check: good semaphore coverage.

Keep the assertion to guarantee the semaphore is held during wait; this protects both spawn and wait phases.

nixie/cli.py (4)

129-129: Rename to semaphore: clarity win.

The parameter rename improves readability and intent.


169-176: Hold the semaphore across spawn and wait.

Keep async with semaphore wrapping both process creation and wait; this removes the race window.


214-220: Emit deprecation warning: good.

Warning on any explicit verbose usage matches the deprecation contract.


11-12: Document the deprecation mirror in the module docstring.

State that --verbose mirrors the deprecated render_block(verbose=True) and point users to configure the nixie.cli logger. The PR summary claims this is documented; align the docstring.

-The ``--verbose`` flag sets the ``nixie.cli`` logger to ``INFO`` to emit the
-underlying ``mermaid-cli`` commands.
+The ``--verbose`` flag sets the ``nixie.cli`` logger to ``INFO`` to emit the
+underlying ``mermaid-cli`` commands. This mirrors ``render_block(verbose=True)``,
+which is deprecated and will be removed in a future release; configure the
+``nixie.cli`` logger instead.

Likely an incorrect or invalid review comment.

nixie/unittests/test_verbose.py (2)

33-33: Silence ARG001 via _cmd/_kwargs: good.

Keep underscore-prefixed parameters in stubs to avoid ARG001.


161-169: Runtime error logging test: LGTM.

The test correctly patches _render_diagram to raise and asserts the logged message.

Comment thread nixie/cli.py Outdated
Comment thread nixie/cli.py
Comment thread nixie/cli.py Outdated
Comment thread nixie/cli.py Outdated
Comment thread nixie/unittests/test_verbose.py
Comment thread nixie/unittests/test_verbose.py
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

🔭 Outside diff range comments (1)
nixie/unittests/test_verbose.py (1)

176-201: Avoid specifying messages outside the exception class (TRY003).

Raise the custom exception class without a message to silence TRY003.

-    async def raise_exception(*_args: object, **_kwargs: object) -> None:
-        raise BoomError("uh oh")
+    async def raise_exception(*_args: object, **_kwargs: object) -> None:
+        raise BoomError
♻️ Duplicate comments (4)
nixie/cli.py (4)

196-213: Rewrite render_block docstring to NumPy style per project guidelines.

Align with NumPy format (Parameters/Returns/Notes) and document the deprecation inline.

Use:

-    """Render a single mermaid block using the CLI asynchronously.
-
-    Args:
-        block: Mermaid code block to render.
-        tmpdir: Temporary directory for intermediate files.
-        cfg_path: Path to the Puppeteer configuration file.
-        path: Markdown file containing the block.
-        idx: Index of the block within ``path``.
-        semaphore: Limits concurrent CLI invocations.
-        timeout: Maximum time in seconds to wait for the CLI to finish.
-        verbose: Deprecated. Configure the ``nixie.cli`` logger instead.
-
-    Returns:
-        ``True`` on success, ``False`` otherwise.
-
-    Notes:
-        The command line used for rendering is logged at ``INFO`` level.
-    """
+    """Render a single Mermaid block using the CLI asynchronously.
+
+    Parameters
+    ----------
+    block : str
+        Mermaid code block to render.
+    tmpdir : Path
+        Temporary directory for intermediate files.
+    cfg_path : Path
+        Path to the Puppeteer configuration file.
+    path : Path
+        Markdown file containing the block.
+    idx : int
+        Index of the block within ``path``.
+    semaphore : asyncio.Semaphore
+        Limits concurrent CLI invocations.
+    timeout : float, default 30.0
+        Maximum time in seconds to wait for the CLI to finish.
+    verbose : bool | None, optional
+        Deprecated. Configure the ``nixie.cli`` logger instead.
+
+    Returns
+    -------
+    bool
+        True on success, False otherwise.
+
+    Notes
+    -----
+    The command line used for rendering is logged at INFO level.
+    """

11-12: Clarify verbose semantics and deprecation in the module docstring.

State that the behaviour mirrors render_block(verbose=True), which is deprecated, and direct users to configure the logger instead.

Apply:

 The ``--verbose`` flag sets the ``nixie.cli`` logger to ``INFO`` to emit the
-underlying ``mermaid-cli`` commands.
+underlying ``mermaid-cli`` commands. This mirrors ``render_block(verbose=True)``,
+which is deprecated and will be removed in a future release; configure the
+``nixie.cli`` logger instead.

229-233: Include path/index context and add trailing comma in runtime-error logging.

Enrich the log for triage and satisfy COM812.

-    except RuntimeError:
-        logging.getLogger(__name__).exception(
-            "Runtime error while rendering diagram"
-        )
+    except RuntimeError:
+        logging.getLogger(__name__).exception(
+            "%s: runtime error while rendering diagram %s",
+            path,
+            idx,
+        )

234-240: Adopt PEP 604 union in isinstance check (UP038).

Modernise the isinstance union syntax.

-    except Exception as exc:
-        if isinstance(exc, (KeyboardInterrupt, SystemExit)):
+    except Exception as exc:
+        if isinstance(exc, KeyboardInterrupt | SystemExit):
             raise
         logging.getLogger(__name__).exception(
             "%s: unexpected error in diagram %s",
             path,
             idx,
         )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 33efdf7 and a58de69.

📒 Files selected for processing (2)
  • nixie/cli.py (8 hunks)
  • nixie/unittests/test_verbose.py (4 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit Inference Engine (AGENTS.md)

For Python files: Pass all relevant unit and behavioral tests, pass lint checks (ruff check), adhere to formatting standards (ruff format), and pass type checking (pyright).

**/*.py: Use snake_case.py for file names, naming files for their contents (e.g., http_client.py, task_queue.py)
Use PascalCase for class names in Python files
Use snake_case for variable and function names in Python files
Use UPPER_SNAKE_CASE for module-level constants in Python files
Prefix private/internal helpers or APIs with a single underscore (_) in Python files
Use typing everywhere and maintain full static type coverage in Python files; use Pyright for type-checking
Use TypedDict or Dataclass for structured data where appropriate; for internal-only usage, prefer @DataClass(slots=True)
Avoid Any in type annotations; use Unknown, generics, or cast() when necessary, and always document why Any is acceptable if used
Be explicit with return types in public functions and class methods (e.g., use -> None, -> str, etc.)
Favor immutability in Python files; prefer tuples over lists, and frozendict or types.MappingProxyType where appropriate
Enable Ruff for linting and formatting; use Ruff to lint for performance, security, consistency, and style issues, and let Ruff handle whitespace and formatting entirely
Enforce strict mode in Pyright and treat all Pyright warnings as CI errors; use # pyright: ignore sparingly and with explanation
Avoid side effects at import time in Python modules; modules should not modify global state or perform actions on import
Use docstrings to document public functions, classes, and modules using NumPy format
Explain tricky code with inline comments for non-obvious logic or decisions in Python files

**/*.py: Use context managers to encapsulate setup and teardown logic cleanly and safely, especially for resource management (files, locks, connections, etc.), instead of manual try/finally blocks.
Use @contextmanager from contextlib for straightforward proce...

Files:

  • nixie/unittests/test_verbose.py
  • nixie/cli.py

⚙️ CodeRabbit Configuration File

**/*.py: How about the following?

- Keep cyclomatic complexity ≤ 12
- Follow single responsibility and CQRS (command/query segregation)
- Docstrings must follow the `numpy` style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
- Move conditionals with >2 branches to predicate/helper functions
- Avoid `eval`, `exec`, `pickle`, monkey-patching, `ctypes`, unsafe shell
- Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
- Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
- Lint suppressions:
  - Blanket `# noqa`, file-level skips, and categories are **forbidden**
  - Only narrow in-line disables (`# noqa: XYZ`) are permitted, and must be accompanied by `FIXME:` or a ticket link, and used only as a last resort.
- Use `pytest` fixtures for shared setup (`conftest.py` or `fixtures/`)
- Replace duplicate tests with `@pytest.mark.parametrize`
- Prefer `pytest-mock` or `unittest.mock` for stubs/mocks
- Use `assert …, "message"` over bare asserts
- Reflect all API/behaviour changes in `docs/` and update roadmap on completion
- Files must not exceed 400 logical lines:
  - Decompose large modules into subpackages
  - Split large `match/case` or dispatch tables by domain and collocate with targets if appropriate
  - Move bulky data (fixtures, templates) to external files for parsing at runtime
- Mutable defaults and shadowed built-ins are forbidden
- All code must have clear type hints using modern style (`A | B`, `list[str]`, `class Foo[A]:`, `type Bar = int`, etc.), with ABC imports drawn from the correct stdlib module.

Files:

  • nixie/unittests/test_verbose.py
  • nixie/cli.py
**/unittests/test_*.py

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

Colocate unit tests with code using a unittests subdirectory and a test_ prefix for test files

Files:

  • nixie/unittests/test_verbose.py
**/test_*.py

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

**/test_*.py: Use pytest idioms in test files: prefer fixtures over setup/teardown methods, parametrize broadly, and avoid unnecessary mocks
Group related tests using class with method names prefixed by test_ in test files

Files:

  • nixie/unittests/test_verbose.py
🧬 Code Graph Analysis (1)
nixie/unittests/test_verbose.py (2)
nixie/unittests/test_render_diagram.py (4)
  • fake_create_subprocess_exec (24-25)
  • fake_create_subprocess_exec (57-58)
  • fake_wait_for_proc (27-31)
  • fake_wait_for_proc (60-64)
nixie/cli.py (2)
  • render_block (185-243)
  • get_mmdc_cmd (75-92)
🪛 Ruff (0.12.2)
nixie/unittests/test_verbose.py

37-37: Trailing comma missing

Add trailing comma

(COM812)


70-70: Trailing comma missing

Add trailing comma

(COM812)


109-109: Trailing comma missing

Add trailing comma

(COM812)


191-191: Avoid specifying long messages outside the exception class

(TRY003)

nixie/cli.py

231-231: Trailing comma missing

Add trailing comma

(COM812)


234-234: Use X | Y in isinstance call instead of (X, Y)

Convert to X | Y

(UP038)

🔇 Additional comments (7)
nixie/cli.py (4)

169-176: Hold the semaphore across spawn and wait (correct concurrency control).

Keep the lock for both create_subprocess_exec and wait_for_proc to enforce the intended concurrency ceiling across the full subprocess lifecycle.


214-220: Deprecation shim emits warning (LGTM).

Warn on any explicit verbose usage and keep functional behaviour unchanged. The stacklevel is correct.


225-228: Use logging.exception for missing CLI (LGTM).

Log with traceback and keep the CLI name in the message.


334-341: Scope logging to nixie.cli (LGTM).

Attach a handler to the module logger, disable propagation, and set level based on --verbose without touching the root logger.

nixie/unittests/test_verbose.py (3)

55-92: Validate deprecation and keep logs quiet at WARNING (LGTM).

Assert DeprecationWarning and that INFO-level command emission does not occur when logger is at WARNING.


127-150: Log FileNotFoundError path cleanly (LGTM).

Assert False return and presence of “not found” in logs. Good coverage for the missing CLI path.


152-174: Capture runtime error logging (LGTM).

Exercise the RuntimeError path and assert message presence.

Comment thread nixie/unittests/test_verbose.py
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Aug 8, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🔭 Outside diff range comments (2)
nixie/cli.py (2)

117-118: Replace timeout print(...) with logging to unify error reporting.

Avoid print in error paths. Log the timeout and let the caller handle the failure, consistent with other branches.

-        print(f"{path}: diagram {idx} timed out", file=sys.stderr)
-        return (False, b"")
+        logging.getLogger(__name__).warning(
+            "%s: diagram %s timed out",
+            path,
+            idx,
+        )
+        return (False, b"")

288-289: Add full type hints to main to meet typing guidelines.

Annotate parameters and return type.

-async def main(paths, max_concurrent):
+async def main(paths: cabc.Iterable[Path], max_concurrent: int) -> int:
♻️ Duplicate comments (2)
nixie/cli.py (2)

11-12: Clarify deprecation in module docstring and mirror render_block behaviour.

Align the module docstring with the PR intent and tests by explicitly stating that this mirrors the deprecated render_block(verbose=True) and advising logging configuration instead.

-The ``--verbose`` flag sets the ``nixie.cli`` logger to ``INFO`` to emit the
-underlying ``mermaid-cli`` commands.
+The ``--verbose`` flag sets the ``nixie.cli`` logger to ``INFO`` to emit the
+underlying ``mermaid-cli`` commands. This mirrors ``render_block(verbose=True)``,
+which is deprecated and will be removed in a future release; configure the
+``nixie.cli`` logger level instead.

Likely an incorrect or invalid review comment.


194-196: Align docstring type with the signature and document the migration path.

Match the signature’s bool | None and document the deprecation/migration explicitly.

-    verbose : bool, optional
-        Deprecated; configure the ``nixie.cli`` logger instead.
+    verbose : bool | None, optional
+        Deprecated. Configure the ``nixie.cli`` logger instead. This parameter
+        will be removed in a future release; set the logger level to ``INFO`` to
+        emit the command line.

Also applies to: 214-216

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a58de69 and 6ce6a53.

📒 Files selected for processing (1)
  • nixie/cli.py (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

⚙️ CodeRabbit Configuration File

**/*.py: How about the following?

- Keep cyclomatic complexity ≤ 12
- Follow single responsibility and CQRS (command/query segregation)
- Docstrings must follow the `numpy` style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
- Move conditionals with >2 branches to predicate/helper functions
- Avoid `eval`, `exec`, `pickle`, monkey-patching, `ctypes`, unsafe shell
- Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
- Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
- Lint suppressions:
  - Blanket `# noqa`, file-level skips, and categories are **forbidden**
  - Only narrow in-line disables (`# noqa: XYZ`) are permitted, and must be accompanied by `FIXME:` or a ticket link, and used only as a last resort.
- Use `pytest` fixtures for shared setup (`conftest.py` or `fixtures/`)
- Replace duplicate tests with `@pytest.mark.parametrize`
- Prefer `pytest-mock` or `unittest.mock` for stubs/mocks
- Use `assert …, "message"` over bare asserts
- Reflect all API/behaviour changes in `docs/` and update roadmap on completion
- Files must not exceed 400 logical lines:
  - Decompose large modules into subpackages
  - Split large `match/case` or dispatch tables by domain and collocate with targets if appropriate
  - Move bulky data (fixtures, templates) to external files for parsing at runtime
- Mutable defaults and shadowed built-ins are forbidden
- All code must have clear type hints using modern style (`A | B`, `list[str]`, `class Foo[A]:`, `type Bar = int`, etc.), with ABC imports drawn from the correct stdlib module.

Files:

  • nixie/cli.py
🔇 Additional comments (8)
nixie/cli.py (8)

29-29: Import warnings for deprecation — LGTM.

Use of warnings for the deprecation path is appropriate.


129-131: Rename semsemaphore for clarity — LGTM.

Improve readability and keep API explicit; docstring is in sync.

Also applies to: 149-150


169-176: Hold the semaphore across both spawn and wait — correct concurrency fix.

Ensure the lock covers process creation and completion, preventing over‑subscription. Good alignment with tests.


226-232: Emit DeprecationWarning with stacklevel — LGTM.

Warn on any non-None usage without mutating logger state; this avoids side effects.


237-240: Log missing CLI with traceback — LGTM.

logging.exception with the missing executable name is the right choice.


244-250: Exception triage and PEP 604 union — LGTM.

Re-raise KeyboardInterrupt/SystemExit and log unexpected errors with traceback.


344-351: Scope logging to nixie.cli without touching root — LGTM.

Attach a handler once, disable propagation, and toggle only this logger’s level based on --verbose.


241-243: Add context to RuntimeError logging and satisfy COM812.

Include path and idx to aid triage and add trailing comma for formatter rules.

-    except RuntimeError:
-        logging.getLogger(__name__).exception("Runtime error while rendering diagram")
+    except RuntimeError:
+        logging.getLogger(__name__).exception(
+            "%s: runtime error while rendering diagram %s",
+            path,
+            idx,
+        )

Likely an incorrect or invalid review comment.

Comment thread nixie/cli.py
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 8, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

leynos added 3 commits August 8, 2025 17:26
- nixie/cli.py: align with ruff rules (use 'typ' alias, Final for constants), switch temporary-file cleanup to Path.unlink, wrap long lines, and avoid explicit exception messages to satisfy TRY003; add type annotations and clarify docstrings.
- tests: reformat test_verbose for ruff; keep behavior intact.
- pyproject.toml: add [tool.ruff.lint.per-file-ignores] to relax docstring/type/line-length/import rules in tests only.
- Makefile: skip 'uv venv/sync' when .venv already exists to work in restricted environments.

All changes are formatting/lint/build tooling only; no functional behavior change intended. Tests could not be executed in this sandbox due to seccomp socket restrictions.
- pyproject.toml: remove ANN from test per-file-ignores to enforce type annotations in tests.
- nixie/unittests/test_get_mmdc_cmd.py: annotate monkeypatch as pytest.MonkeyPatch.
- tests/integration/conftest.py: annotate monkeypatch fixture param.
- tests/integration/test_cli_behavior.py: type *args/**kwargs for mock_check_file.

Ruff now passes with ANN enabled in tests.
Documents test functions for clarity and maintainability.
Removes some per-file lint ignore rules for test files to
enforce stricter code style and documentation standards.
@leynos leynos force-pushed the codex/address-code-review-comments branch from 6ce6a53 to 36ae24f Compare August 8, 2025 16:36
Replaces repeated inline logger retrieval with a module-level logger variable to simplify and standardize logging across the module.
@leynos leynos merged commit 722430b into main Aug 8, 2025
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: 3

🔭 Outside diff range comments (3)
nixie/cli.py (2)

134-152: Align semaphore scope across helpers.

_render_diagram now holds the semaphore for both subprocess creation and wait, but _run_mermaid_cli still releases the lock immediately after creation. This inconsistency makes effective concurrency depend on which helper is used. Either:

-    async with sem:
-        proc = await asyncio.create_subprocess_exec(...)
-    return await wait_for_proc(proc, path, idx, timeout)
+    async with sem:
+        proc = await asyncio.create_subprocess_exec(...)
+        return await wait_for_proc(proc, path, idx, timeout)

or drop _run_mermaid_cli if it is dead code. Keep a single ordering rule to avoid hidden contention bugs.

Also applies to: 202-210


124-129: Replace stray print with logging.

wait_for_proc still prints time-out errors directly to stderr, contradicting the project’s own “unify error reporting via logging” guideline already applied elsewhere. Emit the message via logger.exception (TRY400) and drop the print.

nixie/unittests/test_verbose.py (1)

37-57: Deduplicate identical stubs with fixture/parametrize.

Each test re-declares the same fake_create_subprocess_exec, fake_wait_for_proc, and monkey-patch boilerplate. Extract these into pytest fixtures or parametrise the cases to trim 100+ lines and improve maintainability.

Also applies to: 71-109, 123-143

♻️ Duplicate comments (3)
docs/CHANGELOG.md (1)

5-8: Add a removal window for the deprecated verbose parameter.

State when render_block(verbose=...) will be removed to provide clear migration timing.

-- `--verbose` now sets the `nixie.cli` logger to INFO, logging the underlying
-   `mermaid-cli` commands. The `render_block(verbose=...)` parameter is
-   deprecated and has no effect; configure the `nixie.cli` logger directly
-   instead.
+- `--verbose` now sets the `nixie.cli` logger to INFO, logging the underlying
+  `mermaid-cli` commands.
+- `render_block(verbose=...)` is deprecated and will be removed in the next
+  minor release; configure the `nixie.cli` logger directly instead.
nixie/cli.py (2)

11-12: Restore deprecation note in module docstring.

The earlier revision explicitly mentioned that --verbose mirrors the now-deprecated render_block(verbose=True) and will be removed. That guidance is gone, breaking past review resolution and leaving users without a migration path. Re-insert the deprecation sentence to keep docs, CLI help, and changelog consistent.


278-280: Log runtime-error context.

The generic message "Runtime error while rendering diagram" omits the file path and diagram index that callers supply elsewhere. Add that context to aid troubleshooting:

-    logging.getLogger(__name__).exception("Runtime error while rendering diagram")
+    logging.getLogger(__name__).exception(
+        "%s: runtime error while rendering diagram %s",
+        path,
+        idx,
+    )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6ce6a53 and 36ae24f.

📒 Files selected for processing (7)
  • Makefile (1 hunks)
  • README.md (1 hunks)
  • docs/CHANGELOG.md (1 hunks)
  • nixie/cli.py (8 hunks)
  • nixie/unittests/test_render_diagram.py (2 hunks)
  • nixie/unittests/test_verbose.py (4 hunks)
  • pyproject.toml (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

For Markdown files (.md only): Pass lint checks (markdownlint filename.md).

Files:

  • README.md
  • docs/CHANGELOG.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • README.md
  • docs/CHANGELOG.md
{**/README.md,**/docs/**}

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

Colocate documentation by keeping README.md or docs/ near reusable packages and include usage examples

Files:

  • README.md
  • docs/CHANGELOG.md
**/*.py

📄 CodeRabbit Inference Engine (AGENTS.md)

For Python files: Pass all relevant unit and behavioral tests, pass lint checks (ruff check), adhere to formatting standards (ruff format), and pass type checking (pyright).

**/*.py: Use snake_case.py for file names, naming files for their contents (e.g., http_client.py, task_queue.py)
Use PascalCase for class names in Python files
Use snake_case for variable and function names in Python files
Use UPPER_SNAKE_CASE for module-level constants in Python files
Prefix private/internal helpers or APIs with a single underscore (_) in Python files
Use typing everywhere and maintain full static type coverage in Python files; use Pyright for type-checking
Use TypedDict or Dataclass for structured data where appropriate; for internal-only usage, prefer @DataClass(slots=True)
Avoid Any in type annotations; use Unknown, generics, or cast() when necessary, and always document why Any is acceptable if used
Be explicit with return types in public functions and class methods (e.g., use -> None, -> str, etc.)
Favor immutability in Python files; prefer tuples over lists, and frozendict or types.MappingProxyType where appropriate
Enable Ruff for linting and formatting; use Ruff to lint for performance, security, consistency, and style issues, and let Ruff handle whitespace and formatting entirely
Enforce strict mode in Pyright and treat all Pyright warnings as CI errors; use # pyright: ignore sparingly and with explanation
Avoid side effects at import time in Python modules; modules should not modify global state or perform actions on import
Use docstrings to document public functions, classes, and modules using NumPy format
Explain tricky code with inline comments for non-obvious logic or decisions in Python files

**/*.py: Use context managers to encapsulate setup and teardown logic cleanly and safely, especially for resource management (files, locks, connections, etc.), instead of manual try/finally blocks.
Use @contextmanager from contextlib for straightforward proce...

Files:

  • nixie/cli.py
  • nixie/unittests/test_verbose.py
  • nixie/unittests/test_render_diagram.py

⚙️ CodeRabbit Configuration File

**/*.py: How about the following?

- Keep cyclomatic complexity ≤ 12
- Follow single responsibility and CQRS (command/query segregation)
- Docstrings must follow the `numpy` style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
- Move conditionals with >2 branches to predicate/helper functions
- Avoid `eval`, `exec`, `pickle`, monkey-patching, `ctypes`, unsafe shell
- Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
- Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
- Lint suppressions:
  - Blanket `# noqa`, file-level skips, and categories are **forbidden**
  - Only narrow in-line disables (`# noqa: XYZ`) are permitted, and must be accompanied by `FIXME:` or a ticket link, and used only as a last resort.
- Use `pytest` fixtures for shared setup (`conftest.py` or `fixtures/`)
- Replace duplicate tests with `@pytest.mark.parametrize`
- Prefer `pytest-mock` or `unittest.mock` for stubs/mocks
- Use `assert …, "message"` over bare asserts
- Reflect all API/behaviour changes in `docs/` and update roadmap on completion
- Files must not exceed 400 logical lines:
  - Decompose large modules into subpackages
  - Split large `match/case` or dispatch tables by domain and collocate with targets if appropriate
  - Move bulky data (fixtures, templates) to external files for parsing at runtime
- Mutable defaults and shadowed built-ins are forbidden
- All code must have clear type hints using modern style (`A | B`, `list[str]`, `class Foo[A]:`, `type Bar = int`, etc.), with ABC imports drawn from the correct stdlib module.

Files:

  • nixie/cli.py
  • nixie/unittests/test_verbose.py
  • nixie/unittests/test_render_diagram.py
**/unittests/test_*.py

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

Colocate unit tests with code using a unittests subdirectory and a test_ prefix for test files

Files:

  • nixie/unittests/test_verbose.py
  • nixie/unittests/test_render_diagram.py
**/test_*.py

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

**/test_*.py: Use pytest idioms in test files: prefer fixtures over setup/teardown methods, parametrize broadly, and avoid unnecessary mocks
Group related tests using class with method names prefixed by test_ in test files

Files:

  • nixie/unittests/test_verbose.py
  • nixie/unittests/test_render_diagram.py
pyproject.toml

📄 CodeRabbit Inference Engine (.rules/python-00.mdc)

Use pyproject.toml to configure tools like Ruff, Pyright, and Pytest

pyproject.toml: Always use pyproject.toml as the central configuration file for Astral uv projects; do not use requirements.txt or setup.py.
The [project] table in pyproject.toml must include at least name and version fields as required by PEP 621.
Include description and readme fields in the [project] table to improve indexing and packaging tool compatibility.
Specify requires-python in the [project] table to constrain supported Python versions.
Use the license field in [project] as either an SPDX identifier (license = { text = "MIT" }) or by referencing a file.
List authors in the [project] table as a list of tables with name and email fields.
Include keywords and classifiers in the [project] table to improve discoverability and registry compatibility.
Declare runtime dependencies in the [project].dependencies list using PEP 508 syntax.
Use [project.optional-dependencies] to define groups such as dev and docs for development and documentation dependencies.
Define CLI entry points using [project.scripts] and GUI entry points using [project.gui-scripts] in pyproject.toml.
Register plugin entry points using [project.entry-points.'group.name'] in pyproject.toml if your project supports plugins.
Declare a [build-system] table with requires (e.g., setuptools>=61.0, wheel) and build-backend (e.g., setuptools.build_meta) for modern builds and editable installs.
If [build-system] is omitted, set [tool.uv].package = true to ensure your project is built and installed by uv.
Set [tool.uv].package = true to force uv to build and install your project into its virtual environment on every uv sync or uv run.
Keep pyproject.toml human-readable and edit it by hand when possible.
Follow semantic versioning (semver) for the version field in pyproject.toml.
Keep build constraints minimal in [build-system]; omit it if you do n...

Files:

  • pyproject.toml
🧬 Code Graph Analysis (2)
nixie/unittests/test_verbose.py (2)
nixie/unittests/test_render_diagram.py (4)
  • fake_create_subprocess_exec (27-28)
  • fake_create_subprocess_exec (61-62)
  • fake_wait_for_proc (30-34)
  • fake_wait_for_proc (64-68)
nixie/cli.py (2)
  • render_block (219-290)
  • get_mmdc_cmd (89-103)
nixie/unittests/test_render_diagram.py (1)
nixie/unittests/test_verbose.py (7)
  • fake_create_subprocess_exec (37-38)
  • fake_create_subprocess_exec (71-72)
  • fake_create_subprocess_exec (123-124)
  • fake_create_subprocess_exec (157-158)
  • fake_wait_for_proc (40-43)
  • fake_wait_for_proc (74-77)
  • fake_wait_for_proc (126-129)
🪛 LanguageTool
docs/CHANGELOG.md

[style] ~6-~6: Consider using the typographical ellipsis character here instead.
Context: ...derlying mermaid-cli commands. The render_block(verbose=...) parameter is deprecated and has no...

(ELLIPSIS)

🔇 Additional comments (4)
pyproject.toml (1)

74-74: Acknowledge global D205 ignore.

Global ignore for D205 is fine; keep a single source of truth.

README.md (1)

50-51: Clarify verbose behaviour is logger-scoped.

Description correctly states that --verbose sets nixie.cli to INFO and logs the exact command. Good alignment with implementation.

nixie/unittests/test_render_diagram.py (2)

27-34: Assert semaphore held during wait; silence unused args.

Lock assertion validates the semaphore spans the wait phase; _ prefixes silence ARG001 cleanly.


61-69: Mirror lock assertion for failure path.

Maintain parity by asserting lock coverage on error path; unused-arg fix is correct.

Comment thread Makefile
Comment on lines +16 to +20
@if [ -x .venv/bin/python ]; then \
echo "venv present; skipping uv setup"; \
else \
uv venv && uv sync --group dev; \
fi
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.

🛠️ Refactor suggestion

Run uv sync on every build; only gate uv venv creation.

Skipping uv sync when a venv exists risks stale dependencies. Always sync; only skip uv venv.

-	@if [ -x .venv/bin/python ]; then \
-		echo "venv present; skipping uv setup"; \
-	else \
-		uv venv && uv sync --group dev; \
-	fi
+	@if [ -x .venv/bin/python ]; then \
+		echo "venv present; skipping uv venv"; \
+	else \
+		uv venv; \
+	fi; \
+	uv sync --group dev
📝 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
@if [ -x .venv/bin/python ]; then \
echo "venv present; skipping uv setup"; \
else \
uv venv && uv sync --group dev; \
fi
@if [ -x .venv/bin/python ]; then \
echo "venv present; skipping uv venv"; \
else \
uv venv; \
fi; \
uv sync --group dev
🤖 Prompt for AI Agents
In the Makefile at lines 16 to 20, modify the conditional so that the `uv venv`
command is only skipped if the virtual environment exists, but the `uv sync
--group dev` command runs every time. This means you should check if the virtual
environment exists to decide whether to run `uv venv`, but always run `uv sync
--group dev` regardless of the venv presence to avoid stale dependencies.

Comment on lines +86 to +92
pytest.warns(
DeprecationWarning,
match=(
r"The 'verbose' parameter is deprecated; configure the"
r"'nixie\.cli' logger level instead\."
),
),
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

Fix regexp – missing space breaks assertion.

The joined raw strings produce configure the'nixie\.cli', so the warning text never matches and the test will fail. Insert a space or \s*:

-            match=(
-                r"The 'verbose' parameter is deprecated; configure the"
-                r"'nixie\.cli' logger level instead\."
+            match=(
+                r"The 'verbose' parameter is deprecated; configure the "
+                r"'nixie\.cli' logger level instead\."
             ),
📝 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
pytest.warns(
DeprecationWarning,
match=(
r"The 'verbose' parameter is deprecated; configure the"
r"'nixie\.cli' logger level instead\."
),
),
pytest.warns(
DeprecationWarning,
match=(
r"The 'verbose' parameter is deprecated; configure the "
r"'nixie\.cli' logger level instead\."
),
),
🤖 Prompt for AI Agents
In nixie/unittests/test_verbose.py around lines 86 to 92, the regular expression
used in pytest.warns is missing a space between "configure the" and
"'nixie\.cli'", causing the match to fail. Fix this by adding a space or a
whitespace matcher like \s* between these parts in the regex to correctly match
the warning message text.

Comment thread pyproject.toml
Comment on lines +76 to 81
[tool.ruff.lint.per-file-ignores]
"**/test_*.py" = [
"S101", # allow assert in tests
]
"tests/**/conftest.py" = ["D", "TRY003"]
ignore = ["D205"]
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

Remove duplicated/invalid ignore in per-file-ignores.

ignore = ["D205"] at Line 81 is not a valid key under [tool.ruff.lint.per-file-ignores] and duplicates the global ignore at Line 74. Delete it.

 [tool.ruff.lint.per-file-ignores]
 "**/test_*.py" = [
   "S101",  # allow assert in tests
 ]
 "tests/**/conftest.py" = ["D", "TRY003"]
-ignore = ["D205"]
🤖 Prompt for AI Agents
In pyproject.toml around lines 76 to 81, the key 'ignore = ["D205"]' under
[tool.ruff.lint.per-file-ignores] is invalid and duplicates a global ignore
setting at line 74. Remove the line 'ignore = ["D205"]' from this section to fix
the issue.

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

🔭 Outside diff range comments (4)
nixie/cli.py (4)

196-199: Specify UTF-8 when writing the temporary .mmd file.

Align with read_text(encoding="utf-8") and avoid locale-dependent encodings.

-    mmd.write_text(block)
+    mmd.write_text(block, encoding="utf-8")

121-133: Replace print on timeout with logging and catch asyncio.TimeoutError explicitly.

Avoid printing from library helpers and log with context. asyncio.wait_for raises asyncio.TimeoutError; catch it explicitly.

-    try:
-        _, stderr = await asyncio.wait_for(proc.communicate(), timeout)
-    except TimeoutError:
+    try:
+        _, stderr = await asyncio.wait_for(proc.communicate(), timeout)
+    except asyncio.TimeoutError:
         proc.kill()
         await proc.wait()
-        print(f"{path}: diagram {idx} timed out", file=sys.stderr)
-        return (False, b"")
+        LOGGER.exception("%s: diagram %s timed out", path, idx)
+        return False, b"timed out"

136-155: Remove unused _run_mermaid_cli to avoid duplication.

_render_diagram supersedes _run_mermaid_cli and properly holds the semaphore for the entire lifecycle. Drop the unused helper to reduce cognitive load and keep one codepath.

I can submit a follow-up patch removing this function and adjusting tests if any reference it.


333-339: Use logging for unexpected errors in main.

Standardise error reporting; keep prints for progress if desired, but log exceptions.

-            except Exception as exc:  # noqa: BLE001  pragma: no cover - unexpected
-                # Catch unexpected errors so the CLI can continue processing.
-                print(f"Validation task raised an exception: {exc}")
+            except Exception:  # noqa: BLE001  pragma: no cover - unexpected
+                # Catch unexpected errors so the CLI can continue processing.
+                LOGGER.exception("Validation task raised an exception")
♻️ Duplicate comments (3)
nixie/cli.py (3)

11-12: Clarify verbose semantics and deprecation in module docstring.

State that this mirrors the deprecated render_block(verbose=True) and instruct users to configure logging instead.

-The ``--verbose`` flag sets the ``nixie.cli`` logger to ``INFO`` to emit the
-underlying ``mermaid-cli`` commands.
+The ``--verbose`` flag sets the ``nixie.cli`` logger to ``INFO`` to emit the
+underlying ``mermaid-cli`` commands. This mirrors ``render_block(verbose=True)``,
+which is deprecated and will be removed in a future release; configure the
+``nixie.cli`` logger instead.

281-289: Include path and index in runtime-error logging.

Add context to speed up debugging and satisfy prior lint guidance.

-    except RuntimeError:
-        LOGGER.exception("Runtime error while rendering diagram")
+    except RuntimeError:
+        LOGGER.exception(
+            "%s: runtime error while rendering diagram %s",
+            path,
+            idx,
+        )

374-375: Clarify --verbose help to reflect logger semantics.

State explicitly that it sets nixie.cli logger to INFO.

-        help="Log mermaid-cli commands for each diagram",
+        help="Set 'nixie.cli' logger to INFO and log mermaid-cli commands",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 36ae24f and ad45f6b.

📒 Files selected for processing (1)
  • nixie/cli.py (8 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

📄 CodeRabbit Inference Engine (AGENTS.md)

For Python files: Pass all relevant unit and behavioral tests, pass lint checks (ruff check), adhere to formatting standards (ruff format), and pass type checking (pyright).

**/*.py: Use snake_case.py for file names, naming files for their contents (e.g., http_client.py, task_queue.py)
Use PascalCase for class names in Python files
Use snake_case for variable and function names in Python files
Use UPPER_SNAKE_CASE for module-level constants in Python files
Prefix private/internal helpers or APIs with a single underscore (_) in Python files
Use typing everywhere and maintain full static type coverage in Python files; use Pyright for type-checking
Use TypedDict or Dataclass for structured data where appropriate; for internal-only usage, prefer @DataClass(slots=True)
Avoid Any in type annotations; use Unknown, generics, or cast() when necessary, and always document why Any is acceptable if used
Be explicit with return types in public functions and class methods (e.g., use -> None, -> str, etc.)
Favor immutability in Python files; prefer tuples over lists, and frozendict or types.MappingProxyType where appropriate
Enable Ruff for linting and formatting; use Ruff to lint for performance, security, consistency, and style issues, and let Ruff handle whitespace and formatting entirely
Enforce strict mode in Pyright and treat all Pyright warnings as CI errors; use # pyright: ignore sparingly and with explanation
Avoid side effects at import time in Python modules; modules should not modify global state or perform actions on import
Use docstrings to document public functions, classes, and modules using NumPy format
Explain tricky code with inline comments for non-obvious logic or decisions in Python files

**/*.py: Use context managers to encapsulate setup and teardown logic cleanly and safely, especially for resource management (files, locks, connections, etc.), instead of manual try/finally blocks.
Use @contextmanager from contextlib for straightforward proce...

Files:

  • nixie/cli.py

⚙️ CodeRabbit Configuration File

**/*.py: How about the following?

- Keep cyclomatic complexity ≤ 12
- Follow single responsibility and CQRS (command/query segregation)
- Docstrings must follow the `numpy` style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
- Move conditionals with >2 branches to predicate/helper functions
- Avoid `eval`, `exec`, `pickle`, monkey-patching, `ctypes`, unsafe shell
- Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
- Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar
- Lint suppressions:
  - Blanket `# noqa`, file-level skips, and categories are **forbidden**
  - Only narrow in-line disables (`# noqa: XYZ`) are permitted, and must be accompanied by `FIXME:` or a ticket link, and used only as a last resort.
- Use `pytest` fixtures for shared setup (`conftest.py` or `fixtures/`)
- Replace duplicate tests with `@pytest.mark.parametrize`
- Prefer `pytest-mock` or `unittest.mock` for stubs/mocks
- Use `assert …, "message"` over bare asserts
- Reflect all API/behaviour changes in `docs/` and update roadmap on completion
- Files must not exceed 400 logical lines:
  - Decompose large modules into subpackages
  - Split large `match/case` or dispatch tables by domain and collocate with targets if appropriate
  - Move bulky data (fixtures, templates) to external files for parsing at runtime
- Mutable defaults and shadowed built-ins are forbidden
- All code must have clear type hints using modern style (`A | B`, `list[str]`, `class Foo[A]:`, `type Bar = int`, etc.), with ABC imports drawn from the correct stdlib module.

Files:

  • nixie/cli.py
🔇 Additional comments (5)
nixie/cli.py (5)

29-29: LGTM: Add warnings import for deprecation.

The import is necessary for the DeprecationWarning path.


36-36: LGTM: Use a module-scoped logger.

Keep logging unified through LOGGER across the module.


262-268: LGTM: Emit DeprecationWarning for verbose usage.

The warning text and stacklevel are appropriate.


271-279: LGTM: Log FileNotFoundError with traceback and guidance.

Using LOGGER.exception ensures the traceback is captured for diagnostics.


382-389: LGTM: Scope logging to nixie.cli without touching the root logger.

Handler setup, propagate=False, and level selection are correct.

Comment thread nixie/cli.py
finally:
with suppress(OSError):
path.unlink()
path.unlink(missing_ok=True)
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.

💡 Verification agent

🧩 Analysis chain

Remove redundant missing_ok for wider Python compatibility.

missing_ok=True is redundant under suppress(OSError) and narrows the supported Python versions unnecessarily. Drop it.

If the project targets Python < 3.8, this will otherwise break.

-            path.unlink(missing_ok=True)
+            path.unlink()

🏁 Script executed:

#!/bin/bash
set -e

echo "Detecting project metadata files..."
fd --max-depth 2 --type f 'setup.py|setup.cfg|pyproject.toml|tox.ini|Pipfile|requirements.*' || true

echo
echo "Scanning for python_requires declarations..."
grep -R "python_requires" -n .

echo
echo "Scanning for Python version classifiers in metadata..."
grep -R "Programming Language :: Python :: " -n .

Length of output: 337


🏁 Script executed:

#!/bin/bash
set -e

echo "Check for requires-python in pyproject.toml"
grep -R "requires-python" -n pyproject.toml || echo "No requires-python in pyproject.toml"

echo
echo "Check for Python version classifiers in pyproject.toml"
grep -R "Programming Language :: Python ::" -n pyproject.toml || echo "No Python classifiers in pyproject.toml"

echo
echo "Show context around path.unlink in nixie/cli.py"
sed -n '70,110p' nixie/cli.py

echo
echo "Search for use of suppress in nixie/cli.py"
grep -R "suppress" -n nixie/cli.py || echo "No suppress usage in nixie/cli.py"

Length of output: 2036


Simplify unlink by removing redundant missing_ok

Remove the missing_ok=True argument because the surrounding with suppress(OSError): already handles missing-file errors. Drop the redundant parameter.

• File: nixie/cli.py
• Location: within the finally: block of create_puppeteer_config

-        with suppress(OSError):
-            path.unlink(missing_ok=True)
+        with suppress(OSError):
+            path.unlink()
📝 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
path.unlink(missing_ok=True)
with suppress(OSError):
path.unlink()
🤖 Prompt for AI Agents
In nixie/cli.py at line 88, inside the finally block of create_puppeteer_config,
remove the redundant argument missing_ok=True from the path.unlink() call
because the surrounding with suppress(OSError): block already handles missing
file errors. Simply call path.unlink() without any arguments to simplify the
code.

Comment thread nixie/cli.py
Comment on lines +204 to +211
async with semaphore:
# nosemgrep: python.lang.security.audit.dangerous-asyncio-create-exec-audit
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
success, stderr = await wait_for_proc(proc, path, idx, timeout)
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.

🧹 Nitpick (assertive)

Hold semaphore across the full subprocess lifecycle and fix subprocess alias usage.

Good job moving create+wait under the semaphore. Unify to the imported alias asyncio_subprocess for consistency with _run_mermaid_cli.

-        proc = await asyncio.create_subprocess_exec(
+        proc = await asyncio.create_subprocess_exec(
             *cmd,
-            stdout=asyncio.subprocess.PIPE,
-            stderr=asyncio.subprocess.PIPE,
+            stdout=asyncio_subprocess.PIPE,
+            stderr=asyncio_subprocess.PIPE,
         )

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In nixie/cli.py around lines 204 to 211, hold the semaphore for the entire
subprocess lifecycle by including both the creation and waiting of the
subprocess within the async with semaphore block. Also, replace
asyncio.create_subprocess_exec with the imported alias
asyncio_subprocess.create_subprocess_exec to maintain consistency with other
parts of the code like _run_mermaid_cli.

Comment thread nixie/cli.py
Comment on lines +250 to 252
verbose : bool, optional
Deprecated; configure the ``nixie.cli`` logger instead.

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.

🧹 Nitpick (assertive)

Align docstring type with signature for verbose.

Document verbose as bool | None and add a brief removal note.

-    verbose : bool, optional
-        Deprecated; configure the ``nixie.cli`` logger instead.
+    verbose : bool | None, optional
+        Deprecated. Configure the ``nixie.cli`` logger instead. This parameter
+        will be removed in a future release.
📝 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
verbose : bool, optional
Deprecated; configure the ``nixie.cli`` logger instead.
verbose : bool | None, optional
Deprecated. Configure the ``nixie.cli`` logger instead. This parameter
will be removed in a future release.
🤖 Prompt for AI Agents
In nixie/cli.py around lines 250 to 252, the docstring for the verbose parameter
should be updated to match its type hint in the function signature by
documenting it as bool or None. Additionally, add a brief note indicating that
this parameter is deprecated and will be removed in the future, guiding users to
configure the nixie.cli logger instead.

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