Skip to content

Refactor mermaid rendering helpers#10

Merged
leynos merged 5 commits intomainfrom
codex/refactor-diagram-file-creation-and-cli-invocation
Aug 7, 2025
Merged

Refactor mermaid rendering helpers#10
leynos merged 5 commits intomainfrom
codex/refactor-diagram-file-creation-and-cli-invocation

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 7, 2025

Summary

  • extract _write_diagram_file and _run_mermaid_cli helpers
  • simplify render_block to coordinate helpers
  • add unit tests for new helpers

Testing

  • ruff check nixie/cli.py nixie/unittests/test_write_diagram_file.py nixie/unittests/test_run_mermaid_cli.py
  • pyright nixie/cli.py nixie/unittests/test_write_diagram_file.py nixie/unittests/test_run_mermaid_cli.py
  • python -m pytest

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

Summary by Sourcery

Refactor mermaid diagram rendering by extracting helper functions and adding unit tests for them

Enhancements:

  • Extract _write_diagram_file helper to isolate file writing logic
  • Extract _run_mermaid_cli helper to encapsulate CLI invocation
  • Simplify render_block to coordinate the new helpers

Tests:

  • Add unit tests for _write_diagram_file
  • Add unit tests for _run_mermaid_cli

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 7, 2025

Reviewer's Guide

The PR refactors mermaid rendering in cli.py by extracting file-writing and CLI-invocation into dedicated helpers, streamlining render_block to orchestrate these helpers, and adds unit tests for both new helpers.

File-Level Changes

Change Details Files
Extracted diagram file writing into a helper
  • Moved MMD file creation and naming logic into _write_diagram_file
  • Unified input/output path construction
  • Wrapped file write operation with clear return values
nixie/cli.py
Extracted mermaid-CLI invocation into a helper
  • Encapsulated subprocess spawn, logging, and error mapping in _run_mermaid_cli
  • Used semaphore for concurrency control
  • Raised clear RuntimeError/FileNotFoundError on failures
nixie/cli.py
Simplified render_block to use new helpers
  • Replaced inline file I/O and subprocess logic with calls to helpers
  • Centralized exception handling for FileNotFoundError and RuntimeError
  • Condensed return paths to a single False fallback
nixie/cli.py
Added unit tests for new helpers
  • Covered _write_diagram_file behavior and returned paths
  • Tested _run_mermaid_cli for successful invocation and failure error
  • Mocked subprocess and wait_for_proc interactions
nixie/unittests/test_write_diagram_file.py
nixie/unittests/test_run_mermaid_cli.py

Tips and commands

Interacting with Sourcery

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

Customizing Your Experience

Access your dashboard to:

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

Getting Help

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:167` </location>
<code_context>
+
+    success, stderr = await wait_for_proc(proc, path, idx, timeout)
+    if not success:
+        raise RuntimeError(format_cli_error(stderr.decode("utf-8", errors="replace")))
+
+
</code_context>

<issue_to_address>
Consider including more context in the RuntimeError message.

Adding the command or file name to the error message will help identify issues when processing multiple diagrams concurrently.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    if not success:
        raise RuntimeError(format_cli_error(stderr.decode("utf-8", errors="replace")))
=======
    if not success:
        error_message = (
            f"Error running command {cmd} for file '{path}' (index {idx}):\n"
            f"{format_cli_error(stderr.decode('utf-8', errors='replace'))}"
        )
        raise RuntimeError(error_message)
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `nixie/cli.py:212` </location>
<code_context>
+        mmd, svg = _write_diagram_file(block, tmpdir, path, idx)
+        await _run_mermaid_cli(mmd, svg, cfg_path, semaphore, path, idx, timeout)
+        return True
+    except FileNotFoundError as exc:
+        cli = exc.filename or "mmdc"
+        print(
+            (
+                f"Error: '{cli}' not found. Install Node.js with npx "
+                "or Bun to use @mermaid-js/mermaid-cli."
+            ),
+            file=sys.stderr,
+        )
+    except RuntimeError as exc:
+        print(exc, file=sys.stderr)
</code_context>

<issue_to_address>
The fallback to 'mmdc' as the CLI name may be misleading if a different executable is missing.

If get_mmdc_cmd returns a different executable, the error message may incorrectly reference 'mmdc'. Use the actual command attempted for clarity.

Suggested implementation:

```python
        mmd, svg = _write_diagram_file(block, tmpdir, path, idx)
        # Determine the actual command used for mermaid CLI
        mmdc_cmd = get_mmdc_cmd()  # This should return the command as a list or string
        await _run_mermaid_cli(mmd, svg, cfg_path, semaphore, path, idx, timeout, mmdc_cmd=mmdc_cmd)
        return True
    except FileNotFoundError as exc:
        # Use the actual command attempted, fallback to exc.filename if available, else use mmdc_cmd[0] or "mmdc"
        if hasattr(exc, "filename") and exc.filename:
            cli = exc.filename
        elif isinstance(mmdc_cmd, (list, tuple)) and mmdc_cmd:
            cli = mmdc_cmd[0]
        elif isinstance(mmdc_cmd, str):
            cli = mmdc_cmd
        else:
            cli = "mmdc"
        print(
            (
                f"Error: '{cli}' not found. Install Node.js with npx "
                "or Bun to use @mermaid-js/mermaid-cli."
            ),
            file=sys.stderr,
        )

