Skip to content

Integrate manifest-to-Ninja pipeline#48

Closed
leynos wants to merge 4 commits intomainfrom
codex/implement-manifest-to-ninja-build-process
Closed

Integrate manifest-to-Ninja pipeline#48
leynos wants to merge 4 commits intomainfrom
codex/implement-manifest-to-ninja-build-process

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 5, 2025

Summary

  • Parse Netsukefile, convert to IR, and generate a temporary Ninja script before invoking Ninja
  • Capture generated build files with test helper and exercise full manifest→IR→Ninja CLI flow

Testing

  • make fmt
  • make lint
  • make test (fails: 3 steps failed)
  • cargo test --test runner_tests

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

Summary by Sourcery

Integrate a manifest-to-Ninja pipeline by updating the runner to parse a Netsukefile, convert it to IR, generate a temporary Ninja build script, and invoke Ninja with the generated file; extend tests to use temporary manifests and capture the generated build file; refactor test support and add the tempfile dependency.

New Features:

  • Parse Netsukefile and generate a Ninja build script before invoking Ninja
  • Add an end-to-end integration test to verify the manifest→IR→Ninja pipeline by capturing the generated build file

Enhancements:

  • Update run_ninja to write the generated Ninja script to a temporary file and pass "-f" to Ninja
  • Refactor test support to consolidate script writing and introduce fake_ninja_capture for build file capture

Build:

  • Add tempfile crate for temporary file support

Tests:

  • Adapt runner_tests to use temporary manifest files via a write_manifest helper and adjust test_cli signature

- Parse Netsukefile and convert to IR
- Write Ninja script to a temp file and pass via -f
- Cover manifest→IR→Ninja pipeline with CLI tests
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 5, 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

    • Automatically generates a temporary Ninja build script from the manifest before running the Ninja process.
    • Added a test to verify that the generated Ninja build file matches expected output.
    • Enhanced test utilities to support capturing and verifying generated Ninja build scripts.
  • Bug Fixes

    • Ensured manifest files are correctly created and resolved during test and process steps.
  • Refactor

    • Improved helper functions for script and manifest handling in tests.
    • Streamlined the process of determining executable paths and handling temporary files.
  • Documentation

    • Expanded test documentation for clarity on runner behaviour.

Walkthrough

Promote the "tempfile" crate from a development dependency to a main dependency. Refactor the Ninja runner to load a manifest, convert it to a build graph, generate a Ninja build script, and execute Ninja with this script. Update and expand tests to use temporary manifest files and verify Ninja script generation. Add and refactor test helpers for script creation and capturing Ninja invocations.

Changes

Cohort / File(s) Change Summary
Dependency Management
Cargo.toml
Move "tempfile" from [dev-dependencies] to [dependencies].
Ninja Runner Logic
src/runner.rs
Update run_ninja to load a manifest, build a graph, generate a Ninja build file, and run Ninja with this file. Add manifest_to_build_file helper. Adjust imports accordingly.
Test Logic and Coverage
tests/runner_tests.rs
Refactor test helpers to accept manifest paths. Create and use temporary manifest files in tests. Add a new test to verify Ninja script generation. Update imports.
Test Utilities
tests/support/mod.rs
Add write_script helper for script creation. Refactor fake_ninja to use it. Add fake_ninja_capture to capture and inspect Ninja build files. Add helper to write manifests.
Process Steps
tests/steps/process_steps.rs
Ensure manifest file exists before running Ninja; create temporary manifest if missing. Use idiomatic option handling for ninja executable path. Remove clippy lint suppression. Add imports and no-op reference to test helpers.

Sequence Diagram(s)

