Skip to content

Add Ninja version output in CI#38

Merged
leynos merged 3 commits intomainfrom
fcu4tw-codex/implement-ninja-file-synthesizer
Jul 31, 2025
Merged

Add Ninja version output in CI#38
leynos merged 3 commits intomainfrom
fcu4tw-codex/implement-ninja-file-synthesizer

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 31, 2025

Summary

  • show the installed Ninja version in CI
  • refactor ninja_gen using Display impls
  • sort edges stably and deduplicate by all outputs
  • document the updated strategy in the design doc
  • add class diagram for IR and generator
  • improve default target generation and path joining
  • broaden unit tests for Ninja generator
  • check Ninja availability in integration tests
  • clarify behavioural test failure messages

Testing

  • make lint
  • make test
  • make markdownlint
  • make nixie (fails: FileNotFound for commander package)

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

Summary by Sourcery

Introduce deterministic Ninja build file generation support, update CI to display Ninja version, enhance design documentation with class diagrams, and expand testing coverage for the Ninja generator.

New Features:

  • Print the installed Ninja version in the CI workflow
  • Add ninja_gen module to generate deterministic Ninja build files from the IR

Enhancements:

  • Refactor ninja_gen to use Display implementations with stable sorting and edge deduplication
  • Improve default target handling and path joining, and mark Ninja generation tasks complete in the roadmap

Build:

  • Add itertools, insta, and tempfile dependencies for generation and testing

CI:

  • Add a CI step to show the Ninja version

Documentation:

  • Document the updated Ninja generation strategy with class diagrams in the design document

Tests:

  • Add unit tests, Insta snapshot tests, and Cucumber feature tests for the Ninja generator
  • Integration tests now check Ninja availability and validate no-op behavior

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 31, 2025

Reviewer's Guide

This PR introduces a new deterministic Ninja build file generator (ninja_gen) using Display-based formatting with stable sorting and deduplication, enriches documentation with class diagrams and updated roadmap entries, updates the CI workflow to display and verify the Ninja version, adds necessary dependencies for generation and testing, and greatly expands unit and integration test coverage (including snapshot and Cucumber tests).

Class diagram for IR and Ninja generator

classDiagram
    class BuildGraph {
        +HashMap<String, Action> actions
        +HashMap<PathBuf, BuildEdge> targets
        +Vec<PathBuf> default_targets
    }
    class Action {
        +Recipe recipe
        +Option<String> description
        +Option<String> depfile
        +Option<String> deps_format
        +Option<String> pool
        +bool restat
    }
    class BuildEdge {
        +String action_id
        +Vec<PathBuf> inputs
        +Vec<PathBuf> explicit_outputs
        +Vec<PathBuf> implicit_outputs
        +Vec<PathBuf> order_only_deps
        +bool phony
        +bool always
    }
    class Recipe {
        <<enum>>
        Command
        Script
        Rule
    }
    class ninja_gen {
        +generate(graph: &BuildGraph) String
    }
    BuildGraph "1" o-- "many" Action : actions
    BuildGraph "1" o-- "many" BuildEdge : targets
    Action "1" o-- "1" Recipe
    BuildEdge "1" --> "1" Action : action_id
    ninja_gen ..> BuildGraph : uses
    ninja_gen ..> Action : uses
    ninja_gen ..> BuildEdge : uses
    ninja_gen ..> Recipe : uses
Loading

File-Level Changes

Change Details Files
Implement deterministic Ninja file generator using Display implementations
  • Define generate() to serialize Ninja rules and build edges via NamedAction and DisplayEdge structs
  • Introduce write_kv! and write_flag! macros for optional key-value pairs and flags
  • Sort actions by identifier and edges by joined explicit-output paths for stable ordering
  • Deduplicate build edges based on explicit-output path keys using a HashSet
  • Add join() and path_key() helpers leveraging itertools for path handling
src/ninja_gen.rs
Expand test coverage for the Ninja generator
  • Add broad unit tests covering phony targets, multi-output builds, and empty graphs
  • Introduce end-to-end snapshot tests with insta, tempfile, and real ninja binary validation
  • Extend Cucumber scenarios, feature file, and step definitions for behaviour-driven tests