```

- Ensure that `get_mmdc_cmd()` is defined and returns the actual command used to invoke the mermaid CLI.
- If `_run_mermaid_cli` already determines the command internally, you may need to refactor it to return or expose the command so it can be referenced in the except block.
- If `get_mmdc_cmd()` requires arguments, adjust the call accordingly.
- Pass `mmdc_cmd` to `_run_mermaid_cli` if it needs to use the same command.
</issue_to_address>

### Comment 3
<location> `nixie/cli.py:109` </location>
<code_context>
     return success, stderr


+def _write_diagram_file(
+    block: str, tmpdir: Path, path: Path, idx: int
+) -> tuple[Path, Path]:
</code_context>

<issue_to_address>
Consider merging the file-writing and CLI-invocation helpers into a single function to reduce indirection and simplify parameter passing.

```markdown
Consider merging `_write_diagram_file` and `_run_mermaid_cli` into a single helper to reduce indirection and long parameter lists. For example:

```python
async def _render_diagram(
    block: str,
    tmpdir: Path,
    cfg_path: Path,
    path: Path,
    idx: int,
    sem: asyncio.Semaphore,
    timeout: float,
) -> None:
    # inline file-write
    mmd = tmpdir / f"{path.stem}_{idx}.mmd"
    svg = mmd.with_suffix(".svg")
    mmd.write_text(block)

    # all CLI logic here
    cmd = get_mmdc_cmd(mmd, svg, cfg_path)
    logging.getLogger(__name__).info(shlex.join(cmd))
    async with sem:
        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)
    if not success:
        raise RuntimeError(format_cli_error(stderr.decode("utf-8", errors="replace")))
```

Then simplify `render_block` to:

```python
async def render_block(
    block: str,
    tmpdir: Path,
    cfg_path: Path,
    path: Path,
    idx: int,
    semaphore: asyncio.Semaphore,
    timeout: float = 30.0,
) -> bool:
    try:
        await _render_diagram(block, tmpdir, cfg_path, path, idx, semaphore, timeout)
        return True
    except FileNotFoundError as exc:
        cli = exc.filename or "mmdc"
        print(f"Error: '{cli}' not found. Install Node.js with npx or Bun.", file=sys.stderr)
    except RuntimeError as exc:
        print(exc, file=sys.stderr)
    except Exception as exc:
        print(f"{path}: unexpected error in diagram {idx}", file=sys.stderr)
        traceback.print_exception(type(exc), exc, exc.__traceback__, file=sys.stderr)
    return False
```