sequenceDiagram
    participant CLI
    participant Runner
    participant ManifestLoader
    participant IRBuilder
    participant NinjaGenerator
    participant TempFile
    participant NinjaProcess

    CLI->>Runner: run_ninja(program, cli, targets)
    Runner->>ManifestLoader: load_manifest(cli.file)
    ManifestLoader-->>Runner: Manifest
    Runner->>IRBuilder: manifest_to_graph(Manifest)
    IRBuilder-->>Runner: BuildGraph
    Runner->>NinjaGenerator: generate_ninja(BuildGraph)
    NinjaGenerator-->>Runner: NinjaScript
    Runner->>TempFile: write(NinjaScript)
    TempFile-->>Runner: temp_file_path
    Runner->>NinjaProcess: run_ninja(-f temp_file_path, targets)
    NinjaProcess-->>Runner: Output/Error
    Runner-->>CLI: Stream output/error
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Poem

In the forge where builds ignite,
A manifest’s path brings scripts to light.
Temporary files now lead the way,
Ninja awakes to dance and play.
With helpers new and tests refined,
The pipeline’s magic is redefined!
🥷✨

✨ 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/implement-manifest-to-ninja-build-process

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

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 5, 2025

Reviewer's Guide

This PR embeds the Netsukefile→IR→Ninja build file pipeline into the runner: it parses the manifest, constructs the IR graph, generates a Ninja script in a temp file, and then invokes ninja with that script. It also enhances tests with manifest-writing helpers and a capture variant to validate the end-to-end flow, and adds the requisite tempfile dependency.

Sequence diagram for manifest-to-Ninja pipeline integration

sequenceDiagram
    actor User
    participant Runner
    participant ManifestParser as manifest::from_path
    participant IR as ir::BuildGraph
    participant NinjaGen as ninja_gen::generate
    participant TempFile as NamedTempFile
    participant Ninja

    User->>Runner: run_ninja()
    Runner->>ManifestParser: Parse Netsukefile
    ManifestParser-->>Runner: Manifest
    Runner->>IR: BuildGraph::from_manifest(Manifest)
    IR-->>Runner: BuildGraph
    Runner->>NinjaGen: generate(BuildGraph)
    NinjaGen-->>Runner: Ninja script (String)
    Runner->>TempFile: Create temp file, write Ninja script
    TempFile-->>Runner: Path to temp build file
    Runner->>Ninja: Invoke with -f <temp build file>
    Ninja-->>User: Build output
Loading

File-Level Changes

Change Details Files
Integrate manifest-to-Ninja pipeline in runner
  • Load and parse the Netsukefile from cli.file via manifest::from_path
  • Build an IR graph using ir::BuildGraph::from_manifest
  • Generate Ninja script text with ninja_gen::generate
  • Write the script to a NamedTempFile, flush, and capture its path
  • Pass '-f ' flag when spawning the ninja process
src/runner.rs
Extend runner tests to cover full pipeline
  • Modify test_cli to accept a manifest PathBuf
  • Add write_manifest helper writing a sample Netsukefile to a temp file
  • Update existing tests to create and use a NamedTempFile manifest
  • Introduce run_pipeline_generates_ninja integration test that exercises manifest→IR→Ninja flow
tests/runner_tests.rs
Refactor test support and add capture variant
  • Extract write_script helper to generate fake shell scripts
  • Refactor fake_ninja to use write_script for exit-code scripts
  • Add fake_ninja_capture that captures the generated Ninja build file
tests/support/mod.rs
Add tempfile dependency for temp file support
  • Add tempfile = "3" to main dependencies in Cargo.toml
  • Remove duplicate tempfile entry under [[test]] section
Cargo.toml

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.

  • Consider refactoring run_ninja to separate the Ninja script generation (manifest→IR→ninja) from the actual process invocation for better readability and testability.
  • Rename test_cli to something like cli_with_manifest or cli_for_file to clarify that it accepts a manifest file path.
  • Extract the write_manifest helper into the shared test support module to avoid duplication and keep tests DRY.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider refactoring run_ninja to separate the Ninja script generation (manifest→IR→ninja) from the actual process invocation for better readability and testability.
- Rename test_cli to something like cli_with_manifest or cli_for_file to clarify that it accepts a manifest file path.
- Extract the write_manifest helper into the shared test support module to avoid duplication and keep tests DRY.

