Skip to content

Explain PATH mutability hazards in tests#104

Merged
leynos merged 7 commits intomainfrom
codex/expand-comments-in-ninja-fixtures-and-refactor
Aug 12, 2025
Merged

Explain PATH mutability hazards in tests#104
leynos merged 7 commits intomainfrom
codex/expand-comments-in-ninja-fixtures-and-refactor

Conversation

@leynos
Copy link
Owner

@leynos leynos commented Aug 12, 2025

Summary

  • document Rust 2024 set_var unsafety in PATH fixtures
  • inject Env into PATH helper and fixtures
  • test PATH guard behaviour with mock environment

Testing

  • make fmt
  • make lint
  • make test

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

Summary by Sourcery

Refactor test fixtures to use a new Env-based helper for scoped PATH mutations, document the unsafety of std::env::set_var under Rust 2024, and add tests to validate PathGuard behavior.

Enhancements:

  • Extract common PATH manipulation into prepend_dir_to_path helper that uses Env and EnvLock
  • Refactor ninja_in_path and ninja_with_exit_code fixtures to invoke prepend_dir_to_path instead of manual set_var logic
  • Add allow dead_code annotations for support functions to clarify their use in various test contexts

Documentation:

  • Explain in comments that std::env::set_var is unsafe in Rust 2024 and describe how EnvLock and PathGuard confine the mutation

Tests:

  • Introduce env_path_tests to verify that prepend_dir_to_path correctly sets the first PATH entry and restores the original value on guard drop

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Aug 12, 2025

Reviewer's Guide

Replace ad-hoc PATH fixture code with a reusable Env-based prepend_dir_to_path helper that scopes unsafe std::env::set_var under EnvLock and PathGuard, document the mutability hazards in Rust 2024, and add dedicated tests to verify guard behavior.

File-Level Changes

Change Details Files
Refactor PATH manipulation to use Env abstraction
  • Introduce prepend_dir_to_path helper with EnvLock and PathGuard
  • Inject DefaultEnv into ninja fixtures instead of manual std::env::set_var
  • Remove manual path assembly and unsafe set_var calls
tests/runner_tests.rs
tests/support/env.rs
Document Rust 2024 unsafety of std::env::set_var in fixtures
  • Add comments explaining unsafe mutability hazards and EnvLock usage
  • Annotate helper and fixtures with allow(dead_code) and update fixture docs
tests/runner_tests.rs
tests/support/env.rs
Add unit tests for PATH guard behavior
  • Create env_path_tests.rs verifying prepend_dir_to_path sets and restores PATH using mocked Env
  • Use rstest and serial_test to isolate mutable global state
tests/env_path_tests.rs

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
Contributor

coderabbitai bot commented Aug 12, 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.

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 54 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 71ddea4 and fde9d5f.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • Cargo.toml (1 hunks)
  • tests/env_path_tests.rs (1 hunks)
  • tests/path_guard_tests.rs (1 hunks)
  • tests/runner_tests.rs (1 hunks)
  • tests/steps/process_steps.rs (1 hunks)
  • tests/support/env.rs (3 hunks)
  • tests/support/path_guard.rs (1 hunks)

Summary by CodeRabbit

  • New Features

    • None.
  • Bug Fixes

    • Improved PATH handling during test runs to avoid trailing separators and correctly restore or remove PATH when absent.
  • Tests

    • Added comprehensive tests for PATH manipulation, including empty and missing scenarios.
    • Introduced a safe helper to prepend directories to PATH with automatic restoration.
    • Updated fixtures to use the new approach, improving determinism.
  • Documentation

    • Expanded notes in tests clarifying the safe PATH mutation approach.
  • Chores

    • Suppressed unused-code warnings in test utilities.

Walkthrough

Add a test helper to prepend a directory to PATH under EnvLock with RAII restoration, refactor tests to use that helper and SystemEnv, add serial tests covering normal/empty/missing PATH cases, and adjust PathGuard to represent and restore an unset PATH. Suppress dead-code lint on an existing test helper.