tests/ninja_gen_tests.rs
tests/ninja_snapshot_tests.rs
tests/steps/ninja_steps.rs
tests/features/ninja.feature
tests/cucumber.rs
Update CI workflow to report and verify Ninja version
  • Insert a CI step to run ninja --version before formatting and linting
  • Add logic in integration tests to skip if Ninja binary is unavailable
.github/workflows/ci.yml
Add dependencies for generation and testing
  • Add itertools for stable sorting and joins
  • Add insta for snapshot testing
  • Add tempfile for isolated integration test directories
Cargo.toml
Augment project exports and documentation
  • Expose ninja_gen module in lib.rs
  • Embed class diagram and describe sorting/deduplication strategy in design doc
  • Mark ninja file synthesizer tasks as done in the roadmap
src/lib.rs
docs/netsuke-design.md
docs/roadmap.md

Tips and commands

Interacting with Sourcery

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

Customizing Your Experience

Access your dashboard to:

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

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 31, 2025

Summary by CodeRabbit

New Features

  • Introduced Ninja build file generation from the internal build graph, producing deterministic and valid Ninja files.
  • Exposed the Ninja generator module as part of the public API.
  • Added new dependencies to support file generation and testing.

Documentation

  • Enhanced design documentation with diagrams and detailed IR design decisions.
  • Updated roadmap to reflect completed tasks related to Ninja file generation.

Tests

  • Added comprehensive unit, integration, and Cucumber feature tests to validate Ninja file generation and execution.
  • Implemented snapshot and end-to-end tests to ensure correctness and deterministic output.

Chores

  • Updated CI workflow to display the installed Ninja version for improved build visibility.

Walkthrough

Introduce a Ninja build file generator module (ninja_gen) that serialises the internal IR (BuildGraph) into valid Ninja syntax. Update documentation with diagrams and design notes, expand the roadmap, and add comprehensive unit, integration, and Cucumber tests for Ninja file generation. Amend CI to display the Ninja version. Update dependencies accordingly.

Changes

Cohort / File(s) Change Summary
Ninja Generator Module
src/ninja_gen.rs, src/lib.rs
Add ninja_gen module with a public generate function for converting BuildGraph to Ninja syntax. Expose the module publicly in the library root.
Ninja Generation Unit and Integration Tests
tests/ninja_gen_tests.rs, tests/ninja_snapshot_tests.rs
Add unit tests for various Ninja file generation scenarios and an integration test that snapshots and validates generated Ninja files with the real Ninja tool.
Cucumber Integration for Ninja Generation
tests/cucumber.rs, tests/features/ninja.feature, tests/steps/mod.rs, tests/steps/ninja_steps.rs
Extend the Cucumber world state to store generated Ninja files. Add step definitions and feature scenarios to test Ninja file generation and content assertions.
Documentation Updates
docs/netsuke-design.md, docs/roadmap.md
Add a Mermaid class diagram and design notes to the design doc. Mark relevant roadmap items as complete.
Dependency and CI Updates
Cargo.toml, .github/workflows/ci.yml
Add itertools, insta, and tempfile dependencies. Update CI workflow to print the Ninja version after Rust setup.

Sequence Diagram(s)

sequenceDiagram
    participant Manifest
    participant IR (BuildGraph)
    participant NinjaGen
    participant NinjaFile
    participant NinjaTool

    Manifest->>IR (BuildGraph): Parse manifest to IR
    IR (BuildGraph)->>NinjaGen: Pass BuildGraph for generation
    NinjaGen->>NinjaFile: Generate Ninja file content
    NinjaFile->>NinjaTool: Ninja tool consumes generated file
    NinjaTool-->>NinjaFile: Build/validate targets
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Possibly related PRs

Poem

In the forge of code, a Ninja appears,
IR transformed, as syntax clears.
Tests and docs in harmony blend,
Snapshots and builds that never end.
With rules and edges, so precise—
The build now dances, neat and nice!
🥷✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d97529 and cabe782.

📒 Files selected for processing (4)
  • docs/netsuke-design.md (2 hunks)
  • src/ninja_gen.rs (1 hunks)
  • tests/ninja_gen_tests.rs (1 hunks)
  • tests/ninja_snapshot_tests.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.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:

  • src/ninja_gen.rs
  • tests/ninja_snapshot_tests.rs
  • tests/ninja_gen_tests.rs