## Individual Comments

### Comment 1
<location> `src/runner.rs:59` </location>
<code_context>
+    let graph = ir::BuildGraph::from_manifest(&manifest).map_err(io::Error::other)?;
+    let ninja_script = ninja_gen::generate(&graph);
+
+    let mut build_file = NamedTempFile::new().map_err(io::Error::other)?;
+    build_file.write_all(ninja_script.as_bytes())?;
+    build_file.flush()?;
+    let build_path: PathBuf = build_file.path().to_path_buf();
+
     let mut cmd = Command::new(program);
</code_context>

<issue_to_address>
Consider handling the lifetime of the temporary file more explicitly.

Since the file handle isn't passed to the child process, the temporary file may be deleted before Ninja finishes using it. Ensure the file persists for the duration of the child process, either by keeping the handle alive or using another method.
</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 src/runner.rs 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: 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 46d1a0b and 01d1455.

📒 Files selected for processing (4)
  • Cargo.toml (1 hunks)
  • src/runner.rs (3 hunks)
  • tests/runner_tests.rs (2 hunks)
  • tests/support/mod.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
Cargo.toml

📄 CodeRabbit Inference Engine (AGENTS.md)

Cargo.toml: Use explicit version ranges in Cargo.toml and keep dependencies up-to-date.
Mandate caret requirements for all dependencies: All crate versions specified in Cargo.toml must use SemVer-compatible caret requirements (e.g., some-crate = "1.2.3").
Prohibit unstable version specifiers: The use of wildcard (*) or open-ended inequality (>=) version requirements is strictly forbidden. Tilde requirements (~) should only be used where a dependency must be locked to patch-level updates for a specific, documented reason.

Files:

  • Cargo.toml
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • tests/support/mod.rs
  • tests/runner_tests.rs
  • src/runner.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • tests/support/mod.rs
  • tests/runner_tests.rs
  • src/runner.rs
🔇 Additional comments (11)
Cargo.toml (1)

16-16: LGTM: Dependency promotion justified by main codebase usage.

The promotion of tempfile from dev-dependencies to main dependencies is appropriate given its usage in src/runner.rs for temporary Ninja build file generation.

src/runner.rs (3)

7-10: LGTM: Import organisation follows logical grouping.

The imports are well-organised with internal crates grouped together and standard library imports separated.


55-63: LGTM: Pipeline implementation follows proper error handling patterns.

The manifest loading, IR conversion, and Ninja generation steps properly convert domain errors to io::Error using map_err(io::Error::other). The temporary file handling correctly flushes before use and preserves the path for later reference.


71-71: LGTM: Ninja build file argument correctly specified.

The -f argument properly passes the temporary build file path to Ninja.

tests/runner_tests.rs (4)

12-21: LGTM: Test helper properly parameterised.

The test_cli function correctly accepts a PathBuf parameter for the manifest file, making tests more flexible.


30-35: LGTM: Existing tests properly updated for temporary manifests.

The tests correctly create temporary manifest files and pass their paths to the test CLI configuration.


47-83: LGTM: Comprehensive pipeline test validates end-to-end functionality.

The run_pipeline_generates_ninja test excellently validates the complete pipeline by:

  • Creating a temporary manifest with known content
  • Capturing the generated Ninja build file
  • Verifying the generated content matches expected Ninja rules and build statements
  • Using proper hash-based rule naming

The test demonstrates thorough understanding of the pipeline flow and provides good coverage.


85-97: LGTM: Helper function provides clean test data setup.

The write_manifest function properly encapsulates test manifest creation with realistic YAML content that exercises the pipeline.

tests/support/mod.rs (3)

8-20: LGTM: Helper function properly extracts common script creation logic.

The write_script function effectively eliminates code duplication and handles cross-platform executable permissions correctly with the #[cfg(unix)] conditional compilation.