Changes

Cohort / File(s) Summary
New tests
tests/env_path_tests.rs
Add serial tests that use mockable::DefaultEnv and prepend_dir_to_path to verify PATH is prepended and restored across normal, empty and missing PATH scenarios.
Test runner updates
tests/runner_tests.rs
Replace manual PATH mutation and EnvLock usage with SystemEnv alias and prepend_dir_to_path; update fixtures (ninja_in_path, ninja_with_exit_code) and imports/comments.
Test support: Env helper
tests/support/env.rs
Add pub fn prepend_dir_to_path(env: &impl Env, dir: &Path) -> PathGuard that reads PATH via Env, sets PATH under EnvLock using unsafe set_var, and returns a PathGuard to restore original state; add imports and minor lint attribute on write_manifest.
Test support: Path guard changes
tests/support/path_guard.rs
Introduce enum OriginalPath { Unset, Set(OsString) }; change PathGuard::new to accept Option<OsString> and store OriginalPath; update Drop to restore or remove PATH accordingly.
Test support: misc lint
tests/support/mod.rs
Add #[allow(dead_code, reason = "used in other test crates")] to pub fn fake_ninja to suppress dead-code warnings.
Step updates to handle missing PATH
tests/steps/process_steps.rs
Change PATH handling from unwrap_or_default() to Option-aware logic to avoid trailing colon when PATH is absent and to preserve absent-state restoration.

Sequence Diagram(s)

sequenceDiagram
  participant Test as Test Code
  participant Env as Env (SystemEnv / Mock)
  participant Lock as EnvLock
  participant Guard as PathGuard

  Note over Test,Env: Request to prepend dir to PATH
  Test->>Env: read PATH (Option<String>)
  Test->>Lock: acquire
  Lock->>Env: unsafe set_var(PATH = dir + (if PATH Some then ":" + PATH else "" ))
  Lock-->>Test: release
  Env-->>Guard: return PathGuard(original = Some(Set(path)) | Some(Unset))
  Note over Guard: On drop, match original -> restore or remove PATH under EnvLock
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related issues

Possibly related PRs

Poem

Prepend the path, lock the gate,
Tempdir marches to the front of fate.
Guard in hand, the tests proceed,
Drop it clean — old PATH recede.
Tiny ninja, temp and neat, 🥷✨

✨ 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/expand-comments-in-ninja-fixtures-and-refactor

🪧 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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

4 files reviewed, 1 comment

Edit Code Review Bot Settings | Greptile