This removes a trivial file‐write helper, consolidates CLI + semaphore logic into one place, and keeps your API of `render_block(...)` unchanged.
```
</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
Comment thread nixie/cli.py
return success, stderr


def _write_diagram_file(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider merging the file-writing and CLI-invocation helpers into a single function to reduce indirection and simplify parameter passing.

Consider merging `_write_diagram_file` and `_run_mermaid_cli` into a single helper to reduce indirection and long parameter lists. For example:

```python
async def _render_diagram(
    block: str,
    tmpdir: Path,
    cfg_path: Path,
    path: Path,
    idx: int,
    sem: asyncio.Semaphore,
    timeout: float,
) -> None:
    # inline file-write
    mmd = tmpdir / f"{path.stem}_{idx}.mmd"
    svg = mmd.with_suffix(".svg")
    mmd.write_text(block)

    # all CLI logic here
    cmd = get_mmdc_cmd(mmd, svg, cfg_path)
    logging.getLogger(__name__).info(shlex.join(cmd))
    async with sem:
        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)
    if not success:
        raise RuntimeError(format_cli_error(stderr.decode("utf-8", errors="replace")))

Then simplify render_block to:

async def render_block(
    block: str,
    tmpdir: Path,
    cfg_path: Path,
    path: Path,
    idx: int,
    semaphore: asyncio.Semaphore,
    timeout: float = 30.0,
) -> bool:
    try:
        await _render_diagram(block, tmpdir, cfg_path, path, idx, semaphore, timeout)
        return True
    except FileNotFoundError as exc:
        cli = exc.filename or "mmdc"
        print(f"Error: '{cli}' not found. Install Node.js with npx or Bun.", file=sys.stderr)
    except RuntimeError as exc:
        print(exc, file=sys.stderr)
    except Exception as exc:
        print(f"{path}: unexpected error in diagram {idx}", file=sys.stderr)
        traceback.print_exception(type(exc), exc, exc.__traceback__, file=sys.stderr)
    return False

This removes a trivial file‐write helper, consolidates CLI + semaphore logic into one place, and keeps your API of render_block(...) unchanged.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Has this now been resolved?

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.

The issue has not been resolved yet. The helpers _write_diagram_file and _run_mermaid_cli are still implemented as separate functions, and render_block continues to coordinate between them. The suggestion to merge these helpers into a single function for reduced indirection and simpler parameter passing has not been incorporated in the current state of the code.

If you would like to discuss the trade-offs or revisit the refactor suggestion, let me know!

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Has this now been resolved?

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.

No, this has not been resolved yet. The helpers _write_diagram_file and _run_mermaid_cli are still implemented as separate functions in nixie/cli.py, and have not been merged into a single function as previously suggested. If you'd like to revisit this refactor or discuss the pros and cons, let me know—I'm happy to help!

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Has this now been resolved?

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.

No, this has not been resolved yet. The functions _write_diagram_file and _run_mermaid_cli are still implemented as separate helpers in nixie/cli.py, and have not been merged into a single function as previously suggested. If you'd like to proceed with this refactor or discuss the pros and cons, let me know—I'm here to 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

    • Introduced a Makefile with commands for building, testing, linting, formatting, and validating Mermaid diagrams.
    • Added a new empty documentation file.
  • Bug Fixes

    • Improved error handling and user messages when rendering Mermaid diagrams.
  • Tests

    • Added tests for diagram file writing and Mermaid CLI execution.
  • Chores

    • Updated .gitignore to exclude new tool and editor backup files.
    • Updated project configuration syntax for optional dependencies.

Walkthrough

Refactor the render_block function in nixie/cli.py by extracting the Mermaid diagram writing and CLI invocation logic into two new helpers: _write_diagram_file and _run_mermaid_cli. Add comprehensive asynchronous tests for these helpers in new test modules, ensuring correct command invocation and error handling.

Changes

Cohort / File(s) Change Summary
CLI Refactor
nixie/cli.py
Extract _write_diagram_file and _run_mermaid_cli helpers; refactor render_block to use these; improve error handling and structure.
Tests for Mermaid CLI Invocation
nixie/unittests/test_run_mermaid_cli.py
Add asynchronous tests for _run_mermaid_cli, verifying command invocation and error raising on failure.
Tests for Diagram File Writing
nixie/unittests/test_write_diagram_file.py
Add test for _write_diagram_file, checking file creation, contents, and output path correctness.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant render_block
    participant _write_diagram_file
    participant _run_mermaid_cli
    participant MermaidCLI

    User->>render_block: Request to render diagram block
    render_block->>_write_diagram_file: Write Mermaid block to .mmd file
    _write_diagram_file-->>render_block: Return .mmd and .svg paths
    render_block->>_run_mermaid_cli: Invoke Mermaid CLI asynchronously
    _run_mermaid_cli->>MermaidCLI: Run mmdc to convert .mmd to .svg
    MermaidCLI-->>_run_mermaid_cli: Return success or error
    _run_mermaid_cli-->>render_block: Raise exception or return
    render_block-->>User: Return True (success) or False (failure)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