25-30: LGTM: Refactored fake_ninja uses helper effectively.

The refactoring to use write_script improves code organisation and maintainability whilst preserving the original functionality.


37-46: LGTM: Comprehensive fake Ninja implementation for build file capture.

The fake_ninja_capture function provides excellent test infrastructure by:

  • Creating a shell script that properly parses command-line arguments
  • Correctly identifying and capturing the -f argument's build file
  • Using appropriate temporary file management
  • Including proper documentation and dead code allowance

The shell script logic correctly handles argument parsing and file capture for testing the pipeline.

Comment thread src/runner.rs 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: 6

🔭 Outside diff range comments (1)
tests/steps/process_steps.rs (1)

56-92: Manifest handling logic addresses pipeline integration requirements.

The code properly:

  • Resolves manifest paths relative to the temporary directory
  • Creates manifest files when they don't exist using the write_manifest helper
  • Updates CLI configuration to use the resolved path
  • Cleans up manifest files outside the temp directory

However, there are several issues:

  1. Mutable borrow issue: Line 56 takes a mutable reference to CLI, but line 71 attempts to clone from it whilst still borrowed mutably.

  2. Missing error context: File operations lack proper error context as required by the coding guidelines.

  3. Overly complex path resolution: The manifest path handling could be simplified.

Apply this diff to fix the mutable borrow and improve error handling:

-    let cli = world.cli.as_mut().expect("cli");
-
-    // Ensure a manifest exists at the path expected by the CLI.
-    let dir = world.temp.as_ref().expect("temp dir");
-    let manifest_path = if cli.file.is_absolute() {
-        cli.file.clone()
-    } else {
-        dir.path().join(&cli.file)
-    };
-    if !manifest_path.exists() {
-        let mut file = NamedTempFile::new_in(dir.path()).expect("manifest");
-        support::write_manifest(&mut file);
-        // Persist the temporary file to the desired manifest path.
-        file.persist(&manifest_path).expect("persist manifest");
-    }
-    cli.file.clone_from(&manifest_path);
+    let dir = world.temp.as_ref().expect("temp dir");
+    let manifest_path = {
+        let cli = world.cli.as_ref().expect("cli");
+        if cli.file.is_absolute() {
+            cli.file.clone()
+        } else {
+            dir.path().join(&cli.file)
+        }
+    };
+    
+    if !manifest_path.exists() {
+        let mut file = NamedTempFile::new_in(dir.path())
+            .expect("Failed to create temporary manifest file");
+        support::write_manifest(&mut file);
+        file.persist(&manifest_path)
+            .expect("Failed to persist manifest file");
+    }
+    
+    let cli = world.cli.as_mut().expect("cli");
+    cli.file.clone_from(&manifest_path);
♻️ Duplicate comments (2)
src/runner.rs (2)

42-58: Documentation improvement addresses previous feedback.

The updated documentation clearly describes the complete pipeline flow from Netsukefile → IR → Ninja generation → execution, addressing the previous review comment effectively.


56-58: Proper temporary file lifetime management.

The comment and implementation correctly ensure the build_file handle remains alive for the duration of the child process, preventing premature deletion of the temporary Ninja script.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 01d1455 and 0b03859.

📒 Files selected for processing (4)
  • src/runner.rs (4 hunks)
  • tests/runner_tests.rs (2 hunks)
  • tests/steps/process_steps.rs (3 hunks)
  • tests/support/mod.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • tests/steps/process_steps.rs
  • src/runner.rs
  • tests/runner_tests.rs
  • tests/support/mod.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • tests/steps/process_steps.rs
  • src/runner.rs
  • tests/runner_tests.rs
  • tests/support/mod.rs
🧬 Code Graph Analysis (4)
tests/steps/process_steps.rs (2)
tests/steps/cli_steps.rs (1)
  • manifest_path (94-97)
tests/support/mod.rs (1)
  • write_manifest (53-65)
src/runner.rs (3)
src/manifest.rs (1)
  • from_path (51-56)