#[serial]
fn prepend_dir_to_path_sets_and_restores() {
let env = mocked_path_env();
let original = env.raw("PATH").expect("PATH missing in mock");
Copy link

Choose a reason for hiding this comment

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

style: Consider using .expect("PATH should be set in mock") for more descriptive error message

Copy link
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:

  • Consider using env.set_var(...) in prepend_dir_to_path instead of std::env::set_var so the helper fully respects the Env trait and works correctly with mocked environments.
  • Rename DefaultEnv to something like SystemEnv or RealEnv to more clearly indicate it interacts with the real process environment.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider using `env.set_var(...)` in `prepend_dir_to_path` instead of `std::env::set_var` so the helper fully respects the `Env` trait and works correctly with mocked environments.
- Rename `DefaultEnv` to something like `SystemEnv` or `RealEnv` to more clearly indicate it interacts with the real process environment.

## Individual Comments

### Comment 1
<location> `tests/support/env.rs:54` </location>
<code_context>
+/// globals. `EnvLock` serialises access and `PathGuard` rolls back the change,
+/// keeping the unsafety scoped to a single test.
+#[allow(dead_code, reason = "used in runner tests")]
+pub fn prepend_dir_to_path(env: &impl Env, dir: &Path) -> PathGuard {
+    let original = env.raw("PATH").unwrap_or_default();
+    let original_os: OsString = original.clone().into();
+    let mut paths: Vec<_> = std::env::split_paths(&original_os).collect();
+    paths.insert(0, dir.to_path_buf());
+    let new_path = std::env::join_paths(paths).expect("join paths");
+    let _lock = EnvLock::acquire();
+    // SAFETY: protected by `EnvLock` and reverted by the returned `PathGuard`.
+    unsafe { std::env::set_var("PATH", &new_path) };
+    PathGuard::new(original_os)
+}
</code_context>

<issue_to_address>
Consider adding a test for prepend_dir_to_path with an empty PATH variable.

Testing with an empty or unset PATH will ensure prepend_dir_to_path handles these cases correctly.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
#[allow(dead_code, reason = "used in runner tests")]
pub fn prepend_dir_to_path(env: &impl Env, dir: &Path) -> PathGuard {
    let original = env.raw("PATH").unwrap_or_default();
    let original_os: OsString = original.clone().into();
    let mut paths: Vec<_> = std::env::split_paths(&original_os).collect();
    paths.insert(0, dir.to_path_buf());
    let new_path = std::env::join_paths(paths).expect("join paths");
    let _lock = EnvLock::acquire();
    // SAFETY: protected by `EnvLock` and reverted by the returned `PathGuard`.
    unsafe { std::env::set_var("PATH", &new_path) };
    PathGuard::new(original_os)
}
=======
#[allow(dead_code, reason = "used in runner tests")]
pub fn prepend_dir_to_path(env: &impl Env, dir: &Path) -> PathGuard {
    let original = env.raw("PATH").unwrap_or_default();
    let original_os: OsString = original.clone().into();
    let mut paths: Vec<_> = std::env::split_paths(&original_os).collect();
    paths.insert(0, dir.to_path_buf());
    let new_path = std::env::join_paths(paths).expect("join paths");
    let _lock = EnvLock::acquire();
    // SAFETY: protected by `EnvLock` and reverted by the returned `PathGuard`.
    unsafe { std::env::set_var("PATH", &new_path) };
    PathGuard::new(original_os)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use std::ffi::OsString;
    use std::path::PathBuf;

    struct TestEnv;

    impl Env for TestEnv {
        fn raw(&self, key: &str) -> Option<String> {
            env::var(key).ok()
        }
    }

    #[test]
    fn test_prepend_dir_to_path_with_empty_path() {
        let _lock = EnvLock::acquire();
        // Save original PATH
        let original_path = env::var_os("PATH");
        // Set PATH to empty
        env::remove_var("PATH");
        let test_dir = PathBuf::from("/test/dir");
        let env = TestEnv;
        let guard = prepend_dir_to_path(&env, &test_dir);

        let new_path = env::var_os("PATH").unwrap();
        let mut paths: Vec<_> = env::split_paths(&new_path).collect();
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0], test_dir);

        // Drop guard to restore original PATH
        drop(guard);

        let restored_path = env::var_os("PATH");
        assert_eq!(restored_path, original_path);
    }

    #[test]
    fn test_prepend_dir_to_path_with_unset_path() {
        let _lock = EnvLock::acquire();
        // Save original PATH
        let original_path = env::var_os("PATH");
        // Unset PATH
        env::remove_var("PATH");
        let test_dir = PathBuf::from("/another/test/dir");
        let env = TestEnv;
        let guard = prepend_dir_to_path(&env, &test_dir);

        let new_path = env::var_os("PATH").unwrap();
        let mut paths: Vec<_> = env::split_paths(&new_path).collect();
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0], test_dir);

        // Drop guard to restore original PATH
        drop(guard);

        let restored_path = env::var_os("PATH");
        assert_eq!(restored_path, original_path);
    }
}
>>>>>>> REPLACE