Refactor the block, split helpers in two,
Write diagrams cleanly, let Mermaid flow through.
Tests now abound, for errors and calls,
Async and tidy, no nested pitfalls.
With structure and order, the code’s shining bright—
Review with a grin, for all works just right!
🧑‍💻✨

✨ 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/refactor-diagram-file-creation-and-cli-invocation

🪧 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

@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

♻️ Duplicate comments (1)
nixie/cli.py (1)

136-167: Robust async helper with proper error handling.

The function correctly uses the semaphore for concurrency control and raises appropriate exceptions. The nosemgrep comment is justified for this controlled subprocess usage.

Note: Past review comments suggested including more context in the RuntimeError message and merging this helper with _write_diagram_file. The current separation provides good testability, though merging remains a valid architectural choice.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a568800 and 08bdafe.

📒 Files selected for processing (3)
  • nixie/cli.py (2 hunks)
  • nixie/unittests/test_run_mermaid_cli.py (1 hunks)
  • nixie/unittests/test_write_diagram_file.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_run_mermaid_cli.py
  • nixie/unittests/test_write_diagram_file.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_run_mermaid_cli.py
  • nixie/unittests/test_write_diagram_file.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_run_mermaid_cli.py
  • nixie/unittests/test_write_diagram_file.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_run_mermaid_cli.py
  • nixie/unittests/test_write_diagram_file.py
🧬 Code Graph Analysis (2)
nixie/unittests/test_run_mermaid_cli.py (1)
nixie/cli.py (3)
  • cli (314-321)
  • _run_mermaid_cli (136-167)
  • get_mmdc_cmd (61-78)
nixie/unittests/test_write_diagram_file.py (1)
nixie/cli.py (2)
  • cli (314-321)
  • _write_diagram_file (109-133)
🪛 Ruff (0.12.2)
nixie/unittests/test_run_mermaid_cli.py

28-28: Unused function argument: cmd

(ARG001)


28-28: Unused function argument: kwargs

(ARG001)


32-32: Unused function argument: proc

(ARG001)


32-32: Unused function argument: path

(ARG001)


32-32: Unused function argument: idx

(ARG001)


32-32: Async function definition with a timeout parameter

(ASYNC109)


32-32: Unused function argument: timeout

(ARG001)


32-32: Trailing comma missing

Add trailing comma

(COM812)


49-49: Trailing comma missing

Add trailing comma

(COM812)


59-59: Unused function argument: cmd

(ARG001)


59-59: Unused function argument: kwargs

(ARG001)


63-63: Unused function argument: proc

(ARG001)


63-63: Unused function argument: path

(ARG001)


63-63: Unused function argument: idx

(ARG001)


63-63: Async function definition with a timeout parameter

(ASYNC109)


63-63: Unused function argument: timeout

(ARG001)


63-63: Trailing comma missing

Add trailing comma

(COM812)

nixie/cli.py

110-110: Trailing comma missing

Add trailing comma

(COM812)


143-143: Async function definition with a timeout parameter

(ASYNC109)


211-211: Consider moving this statement to an else block

(TRY300)


223-223: Do not catch blind exception: Exception

(BLE001)

🔇 Additional comments (5)
nixie/unittests/test_write_diagram_file.py (1)

8-16: LGTM! Well-structured test coverage.

The test effectively verifies the core functionality of _write_diagram_file: writing the mermaid source to a .mmd file, generating the correct SVG path, and confirming file creation.

nixie/unittests/test_run_mermaid_cli.py (2)

14-44: Excellent test coverage for the success path.

The test properly mocks the subprocess execution and verifies that the command is logged correctly. The monkeypatching approach is appropriate for testing async subprocess operations.


47-74: Solid error handling test.