src/ir.rs (1)
  • from_manifest (108-119)
src/ninja_gen.rs (1)
  • generate (37-73)
tests/runner_tests.rs (3)
tests/support/mod.rs (2)
  • write_manifest (53-65)
  • fake_ninja_capture (37-46)
src/runner.rs (1)
  • run_ninja (55-107)
src/hasher.rs (1)
  • hash (38-43)
tests/support/mod.rs (1)
tests/steps/process_steps.rs (1)
  • fake_ninja (32-35)
🔇 Additional comments (5)
tests/runner_tests.rs (3)

11-20: LGTM! Function signature improvement aligns with dynamic manifest handling.

The rename from test_cli to cli_with_manifest and the parameter change from hardcoded "Netsukefile" to a PathBuf argument properly supports the new dynamic manifest file approach.


29-31: LGTM! Proper temporary file management for test isolation.

The use of NamedTempFile with the write_manifest helper ensures each test operates with its own manifest file, providing proper test isolation.


46-75: Comprehensive end-to-end pipeline validation.

This test properly validates the complete manifest→IR→Ninja pipeline by:

  • Creating a temporary manifest
  • Capturing the generated Ninja build file using fake_ninja_capture
  • Verifying the generated content matches expected Ninja syntax with correct rule hash

The hash calculation and expected output format are correctly implemented.

tests/support/mod.rs (2)

8-20: Extract script creation logic effectively.

The write_script helper properly centralises executable script creation with correct permission handling on Unix platforms. The implementation correctly handles file creation and permission setting.


25-30: LGTM! Simplified fake ninja creation using the helper.

The refactored fake_ninja function now delegates script creation to the write_script helper, improving code reuse and maintainability.

Comment thread src/runner.rs
Comment on lines +109 to +119
/// Generate a temporary Ninja build file from a manifest.
fn manifest_to_build_file(path: &Path) -> io::Result<NamedTempFile> {
let manifest = manifest::from_path(path).map_err(io::Error::other)?;
let graph = ir::BuildGraph::from_manifest(&manifest).map_err(io::Error::other)?;
let ninja_script = ninja_gen::generate(&graph);

let mut build_file = NamedTempFile::new().map_err(io::Error::other)?;
build_file.write_all(ninja_script.as_bytes())?;
build_file.flush()?;
Ok(build_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.

🛠️ Refactor suggestion

Error handling violates Result type guidelines.

The manifest_to_build_file function uses io::Error::other() to convert all errors to io::Error, which loses important error context. The coding guidelines require proper error propagation and context.

Create a proper error type or improve error context:

-fn manifest_to_build_file(path: &Path) -> io::Result<NamedTempFile> {
-    let manifest = manifest::from_path(path).map_err(io::Error::other)?;
-    let graph = ir::BuildGraph::from_manifest(&manifest).map_err(io::Error::other)?;
+fn manifest_to_build_file(path: &Path) -> io::Result<NamedTempFile> {
+    let manifest = manifest::from_path(path)
+        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, 
+            format!("Failed to load manifest from {}: {}", path.display(), e)))?;
+    let graph = ir::BuildGraph::from_manifest(&manifest)
+        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData,
+            format!("Failed to convert manifest to build graph: {}", e)))?;
     let ninja_script = ninja_gen::generate(&graph);

-    let mut build_file = NamedTempFile::new().map_err(io::Error::other)?;
+    let mut build_file = NamedTempFile::new()
+        .map_err(|e| io::Error::new(io::ErrorKind::Other,
+            format!("Failed to create temporary build file: {}", e)))?;
     build_file.write_all(ninja_script.as_bytes())?;
     build_file.flush()?;
     Ok(build_file)
 }