</suggested_fix>

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 on lines 53 to 64
#[allow(dead_code, reason = "used in runner tests")]
pub fn prepend_dir_to_path(env: &impl Env, dir: &Path) -> PathGuard {
let original = env.raw("PATH").unwrap_or_default();
let original_os: OsString = original.clone().into();
let mut paths: Vec<_> = std::env::split_paths(&original_os).collect();
paths.insert(0, dir.to_path_buf());
let new_path = std::env::join_paths(paths).expect("join paths");
let _lock = EnvLock::acquire();
// SAFETY: protected by `EnvLock` and reverted by the returned `PathGuard`.
unsafe { std::env::set_var("PATH", &new_path) };
PathGuard::new(original_os)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Consider adding a test for prepend_dir_to_path with an empty PATH variable.

Testing with an empty or unset PATH will ensure prepend_dir_to_path handles these cases correctly.

Suggested change
#[allow(dead_code, reason = "used in runner tests")]
pub fn prepend_dir_to_path(env: &impl Env, dir: &Path) -> PathGuard {
let original = env.raw("PATH").unwrap_or_default();
let original_os: OsString = original.clone().into();
let mut paths: Vec<_> = std::env::split_paths(&original_os).collect();
paths.insert(0, dir.to_path_buf());
let new_path = std::env::join_paths(paths).expect("join paths");
let _lock = EnvLock::acquire();
// SAFETY: protected by `EnvLock` and reverted by the returned `PathGuard`.
unsafe { std::env::set_var("PATH", &new_path) };
PathGuard::new(original_os)
}
#[allow(dead_code, reason = "used in runner tests")]
pub fn prepend_dir_to_path(env: &impl Env, dir: &Path) -> PathGuard {
let original = env.raw("PATH").unwrap_or_default();
let original_os: OsString = original.clone().into();
let mut paths: Vec<_> = std::env::split_paths(&original_os).collect();
paths.insert(0, dir.to_path_buf());
let new_path = std::env::join_paths(paths).expect("join paths");
let _lock = EnvLock::acquire();
// SAFETY: protected by `EnvLock` and reverted by the returned `PathGuard`.
unsafe { std::env::set_var("PATH", &new_path) };
PathGuard::new(original_os)
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
struct TestEnv;
impl Env for TestEnv {
fn raw(&self, key: &str) -> Option<String> {
env::var(key).ok()
}
}
#[test]
fn test_prepend_dir_to_path_with_empty_path() {
let _lock = EnvLock::acquire();
// Save original PATH
let original_path = env::var_os("PATH");
// Set PATH to empty
env::remove_var("PATH");
let test_dir = PathBuf::from("/test/dir");
let env = TestEnv;
let guard = prepend_dir_to_path(&env, &test_dir);
let new_path = env::var_os("PATH").unwrap();
let mut paths: Vec<_> = env::split_paths(&new_path).collect();
assert_eq!(paths.len(), 1);
assert_eq!(paths[0], test_dir);
// Drop guard to restore original PATH
drop(guard);
let restored_path = env::var_os("PATH");
assert_eq!(restored_path, original_path);
}
#[test]
fn test_prepend_dir_to_path_with_unset_path() {
let _lock = EnvLock::acquire();
// Save original PATH
let original_path = env::var_os("PATH");
// Unset PATH
env::remove_var("PATH");
let test_dir = PathBuf::from("/another/test/dir");
let env = TestEnv;
let guard = prepend_dir_to_path(&env, &test_dir);
let new_path = env::var_os("PATH").unwrap();
let mut paths: Vec<_> = env::split_paths(&new_path).collect();
assert_eq!(paths.len(), 1);
assert_eq!(paths[0], test_dir);
// Drop guard to restore original PATH
drop(guard);
let restored_path = env::var_os("PATH");
assert_eq!(restored_path, original_path);
}
}

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

2 files reviewed, 1 comment

Edit Code Review Bot Settings | Greptile

let original_os: OsString = original.clone().into();
let mut paths: Vec<_> = std::env::split_paths(&original_os).collect();
paths.insert(0, dir.to_path_buf());
let new_path = std::env::join_paths(paths).expect("join paths");
Copy link

Choose a reason for hiding this comment

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

style: Consider using .expect("Failed to join PATH entries") for more descriptive error message

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

212-245: Inconsistent safety approach in environment override test.

This test still uses raw unsafe blocks for set_var and remove_var without the EnvLock protection that other tests use. Refactor to use the same safe pattern or document why this test requires direct manipulation.

 #[test]
 #[serial]
 fn run_respects_env_override_for_ninja() {
     let (temp_dir, ninja_path) = support::fake_ninja(0);
-    let original = std::env::var_os(NINJA_ENV);
-    unsafe {
-        std::env::set_var(NINJA_ENV, &ninja_path);
-    }
+    let original = std::env::var_os(NINJA_ENV);
+    {
+        let _lock = support::env_lock::EnvLock::acquire();
+        unsafe {
+            std::env::set_var(NINJA_ENV, &ninja_path);
+        }
+    }

     // ... test logic ...

-    unsafe {
-        if let Some(val) = original {
-            std::env::set_var(NINJA_ENV, val);
-        } else {
-            std::env::remove_var(NINJA_ENV);
+    {
+        let _lock = support::env_lock::EnvLock::acquire();
+        unsafe {
+            if let Some(val) = original {
+                std::env::set_var(NINJA_ENV, val);
+            } else {
+                std::env::remove_var(NINJA_ENV);
+            }
         }
     }
♻️ Duplicate comments (1)
tests/env_path_tests.rs (1)

15-15: Descriptive error message already implemented.

The test already uses .expect("PATH should be set in mock") as suggested in the past review comment.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fed9793 and b8fbb4d.

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

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Use functions and composition. Avoid repetition by extracting reusable logic. Prefer generators or comprehensions, and declarative code to imperative repetition when readable.
Small, meaningful functions. Functions must be small, clear in purpose, single responsibility, and obey command/query segregation.
Name things precisely. Use clear, descriptive variable and function names. For booleans, prefer names with is, has, or should.
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.
Place function attributes after doc comments.
Do not use return in single-line functions.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer single line versions of functions where appropriate.
Clippy warnings MUST be disallowed.
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.
Keep file size manageable. No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents colocated with targets. Large blocks of test data should be moved to external data files.
Illustrate with clear examples. Function documentation must include clear examples demonstrating the usage and outcome of the function. Test documentation should omit examples where the example serves only to reiterate the test logic.
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.
...

Files:

  • tests/env_path_tests.rs
  • tests/runner_tests.rs
  • tests/support/mod.rs
  • tests/support/env.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.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • 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/env_path_tests.rs
  • tests/runner_tests.rs
  • tests/support/mod.rs
  • tests/support/env.rs
🧬 Code Graph Analysis (3)
tests/env_path_tests.rs (3)
tests/support/env.rs (2)
  • mocked_path_env (21-28)
  • prepend_dir_to_path (54-65)
tests/support/path_guard.rs (1)
  • drop (30-36)
tests/support/env_lock.rs (1)
  • acquire (19-21)
tests/runner_tests.rs (5)
tests/support/env.rs (1)
  • prepend_dir_to_path (54-65)
tests/support/check_ninja.rs (1)
  • fake_ninja_check_build_file (12-36)
tests/support/path_guard.rs (1)
  • new (22-26)
tests/support/mod.rs (1)
  • fake_ninja (21-34)
tests/steps/process_steps.rs (1)
  • fake_ninja (36-40)
tests/support/env.rs (3)
tests/env_path_tests.rs (1)
  • std (40-42)
tests/support/env_lock.rs (1)
  • acquire (19-21)
tests/support/path_guard.rs (1)
  • new (22-26)
🔍 MCP Research (1 server)

Context7:
Selected library ID: none

Reason: No relevant library matches found for the query. Please provide a repository or package identifier (for example "leynos/netsuke" or "/org/project") or a file/path from the repo so I can resolve and fetch documentation specific to those code changes.

⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-test
🔇 Additional comments (9)
tests/support/mod.rs (1)

20-20: LGTM! Correct lint suppression for cross-crate test usage.

The #[allow(dead_code)] attribute with a clear reason correctly addresses the lint warning for this function that's used by other test crates.

tests/support/env.rs (2)

6-13: LGTM! Clean imports and proper module structure.

The imports align with the new PATH manipulation functionality and the module organisation follows established patterns.


48-65: Excellent documentation of unsafe PATH mutation hazards.

The function correctly documents the Rust 2024 unsafe nature of std::env::set_var and provides a well-architected solution using EnvLock for serialisation and PathGuard for RAII restoration. The implementation properly handles the original PATH retrieval, prepending logic, and guard creation.

tests/runner_tests.rs (3)

1-1: LGTM! Clean integration of environment abstraction.

The SystemEnv alias and module imports properly integrate the new environment abstraction pattern for PATH manipulation.

Also applies to: 10-13


16-29: Excellent documentation of unsafe PATH mutation mitigation.

The fixture documentation clearly explains the Rust 2024 safety concerns and how EnvLock and PathGuard address them. The implementation correctly uses the new helper function.


31-44: LGTM! Consistent pattern for PATH fixture with exit code.

The fixture follows the same safe pattern as ninja_in_path and properly documents the approach. The parameterised exit code functionality is maintained whilst adopting the safer PATH manipulation.

tests/env_path_tests.rs (3)

1-9: LGTM! Proper test module setup and imports.

The imports correctly bring in the environment abstraction, test utilities, and serialisation support needed for PATH manipulation testing.


11-26: LGTM! Comprehensive test of PATH prepend and restore behaviour.

The test correctly verifies that prepend_dir_to_path places the directory first in PATH and that the PathGuard restores the original value when dropped. The use of mocked_path_env properly isolates the test.


28-53: Excellent edge case testing for empty PATH.

This test properly validates the behaviour when PATH is empty, correctly using EnvLock for safe manipulation and ensuring proper restoration. The filtering of empty path entries on lines 40-42 correctly handles the edge case where an empty PATH might introduce empty path components.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

4 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

♻️ Duplicate comments (2)
tests/support/env.rs (2)

33-46: Replace #[allow] with #[expect] on write_manifest.

Keep lint policy consistent.

Apply this diff:

-#[allow(dead_code, reason = "used in Cucumber tests")]
+#[expect(dead_code, reason = "used in Cucumber tests")]
 pub fn write_manifest(file: &mut impl Write) -> io::Result<()> {

53-68: Replace #[allow] with #[expect] on prepend_dir_to_path.

Apply the repo lint policy and keep the suppression tightly scoped.

Apply this diff:

-#[allow(dead_code, reason = "used in runner tests")]
+#[expect(dead_code, reason = "used in runner tests")]
 pub fn prepend_dir_to_path(env: &impl Env, dir: &Path) -> PathGuard {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b8fbb4d and 71ddea4.

📒 Files selected for processing (4)
  • tests/env_path_tests.rs (1 hunks)
  • tests/steps/process_steps.rs (1 hunks)
  • tests/support/env.rs (3 hunks)
  • tests/support/path_guard.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Use functions and composition. Avoid repetition by extracting reusable logic. Prefer generators or comprehensions, and declarative code to imperative repetition when readable.
Small, meaningful functions. Functions must be small, clear in purpose, single responsibility, and obey command/query segregation.
Name things precisely. Use clear, descriptive variable and function names. For booleans, prefer names with is, has, or should.
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.
Place function attributes after doc comments.
Do not use return in single-line functions.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer single line versions of functions where appropriate.
Clippy warnings MUST be disallowed.
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.
Keep file size manageable. No single code file may be longer than 400 lines. Long switch statements or dispatch tables should be broken up by feature and constituents colocated with targets. Large blocks of test data should be moved to external data files.
Illustrate with clear examples. Function documentation must include clear examples demonstrating the usage and outcome of the function. Test documentation should omit examples where the example serves only to reiterate the test logic.
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.
...

Files:

  • tests/steps/process_steps.rs
  • tests/env_path_tests.rs
  • tests/support/env.rs
  • tests/support/path_guard.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.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • 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
  • tests/env_path_tests.rs
  • tests/support/env.rs
  • tests/support/path_guard.rs
🧬 Code Graph Analysis (4)
tests/steps/process_steps.rs (1)
tests/support/path_guard.rs (1)
  • new (29-34)
tests/env_path_tests.rs (3)
tests/support/env.rs (2)
  • mocked_path_env (21-28)
  • prepend_dir_to_path (54-68)
tests/support/path_guard.rs (2)
  • drop (38-47)
  • new (29-34)
tests/support/env_lock.rs (1)
  • acquire (19-21)
tests/support/env.rs (3)
tests/env_path_tests.rs (1)
  • std (40-42)
tests/support/env_lock.rs (1)
  • acquire (19-21)
tests/support/path_guard.rs (1)
  • new (29-34)
tests/support/path_guard.rs (2)
tests/support/env_lock.rs (1)
  • acquire (19-21)
tests/env_path_tests.rs (1)
  • std (40-42)
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-test
🔇 Additional comments (5)
tests/support/path_guard.rs (1)

41-46: LGTM: Scoped restoration logic is correct and threadsafe under EnvLock.

Match on the captured state, serialise with EnvLock, and revert via set/remove is the right approach given Rust 2024’s unsafe on env mutation.

tests/support/env.rs (2)

21-28: Preserve “unset PATH” semantics in the mock.

Do not collapse an unset PATH to an empty string. Align the mock with real behaviour so callers can distinguish None (unset) from Some("") (set but empty). If mockable::MockEnv cannot express “unset”, return an error for raw("PATH") when it was unset at capture time and let call sites use .ok() to recover None.

I can draft a patch once you confirm the error type to return from MockEnv::raw for a missing key.


48-69: Good: Scoped, cross‑platform PATH mutation with EnvLock + RAII.

Read via Env, build with split/join_paths, serialise with EnvLock, and restore via PathGuard. This centralises the hazard and avoids platform separator bugs.

tests/env_path_tests.rs (2)

28-54: LGTM: Validate empty PATH handling and restoration.

Serialise with EnvLock, assert that only the new dir is in PATH, and verify restoration to an empty PATH after guard drop.


56-80: LGTM: Validate missing PATH handling and restoration.

Unset PATH, prepend safely, assert the single entry, and ensure PATH is removed again on drop.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

5 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

leynos added 2 commits August 12, 2025 22:43
Explain restoration behaviour in PathGuard::new and streamline path splitting in tests.
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

4 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

3 files reviewed, 1 comment

Edit Code Review Bot Settings | Greptile

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

1 file reviewed, no comments

Edit Code Review Bot Settings | Greptile

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

1 file reviewed, no comments

Edit Code Review Bot Settings | Greptile

@leynos leynos force-pushed the codex/expand-comments-in-ninja-fixtures-and-refactor branch from 9032e68 to fde9d5f Compare August 12, 2025 21:59
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

1 file reviewed, no comments

Edit Code Review Bot Settings | Greptile

@leynos leynos merged commit 9e5c209 into main Aug 12, 2025
4 checks passed
@leynos leynos deleted the codex/expand-comments-in-ninja-fixtures-and-refactor branch August 12, 2025 22:24
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

Comments