The test correctly verifies that _run_mermaid_cli raises a RuntimeError with the expected error message when the subprocess fails.

nixie/cli.py (2)

109-133: Well-structured helper function with comprehensive documentation.

The function follows the coding guidelines with proper numpy-style docstrings and clear parameter descriptions. The implementation is straightforward and testable.

Fix the trailing comma issue:

 def _write_diagram_file(
-    block: str, tmpdir: Path, path: Path, idx: int
+    block: str, tmpdir: Path, path: Path, idx: int,
 ) -> tuple[Path, Path]:

208-226: Refactor improves error handling and modularity.

The extracted helpers make the code more testable and the error handling clearer.

Improve the try/except structure by moving the success return to an else block:

 try:
     mmd, svg = _write_diagram_file(block, tmpdir, path, idx)
     await _run_mermaid_cli(mmd, svg, cfg_path, semaphore, path, idx, timeout)
-    return True
 except FileNotFoundError as exc:
     cli = exc.filename or "mmdc"
     print(
         (
             f"Error: '{cli}' not found. Install Node.js with npx "
             "or Bun to use @mermaid-js/mermaid-cli."
         ),
         file=sys.stderr,
     )
 except RuntimeError as exc:
     print(exc, file=sys.stderr)
 except Exception as exc:
     print(f"{path}: unexpected error in diagram {idx}", file=sys.stderr)
     traceback.print_exception(type(exc), exc, exc.__traceback__, file=sys.stderr)
+else:
+    return True
 return False

Comment thread nixie/unittests/test_run_mermaid_cli.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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 08bdafe and 87c0320.

📒 Files selected for processing (2)
  • nixie/cli.py (2 hunks)
  • nixie/unittests/test_run_mermaid_cli.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_run_mermaid_cli.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_run_mermaid_cli.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_run_mermaid_cli.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_run_mermaid_cli.py
🧠 Learnings (1)
📚 Learning: in the nixie codebase, trailing commas are only used when function parameters are formatted one per ...
Learnt from: leynos
PR: leynos/nixie#10
File: nixie/unittests/test_run_mermaid_cli.py:32-34
Timestamp: 2025-08-07T09:30:31.098Z
Learning: In the nixie codebase, trailing commas are only used when function parameters are formatted one per line (each parameter on its own line), not when parameters are simply wrapped to multiple lines but grouped together. Example of when trailing comma is acceptable: `def foo(a,\n    b,\n    c,\n) -> d:` vs when it's not needed: `def foo(\n    a, b, c\n) -> d:`

Applied to files:

  • nixie/unittests/test_run_mermaid_cli.py
🧬 Code Graph Analysis (1)
nixie/unittests/test_run_mermaid_cli.py (1)
nixie/cli.py (3)
  • cli (318-325)
  • _run_mermaid_cli (136-169)
  • get_mmdc_cmd (61-78)
🪛 Ruff (0.12.2)
nixie/unittests/test_run_mermaid_cli.py

29-29: Unused function argument: cmd

(ARG001)


29-29: Unused function argument: kwargs

(ARG001)


33-33: Unused function argument: proc

(ARG001)


33-33: Unused function argument: path

(ARG001)


33-33: Unused function argument: idx

(ARG001)


33-33: Async function definition with a timeout parameter

(ASYNC109)


33-33: Unused function argument: timeout

(ARG001)


33-33: Trailing comma missing

Add trailing comma

(COM812)


50-50: Trailing comma missing

Add trailing comma

(COM812)


61-61: Unused function argument: cmd

(ARG001)


61-61: Unused function argument: kwargs

(ARG001)


65-65: Unused function argument: proc

(ARG001)


65-65: Unused function argument: path

(ARG001)


65-65: Unused function argument: idx

(ARG001)


65-65: Async function definition with a timeout parameter

(ASYNC109)


65-65: Unused function argument: timeout

(ARG001)


65-65: Trailing comma missing

Add trailing comma

(COM812)

nixie/cli.py

110-110: Trailing comma missing

Add trailing comma

(COM812)


141-141: Async function definition with a timeout parameter

(ASYNC109)


215-215: Consider moving this statement to an else block

(TRY300)