📝 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
/// Generate a temporary Ninja build file from a manifest.
fn manifest_to_build_file(path: &Path) -> io::Result<NamedTempFile> {
let manifest = manifest::from_path(path).map_err(io::Error::other)?;
let graph = ir::BuildGraph::from_manifest(&manifest).map_err(io::Error::other)?;
let ninja_script = ninja_gen::generate(&graph);
let mut build_file = NamedTempFile::new().map_err(io::Error::other)?;
build_file.write_all(ninja_script.as_bytes())?;
build_file.flush()?;
Ok(build_file)
}
/// Generate a temporary Ninja build file from a manifest.
fn manifest_to_build_file(path: &Path) -> io::Result<NamedTempFile> {
let manifest = manifest::from_path(path)
.map_err(|e| io::Error::new(
io::ErrorKind::InvalidData,
format!("Failed to load manifest from {}: {}", path.display(), e),
))?;
let graph = ir::BuildGraph::from_manifest(&manifest)
.map_err(|e| io::Error::new(
io::ErrorKind::InvalidData,
format!("Failed to convert manifest to build graph: {}", e),
))?;
let ninja_script = ninja_gen::generate(&graph);
let mut build_file = NamedTempFile::new()
.map_err(|e| io::Error::new(
io::ErrorKind::Other,
format!("Failed to create temporary build file: {}", e),
))?;
build_file.write_all(ninja_script.as_bytes())?;
build_file.flush()?;
Ok(build_file)
}
🤖 Prompt for AI Agents
In src/runner.rs around lines 109 to 119, the function manifest_to_build_file
improperly converts all errors to io::Error using io::Error::other(), losing
error context. To fix this, define a custom error type or use a suitable error
handling crate like thiserror or anyhow to propagate errors with full context.
Replace map_err(io::Error::other) calls with proper conversions or use the ?
operator to propagate errors while preserving their original types and messages.

Comment thread src/runner.rs Outdated
Comment thread tests/runner_tests.rs
Comment thread tests/support/mod.rs
Comment thread tests/support/mod.rs Outdated
Comment on lines +49 to +51
#[allow(
dead_code,
reason = "helper is unused when the support crate builds independently"
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

Inappropriate use of #[allow] violates coding guidelines.

The coding guidelines explicitly forbid #[allow] and require #[expect] with reasons instead. Additionally, the dead_code suppression should be more narrowly scoped.

Replace the lint suppression:

-#[allow(dead_code, reason = "not every test exercises the capture variant")]
+#[expect(dead_code, reason = "not every test exercises the capture variant")]

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

🤖 Prompt for AI Agents
In tests/support/mod.rs around lines 49 to 51, replace the #[allow(dead_code,
reason = "...")] attribute with #[expect(dead_code, reason = "...")] to comply
with coding guidelines that forbid #[allow]. Also, narrow the scope of the
dead_code suppression to only the specific helper function or item that is
unused, rather than applying it broadly.

Comment thread tests/support/mod.rs
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 (2)
tests/support/mod.rs (1)

32-56: Shell script robustness improvements implemented.

The script now properly handles argument parsing with $# checks and ensures -f has a following argument, addressing the previous review concerns.

src/runner.rs (1)

136-144: Replace io::Error::other with proper error kinds.

The use of io::Error::other violates the error handling guidelines. Use appropriate error kinds instead.

-    let mut build_file = NamedTempFile::new()
-        .map_err(|e| io::Error::other(format!("Failed to create temporary build file: {e}")))?;
+    let mut build_file = NamedTempFile::new()
+        .map_err(|e| io::Error::new(
+            io::ErrorKind::Other,
+            format!("Failed to create temporary build file: {e}")
+        ))?;
     build_file
         .write_all(ninja_script.as_bytes())
-        .map_err(|e| io::Error::other(format!("Failed to write build file: {e}")))?;
+        .map_err(|e| io::Error::new(
+            e.kind(),
+            format!("Failed to write build file: {e}")
+        ))?;
     build_file
         .flush()
-        .map_err(|e| io::Error::other(format!("Failed to flush build file: {e}")))?;
+        .map_err(|e| io::Error::new(
+            e.kind(),
+            format!("Failed to flush build file: {e}")
+        ))?;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0b03859 and 97bd6d8.