**/*.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:

  • docs/netsuke-design.md
🧠 Learnings (1)
📚 Learning: applies to docs/src/ir.rs : implement the ir::from_manifest transformation logic to convert the ast ...
Learnt from: CR
PR: leynos/netsuke#0
File: docs/roadmap.md:0-0
Timestamp: 2025-07-27T17:59:36.506Z
Learning: Applies to docs/src/ir.rs : Implement the ir::from_manifest transformation logic to convert the AST into the BuildGraph IR.

Applied to files:

  • docs/netsuke-design.md
🧬 Code Graph Analysis (1)
tests/ninja_snapshot_tests.rs (3)
src/manifest.rs (1)
  • from_str (33-35)
src/ir.rs (1)
  • from_manifest (108-119)
src/ninja_gen.rs (1)
  • generate (37-73)
🔇 Additional comments (13)
docs/netsuke-design.md (2)

963-1004: Excellent visual documentation enhancement.

The Mermaid class diagram effectively illustrates the relationships between IR components and the ninja_gen generator. The syntax is correct and the cardinality indicators properly show the one-to-many relationships between BuildGraph and its constituent elements.


1117-1123: Well-documented implementation decisions.

These additions accurately capture key design choices in the Ninja generator implementation. The emphasis on deterministic output through sorting and the comprehensive testing approach using both snapshot tests and real Ninja execution are sound engineering practices.

src/ninja_gen.rs (4)

1-13: Clear module documentation and appropriate imports.

The module documentation effectively explains the purpose and key behaviours, particularly the deterministic sorting for snapshot tests. The imports are well-organised and include all necessary dependencies.


75-85: Well-designed helper functions.

Both functions are focused and effective. The path_key function particularly demonstrates good design by using sorted components with null separators to ensure stable, unique keys for deduplication.


113-141: Comprehensive build edge formatting.

The implementation correctly handles all Ninja build statement components including explicit/implicit outputs, order-only dependencies, and phony targets. The conditional restat logic is particularly well-thought-out.


143-184: Good basic test coverage.

The test effectively validates the core generation functionality with a simple but complete example. It provides a solid foundation alongside the more comprehensive unit tests in the separate test files.

tests/ninja_snapshot_tests.rs (3)

1-12: Excellent integration test strategy.

The documentation clearly explains the comprehensive end-to-end validation approach using both snapshot testing and real Ninja execution. The imports are well-chosen for this testing strategy.


13-21: Well-designed command execution helper.

The function provides excellent error reporting by including stderr content in assertion failures, and appropriately handles the common pattern of running commands in tests.


48-81: Comprehensive end-to-end validation.

The test provides thorough validation through snapshot testing and multiple Ninja command executions. The final check for "no work to do" on the second run is particularly valuable for verifying correct dependency tracking.

tests/ninja_gen_tests.rs (4)

13-45: Focused test for phony target generation.

The test correctly validates that phony targets use the special "phony" rule in the generated Ninja output. The test structure is clear and appropriately focused on this specific functionality.


47-79: Solid test for standard build scenarios.

The test effectively validates standard build rule generation with realistic compiler commands and multiple inputs. The expected output correctly demonstrates proper Ninja build statement formatting.


81-113: Excellent coverage of complex Ninja syntax.

The test thoroughly validates complex build statement generation including multiple explicit outputs, implicit outputs with | separator, and order-only dependencies with || separator. This provides crucial validation of the complex formatting logic.


115-120: Important edge case coverage.

The test appropriately validates the edge case of empty build graphs producing empty output. Simple but essential for ensuring robust behaviour across all input scenarios.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fcu4tw-codex/implement-ninja-file-synthesizer

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai 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.

@leynos leynos mentioned this pull request Jul 31, 2025
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

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

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

### Comment 1
<location> `tests/ninja_snapshot_tests.rs:25` </location>
<code_context>
+
+#[test]
+fn touch_manifest_ninja_validation() {
+    Command::new("ninja")
+        .arg("--version")
+        .output()
+        .expect("ninja must be installed for integration tests");
+    let manifest_yaml = r#"
</code_context>

<issue_to_address>
Consider skipping the test if Ninja is not installed.

The test currently fails if Ninja is missing, which can disrupt CI and local runs. Use `#[ignore]` or a runtime check to skip the test with a clear message when Ninja isn't available.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
#[test]
fn touch_manifest_ninja_validation() {
    Command::new("ninja")
        .arg("--version")
        .output()
        .expect("ninja must be installed for integration tests");
    let manifest_yaml = r#"
=======
#[test]
fn touch_manifest_ninja_validation() {
    let ninja_check = Command::new("ninja")
        .arg("--version")
        .output();

    if ninja_check.is_err() || !ninja_check.as_ref().unwrap().status.success() {
        eprintln!("skipping test: ninja must be installed for integration tests");
        return;
    }

    let manifest_yaml = r#"
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `src/ninja_gen.rs:76` </location>
<code_context>
+    action: &'a crate::ir::Action,
+}
+
+impl Display for NamedAction<'_> {
+    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+        writeln!(f, "rule {}", self.id)?;
</code_context>

<issue_to_address>
Consider introducing a small macro to handle repeated key-value writing logic in Display implementations.

Consider collapsing all those repetitive `if let Some(...) { writeln!(f, "  key = {}", val)?; }` calls into a tiny helper. For example, at the top of the file:

```rust
macro_rules! write_kv {
    ($f:expr, $key:expr, $opt:expr) => {
        if let Some(v) = $opt {
            writeln!($f, "  {} = {}", $key, v)?;
        }
    };
}
```

Then your `impl Display for NamedAction` becomes:

```rust
impl Display for NamedAction<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "rule {}", self.id)?;
        match &self.action.recipe {
            Recipe::Command { command } => writeln!(f, "  command = {command}")?,
            Recipe::Script { script } => {
                writeln!(f, "  command = /bin/sh -e -c \"")?;
                for line in script.lines() {
                    writeln!(f, "    {line}")?;
                }
                writeln!(f, "  \"")?;
            }
            Recipe::Rule { .. } => unreachable!(),
        }

        write_kv!(f, "description", &self.action.description);
        write_kv!(f, "depfile", &self.action.depfile);
        write_kv!(f, "deps", &self.action.deps_format);
        write_kv!(f, "pool", &self.action.pool);
        if self.action.restat {
            writeln!(f, "  restat = 1")?;
        }
        writeln!(f)
    }
}
```

You can apply the same macro-oriented approach in `DisplayEdge` to shrink its boilerplate as well. This keeps all functionality, but makes both impls far more declarative and easier to scan.
</issue_to_address>

### Comment 3
<location> `docs/roadmap.md:58` </location>
<code_context>

-  - [ ] Implement the Ninja file synthesizer in
-    [src/ninja_gen.rs](src/ninja_gen.rs) to traverse the BuildGraph IR.
+  - [x] Implement the Ninja file synthesizer in
+    [src/ninja_gen.rs](src/ninja_gen.rs) to traverse the BuildGraph IR. *(done)*

</code_context>

<issue_to_address>
Bullet point exceeds 80 columns and should be wrapped for readability.

Please wrap this bullet point so that no line exceeds 80 columns, as per the documentation guidelines.
</issue_to_address>

### Comment 4
<location> `docs/roadmap.md:61` </location>
<code_context>

-  - [ ] Write logic to generate Ninja rule statements from ir::Action structs
-    and build statements from ir::BuildEdge structs.
+  - [x] Write logic to generate Ninja rule statements from ir::Action structs
+    and build statements from ir::BuildEdge structs. *(done)*

</code_context>

<issue_to_address>
Bullet point exceeds 80 columns and should be wrapped for readability.

Please wrap this bullet point so that no line exceeds 80 columns, as per the documentation guidelines.
</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 tests/ninja_snapshot_tests.rs
Comment thread src/ninja_gen.rs
Comment thread docs/roadmap.md
Comment thread docs/roadmap.md
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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd898d5 and 8d97529.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • tests/snapshots/ninja/ninja_snapshot_tests__touch_manifest_ninja.snap is excluded by !**/*.snap
📒 Files selected for processing (12)
  • .github/workflows/ci.yml (1 hunks)
  • Cargo.toml (2 hunks)
  • docs/netsuke-design.md (2 hunks)
  • docs/roadmap.md (1 hunks)
  • src/lib.rs (1 hunks)
  • src/ninja_gen.rs (1 hunks)
  • tests/cucumber.rs (1 hunks)
  • tests/features/ninja.feature (1 hunks)
  • tests/ninja_gen_tests.rs (1 hunks)
  • tests/ninja_snapshot_tests.rs (1 hunks)
  • tests/steps/mod.rs (1 hunks)
  • tests/steps/ninja_steps.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
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/steps/mod.rs
  • tests/cucumber.rs
  • src/lib.rs
  • src/ninja_gen.rs
  • tests/ninja_snapshot_tests.rs
  • tests/steps/ninja_steps.rs
  • tests/ninja_gen_tests.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/mod.rs
  • tests/cucumber.rs
  • src/lib.rs
  • src/ninja_gen.rs
  • tests/ninja_snapshot_tests.rs
  • tests/steps/ninja_steps.rs
  • tests/ninja_gen_tests.rs