227-227: Do not catch blind exception: Exception

(BLE001)

🔇 Additional comments (6)
nixie/unittests/test_run_mermaid_cli.py (3)

14-46: Excellent test coverage for successful CLI invocation.

The test effectively verifies that _run_mermaid_cli properly logs commands and handles successful execution through well-crafted fakes.


48-79: Solid error handling test implementation.

The test thoroughly verifies that _run_mermaid_cli raises RuntimeError with appropriate error messages when the CLI fails, including proper context about the file and error details.


29-35: Ignore the unused argument warnings from Ruff.

The static analysis tool flags unused arguments in the fake functions, but these parameters are required to match the signatures of the real functions being mocked. This is a false positive.

nixie/cli.py (3)

109-133: Clean and focused file writing helper.

The function properly encapsulates the diagram file creation logic with clear documentation following NumPy style. The implementation is straightforward and returns both the input and expected output paths as needed.


136-170: Robust CLI invocation with proper error handling.

The function correctly handles subprocess execution within the semaphore, provides comprehensive error messages including command details, and properly decodes stderr with error handling. The docstring follows NumPy format and clearly documents the exceptions raised.


210-230: Well-orchestrated refactor of render_block.

The function now serves as a clear coordinator, delegating file writing and CLI execution to the helper functions whilst centralising error handling. The error messages provide appropriate context for different failure scenarios.

Comment thread nixie/cli.py Outdated
Repository owner deleted a comment from sourcery-ai Bot Aug 7, 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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 87c0320 and c888239.