📒 Files selected for processing (4)
  • src/runner.rs (4 hunks)
  • tests/runner_tests.rs (2 hunks)
  • tests/steps/process_steps.rs (3 hunks)
  • tests/support/mod.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • tests/support/mod.rs
  • src/runner.rs
  • tests/runner_tests.rs
  • tests/steps/process_steps.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • tests/support/mod.rs
  • src/runner.rs
  • tests/runner_tests.rs
  • tests/steps/process_steps.rs
🧬 Code Graph Analysis (3)
tests/support/mod.rs (1)
tests/steps/process_steps.rs (1)
  • fake_ninja (32-35)
src/runner.rs (3)
src/manifest.rs (1)
  • from_path (51-56)
src/ir.rs (1)
  • from_manifest (108-119)
src/ninja_gen.rs (1)
  • generate (37-73)
tests/steps/process_steps.rs (1)
tests/support/mod.rs (2)
  • fake_ninja_capture (36-56)
  • write_manifest (59-71)
🔇 Additional comments (12)
tests/runner_tests.rs (5)

1-4: Documentation improvements look good!

The expanded module documentation clearly explains that the tests verify both manifest translation and Ninja process invocation.


14-23: Helper function refactoring is appropriate.

The renamed function with the PathBuf parameter provides better flexibility for tests to specify different manifest paths.


31-37: Test updates correctly handle temporary manifest files.

The test properly creates a temporary manifest and passes its path to the runner.


40-47: Consistent test pattern implementation.

The test follows the same pattern as run_ninja_status for manifest handling.


49-78: Comprehensive end-to-end pipeline test.

The test effectively verifies the complete manifest-to-Ninja pipeline, including correct hash generation and build script formatting.

tests/steps/process_steps.rs (2)

60-74: Robust manifest file handling.

The code correctly ensures a manifest exists at the CLI-specified path, handling both absolute and relative paths appropriately.


91-94: Appropriate cleanup of test artifacts.

The cleanup logic correctly removes manifests created outside the temporary directory, preventing test pollution.

tests/support/mod.rs (3)

8-20: Well-structured helper function for script creation.

The write_script function properly centralizes script creation with appropriate Unix permissions handling.


22-30: Clean refactoring using the helper function.

The refactored implementation properly delegates script creation to the helper.


58-71: Proper test manifest generation.

The function creates a valid minimal Netsukefile with appropriate use of concat! for the multi-line string literal.

src/runner.rs (2)

56-68: Pipeline integration implemented correctly.

The implementation properly manages the temporary build file lifetime and passes it to Ninja via the -f flag.


122-133: Proper error context for manifest operations.

The error handling for manifest loading and graph conversion provides clear context about what failed.

Comment on lines +56 to +57
// Touch the capture variant so the support module's helpers remain used.
let _ = support::fake_ninja_capture as fn() -> (TempDir, PathBuf, PathBuf);
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

Remove the workaround for unused function reference.

The comment indicates this is keeping fake_ninja_capture artificially referenced. Instead, use #[expect(dead_code)] on the function in the support module if it's genuinely unused in some contexts.

-    // Touch the capture variant so the support module's helpers remain used.
-    let _ = support::fake_ninja_capture as fn() -> (TempDir, PathBuf, PathBuf);
📝 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
// Touch the capture variant so the support module's helpers remain used.
let _ = support::fake_ninja_capture as fn() -> (TempDir, PathBuf, PathBuf);
🤖 Prompt for AI Agents
In tests/steps/process_steps.rs around lines 56 to 57, remove the line that
assigns `support::fake_ninja_capture` to an unused variable as a workaround to
keep the function referenced. Instead, go to the support module where
`fake_ninja_capture` is defined and add the attribute `#[expect(dead_code)]` to
that function to suppress unused code warnings properly.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 5, 2025

Stale

@leynos leynos closed this Aug 5, 2025
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