docs/**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

docs/**/*.md: Use the markdown files within the docs/ directory as a knowledge base and source of truth for project requirements, dependency choices, and architectural decisions.
Proactively update the relevant file(s) in the docs/ directory to reflect the latest state when new decisions are made, requirements change, libraries are added/removed, or architectural patterns evolve.

Files:

  • docs/roadmap.md
  • docs/netsuke-design.md
**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.md: Documentation must use en-GB-oxendict spelling and grammar, except for the naming of the "LICENSE" file.
Validate Markdown files using make markdownlint.
Run make fmt after any documentation changes to format all Markdown files and fix table markup.
Validate Mermaid diagrams in Markdown files by running make nixie.
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks in Markdown must be wrapped at 120 columns.
Tables and headings in Markdown must not be wrapped.
Use dashes (-) for list bullets in Markdown.
Use GitHub-flavoured Markdown footnotes ([^1]) for references and footnotes.

Files:

  • docs/roadmap.md
  • docs/netsuke-design.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:

  • docs/roadmap.md
  • docs/netsuke-design.md
🧠 Learnings (3)
📚 Learning: applies to docs/src/ninja_gen.rs : implement the ninja file synthesizer in src/ninja_gen.rs to trave...
Learnt from: CR
PR: leynos/netsuke#0
File: docs/roadmap.md:0-0
Timestamp: 2025-07-27T17:59:36.506Z
Learning: Applies to docs/src/ninja_gen.rs : Implement the Ninja file synthesizer in src/ninja_gen.rs to traverse the BuildGraph IR.