📒 Files selected for processing (1)
  • nixie/cli.py (2 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
🪛 Ruff (0.12.2)
nixie/cli.py

110-110: Trailing comma missing

Add trailing comma

(COM812)


145-145: Async function definition with a timeout parameter

(ASYNC109)


233-233: Do not catch blind exception: Exception

(BLE001)

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

140-177: Well-structured async helper with comprehensive error handling.

The function correctly isolates CLI invocation logic with proper concurrency control and detailed error reporting. The timeout parameter is appropriately used for subprocess management.


217-238: Clean refactoring with proper error handling structure.

The refactored function successfully delegates responsibilities to the helper functions whilst maintaining comprehensive error handling. The else clause clearly delineates the success path, and the broad Exception catch is appropriate for this top-level handler that provides debugging information for unexpected errors.

Comment thread nixie/cli.py
@leynos leynos force-pushed the codex/refactor-diagram-file-creation-and-cli-invocation branch from c888239 to 64368b1 Compare August 7, 2025 16:43
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 (1)
nixie/cli.py (1)

179-210: Remove or implement the unused verbose parameter.

The verbose parameter is documented in the docstring but not used in the implementation. Either remove it from the function signature and docstring, or implement the logging control as described.

-    *,
-    verbose: bool | None = None,
     timeout: float = 30.0,

And remove the corresponding documentation from the docstring.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c888239 and 64368b1.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • .gitignore (1 hunks)
  • CRUSH.md (1 hunks)
  • Makefile (1 hunks)
  • nixie/cli.py (2 hunks)
  • nixie/unittests/test_run_mermaid_cli.py (1 hunks)
  • nixie/unittests/test_write_diagram_file.py (1 hunks)
  • pyproject.toml (1 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:

  • CRUSH.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:

  • CRUSH.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_write_diagram_file.py
  • nixie/cli.py
  • nixie/unittests/test_run_mermaid_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_write_diagram_file.py
  • nixie/cli.py
  • nixie/unittests/test_run_mermaid_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_write_diagram_file.py
  • nixie/unittests/test_run_mermaid_cli.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_write_diagram_file.py
  • nixie/unittests/test_run_mermaid_cli.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
🧠 Learnings (1)
📚 Learning: 2025-08-07T09:30:31.098Z
Learnt from: leynos
PR: leynos/nixie#10
File: nixie/unittests/test_run_mermaid_cli.py:32-34
Timestamp: 2025-08-07T09:30:31.098Z
Learning: In the nixie codebase, trailing commas are only used when function parameters are formatted one per line (each parameter on its own line), not when parameters are simply wrapped to multiple lines but grouped together. Example of when trailing comma is acceptable: `def foo(a,\n    b,\n    c,\n) -> d:` vs when it's not needed: `def foo(\n    a, b, c\n) -> d:`

Applied to files:

  • nixie/cli.py
  • nixie/unittests/test_run_mermaid_cli.py
🧬 Code Graph Analysis (2)
nixie/unittests/test_write_diagram_file.py (1)
nixie/cli.py (2)
  • cli (320-327)
  • _write_diagram_file (109-137)
nixie/unittests/test_run_mermaid_cli.py (1)
nixie/cli.py (3)
  • cli (320-327)
  • _run_mermaid_cli (140-176)
  • get_mmdc_cmd (61-78)
🪛 Ruff (0.12.2)
nixie/cli.py

110-110: Trailing comma missing

Add trailing comma

(COM812)


145-145: Async function definition with a timeout parameter

(ASYNC109)


227-227: Do not catch blind exception: Exception

(BLE001)

nixie/unittests/test_run_mermaid_cli.py

29-29: Unused function argument: cmd

(ARG001)


29-29: Unused function argument: kwargs

(ARG001)


33-33: Unused function argument: proc

(ARG001)


33-33: Unused function argument: path

(ARG001)


33-33: Unused function argument: idx

(ARG001)


33-33: Async function definition with a timeout parameter

(ASYNC109)


33-33: Unused function argument: timeout

(ARG001)


33-33: Trailing comma missing

Add trailing comma

(COM812)


50-50: Trailing comma missing

Add trailing comma

(COM812)


61-61: Unused function argument: cmd

(ARG001)


61-61: Unused function argument: kwargs

(ARG001)


65-65: Unused function argument: proc

(ARG001)


65-65: Unused function argument: path

(ARG001)


65-65: Unused function argument: idx

(ARG001)


65-65: Async function definition with a timeout parameter

(ASYNC109)


65-65: Unused function argument: timeout

(ARG001)


65-65: Trailing comma missing

Add trailing comma

(COM812)

🔇 Additional comments (9)
.gitignore (1)

194-200: LGTM!

The gitignore additions are appropriate and well-documented. The .crush pattern aligns with the new tooling, and the editor backup pattern follows standard conventions.

CRUSH.md (1)

1-87: Comprehensive agent documentation with good structure.

The documentation provides thorough guidance on code style, testing procedures, and development workflow. The structure is logical and the content aligns well with modern development practices.

nixie/unittests/test_write_diagram_file.py (1)

8-16: Well-structured unit test with good coverage.

The test effectively validates the core functionality of _write_diagram_file: content writing, path derivation, and file creation. The use of pytest fixtures and clear assertions follows best practices.

Makefile (1)

1-43: Well-structured Makefile with comprehensive automation.

The Makefile provides excellent build and maintenance automation with proper .PHONY declarations, variable definitions, and helpful documentation. The integration with uv and modern Python tooling is appropriate.

nixie/cli.py (3)

109-137: Well-designed helper function with clear separation of concerns.

The function correctly isolates filesystem operations from the rendering workflow, making the code more testable and maintainable. The docstring clearly explains the rationale and parameters.


140-177: Excellent async CLI invocation helper with robust error handling.

The function properly manages subprocess execution with semaphore-based concurrency control and provides comprehensive error messages for debugging. The nosemgrep comment appropriately addresses the security scanner warning for subprocess execution.


211-232: Excellent refactoring that simplifies coordination logic.

The function now cleanly delegates to focused helper functions and provides comprehensive error handling with user-friendly messages. The use of try-except-else pattern improves code clarity.

nixie/unittests/test_run_mermaid_cli.py (2)

14-45: Comprehensive test coverage for successful CLI invocation.

The test effectively verifies command construction, logging, and successful execution using appropriate mocking strategies. The mock functions correctly match the expected signatures even though parameters are unused.


48-79: Thorough test coverage for CLI failure scenarios.

The test properly verifies exception raising and ensures error messages contain essential debugging information including the parse error, filename, and command. The assertions effectively validate the error message construction.

Comment thread Makefile
Comment thread Makefile
Comment thread pyproject.toml
@leynos leynos merged commit 906f11d into main Aug 7, 2025
1 check passed
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