Applied to files:

  • docs/roadmap.md
📚 Learning: applies to docs/src/ninja_gen.rs : write logic to generate ninja rule statements from ir::action str...
Learnt from: CR
PR: leynos/netsuke#0
File: docs/roadmap.md:0-0
Timestamp: 2025-07-27T17:59:36.506Z
Learning: Applies to docs/src/ninja_gen.rs : Write logic to generate Ninja rule statements from ir::Action structs and build statements from ir::BuildEdge structs.

Applied to files:

  • docs/roadmap.md
📚 Learning: applies to docs/src/ir.rs : implement the ir::from_manifest transformation logic to convert the ast ...
Learnt from: CR
PR: leynos/netsuke#0
File: docs/roadmap.md:0-0
Timestamp: 2025-07-27T17:59:36.506Z
Learning: Applies to docs/src/ir.rs : Implement the ir::from_manifest transformation logic to convert the AST into the BuildGraph IR.

Applied to files:

  • docs/netsuke-design.md
🧬 Code Graph Analysis (2)
tests/steps/ninja_steps.rs (1)
src/ninja_gen.rs (1)
  • generate (20-56)
tests/ninja_gen_tests.rs (1)
src/ninja_gen.rs (1)
  • generate (20-56)
🔇 Additional comments (22)
src/lib.rs (1)

11-11: LGTM! Module declaration follows proper conventions.

The ninja_gen module is correctly declared and maintains alphabetical ordering with other public modules.

tests/steps/mod.rs (1)

4-4: LGTM! Module declaration maintains proper ordering.

The ninja_steps module is correctly declared and preserves alphabetical ordering with other step modules.

tests/cucumber.rs (1)

10-10: LGTM! Field addition follows established patterns.

The ninja field correctly extends the CliWorld struct using the same Option<String> pattern as other state fields.

Cargo.toml (2)

15-15: LGTM! Dependency follows version requirements.

The itertools dependency correctly uses caret versioning and maintains alphabetical ordering.


61-62: LGTM! Dev dependencies properly configured.

Both insta with yaml feature and tempfile use appropriate caret versioning and support the new testing infrastructure.

docs/roadmap.md (1)

58-62: LGTM! Roadmap updates accurately reflect completed work.

The completed tasks are properly documented with cross-references to the implementation, maintaining clear project tracking.

tests/features/ninja.feature (1)

1-13: Well-structured feature tests covering core Ninja generation scenarios.

The scenarios effectively validate both standard builds and phony targets, providing good behavioural test coverage for the new functionality.

docs/netsuke-design.md (2)

963-1004: Excellent class diagram illustrating the IR and generator architecture.

The Mermaid diagram clearly shows the relationships between data structures and the ninja_gen generator, providing valuable architectural documentation.


1117-1122: Important design notes ensuring deterministic builds.

The documentation of sorting and deduplication strategies is crucial for cross-platform stability and aligns well with the implementation approach.

tests/steps/ninja_steps.rs (1)

1-27: Well-implemented Cucumber step definitions.

The steps correctly handle the test workflow, use proper error handling with descriptive messages, and appropriately manage the clippy lint for Cucumber's String requirements.

src/ninja_gen.rs (4)

1-6: Excellent module documentation.

The module doc clearly explains the purpose and highlights the deterministic output guarantee, which is crucial for reproducible builds.


63-68: Solid path key generation for cross-platform stability.

The path_key function correctly normalises paths and uses null separator for uniqueness. The sorting ensures deterministic ordering across platforms.


147-181: Comprehensive test covering the main generation workflow.

The test validates rule generation, build edge formatting, and default target handling with a realistic example.


29-47: Resolve edge deduplication logic
Deduplication by the full set of explicit outputs is intentional and documented in docs/netsuke-design.md. No changes required.

tests/ninja_snapshot_tests.rs (4)

1-12: Excellent module documentation and imports.

The module documentation clearly explains the purpose and testing strategy. Imports are well-organised and necessary for the functionality.


13-21: Well-implemented helper function with proper error handling.

Good use of expect with descriptive messages and appropriate error context when commands fail.


23-56: Solid test setup with good error handling.

The test properly checks for Ninja availability and handles errors appropriately. The embedded YAML manifest is acceptable for this test size, though consider moving to an external file if it grows significantly larger.


57-80: Comprehensive integration testing with excellent validation.

The test thoroughly validates the generated Ninja file through multiple operations and includes the crucial no-op second build check. The closure pattern for Ninja commands is clean and maintainable.

tests/ninja_gen_tests.rs (4)

9-41: Well-structured test for phony target generation.

Good use of concat! for string literals and proper validation of Ninja syntax for phony builds.


43-75: Solid test coverage for standard build scenarios.

The test appropriately covers the common compilation use case with multiple inputs and validates correct Ninja syntax generation.


77-109: Excellent coverage of complex dependency scenarios.

The test properly validates the generation of multiple explicit outputs, implicit outputs (|), and order-only dependencies (||) with correct Ninja syntax.


111-116: Good edge case coverage for empty graphs.

Proper validation that empty build graphs produce empty output, ensuring graceful handling of edge cases.

Comment thread .github/workflows/ci.yml
Comment thread src/ninja_gen.rs
Comment thread src/ninja_gen.rs Outdated
Comment thread tests/ninja_gen_tests.rs
Repository owner deleted a comment from sourcery-ai Bot Jul 31, 2025
Repository owner deleted a comment from sourcery-ai Bot Jul 31, 2025
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 31, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 31, 2025

✅ Actions performed

Review triggered.

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

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 31, 2025

@sourcery-ai review

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @leynos - I've reviewed your changes - here's some feedback:

  • Instead of silently returning in integration tests when Ninja is missing, consider using #[ignore] or a test-harness skip mechanism so that missing prerequisites are reported as skipped tests rather than no-ops.
  • The CI workflow currently only prints the Ninja version; consider parsing that output and enforcing a minimum supported version to fail early on incompatible environments.
  • The deduplication in ninja_gen.generate only keys off explicit outputs—edges that differ only by implicit outputs or inputs will be collapsed, so you may want to expand the key or document this trade-off.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Instead of silently returning in integration tests when Ninja is missing, consider using #[ignore] or a test-harness skip mechanism so that missing prerequisites are reported as skipped tests rather than no-ops.
- The CI workflow currently only prints the Ninja version; consider parsing that output and enforcing a minimum supported version to fail early on incompatible environments.
- The deduplication in ninja_gen.generate only keys off explicit outputs—edges that differ only by implicit outputs or inputs will be collapsed, so you may want to expand the key or document this trade-off.

## Individual Comments

### Comment 1
<location> `tests/features/ninja.feature:1` </location>
<code_context>
+Feature: Ninja file generation
+
+  Scenario: Generate build statements
</code_context>

<issue_to_address>
Consider replacing the Cucumber feature file with direct Rust tests to simplify the test suite.

Consider replacing the Cucumber feature with a couple of focused Rust tests—either plain `assert!` checks or a snapshot test—so you keep all of the coverage but remove the extra BDD layer.

1) Delete `features/ninja.feature`.  
2) Add something like this in `tests/ninja_generation.rs`:

```rust
use mycrate::{compile_manifest, generate_ninja};

#[test]
fn generate_rules() {
    let ir = compile_manifest("tests/data/rules.yml").unwrap();
    let ninja = generate_ninja(&ir);
    assert!(ninja.contains("rule"), "expected a rule block");
    assert!(ninja.contains("build hello.o:"), "expected hello.o build");
}

#[test]
fn generate_phony() {
    let ir = compile_manifest("tests/data/phony.yml").unwrap();
    let ninja = generate_ninja(&ir);
    assert!(ninja.contains("build clean: phony"), "expected phony target");
}
```

3) (Optional) If you want full-file regression, you can use insta:

```rust
use insta::assert_snapshot;
use mycrate::{compile_manifest, generate_ninja};

#[test]
fn ninja_rules_snapshot() {
    let ir = compile_manifest("tests/data/rules.yml").unwrap();
    let ninja = generate_ninja(&ir);
    assert_snapshot!(ninja);
}
```
</issue_to_address>

### Comment 2
<location> `tests/steps/ninja_steps.rs:8` </location>
<code_context>
+use netsuke::ninja_gen;
+
+#[when("the ninja file is generated")]
+fn generate_ninja(world: &mut CliWorld) {
+    let graph = world
+        .build_graph
</code_context>

<issue_to_address>
Consider extracting repeated logic into `CliWorld` helper methods to make step handlers one-liners.

Consider moving the `as_ref().expect()` and generation/assertion logic into `CliWorld` helpers so each step handler is a one-liner. For example:

```rust
// in src/cli_world.rs
impl CliWorld {
    pub fn generate_ninja(&mut self) {
        let graph = self
            .build_graph
            .as_ref()
            .expect("build graph should be available");
        self.ninja = Some(netsuke::ninja_gen::generate(graph));
    }

    pub fn assert_ninja_contains(&self, expected: &str) {
        let ninja = self
            .ninja
            .as_ref()
            .expect("ninja content should be available");
        assert!(
            ninja.contains(expected),
            "expected ninja to contain {:?}, got {:?}",
            expected,
            ninja
        );
    }
}
```

Then shrink each step definition to:

```rust
#[when("the ninja file is generated")]
fn generate_ninja(world: &mut CliWorld) {
    world.generate_ninja();
}

#[then(expr = "the ninja file contains {string}")]
fn ninja_contains(world: &mut CliWorld, text: String) {
    world.assert_ninja_contains(&text);
}
```

This preserves cucumber steps but removes the repeated boilerplate and keeps the fns trivial.
</issue_to_address>

### Comment 3
<location> `docs/netsuke-design.md:965` </location>
<code_context>

+```mermaid
+classDiagram
+    class BuildGraph {
+        +HashMap<String, Action> actions
+        +HashMap<PathBuf, BuildEdge> targets
</code_context>

<issue_to_address>
Mermaid code block lines exceed 120 columns and should be wrapped accordingly.

The lines in the added Mermaid diagram code block are longer than 120 columns, which violates the wrapping guideline for code blocks. Please wrap these lines to a maximum of 120 columns.
</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 tests/features/ninja.feature
Comment thread tests/steps/ninja_steps.rs
Comment thread docs/netsuke-design.md
@leynos leynos merged commit fb6dda3 into main Jul 31, 2025
3 checks passed
@leynos leynos deleted the fcu4tw-codex/implement-ninja-file-synthesizer branch July 31, 2025 21:53
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