Skip to content

Refactor main module into smaller components#59

Merged
leynos merged 4 commits intomainfrom
codex/refactor-src/main.rs-to-reduce-line-count
Aug 9, 2025
Merged

Refactor main module into smaller components#59
leynos merged 4 commits intomainfrom
codex/refactor-src/main.rs-to-reduce-line-count

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 7, 2025

Summary

  • extract review thread fetching into dedicated module
  • move summary generation and banner printing into reusable helpers
  • isolate configuration loading logic and test utilities

Testing

  • make fmt
  • make lint
  • make test

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

Summary by Sourcery

Modularize the main module by extracting core functionalities into dedicated components

Enhancements:

  • Split main.rs functionality into new modules: review_threads for GraphQL review thread fetching, summary for review summary generation, issues for issue retrieval, config for configuration loading with reference fallback, and test_utils for shared test helpers

Tests:

  • Update existing tests to use the centralized test_utils module for environment variable management

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 7, 2025

Reviewer's Guide

This PR refactors the monolithic main.rs by extracting distinct functionalities—review thread fetching, summary generation, issue retrieval, configuration loading, and test utilities—into dedicated modules, reducing code duplication and improving maintainability.

Class diagram for extracted review thread types and functions

classDiagram
    class ReviewThread {
        +String id
        +bool is_resolved
        +CommentConnection comments
    }
    class CommentConnection {
        +Vec~ReviewComment~ nodes
        +PageInfo page_info
    }
    class ReviewComment {
        +String body
        +String diff_hunk
        +Option<i32> original_position
        +Option<i32> position
        +String path
        +String url
        +Option<User> author
    }
    class PageInfo {
        +bool has_next_page
        +Option<String> end_cursor
    }
    class User {
        +String login
    }
    ReviewThread --> CommentConnection : comments
    CommentConnection --> ReviewComment : nodes
    ReviewComment --> User : author
    ReviewThread --> PageInfo : page_info
    CommentConnection --> PageInfo : page_info

    class review_threads {
        +fetch_review_threads(client, repo, number)
    }
Loading

Class diagram for summary module utilities

classDiagram
    class summary {
        +summarize_files(threads: &[ReviewThread]) Vec<(String, usize)>
        +write_summary<W: Write>(out: W, summary: &[(String, usize)])
        +print_summary(summary: &[(String, usize)])
        +print_end_banner()
    }
Loading

Class diagram for issues module

classDiagram
    class Issue {
        +String title
        +String body
    }
    class issues {
        +fetch_issue(client, repo, number) Issue
    }
Loading

Class diagram for configuration loading helper

classDiagram
    class config {
        +load_with_reference_fallback<T>(cli_args: T) Result<T, OrthoError>
    }
Loading

Class diagram for test utilities module

classDiagram
    class test_utils {
        +set_var(key, value)
        +remove_var(key)
    }
Loading

File-Level Changes

Change Details Files
Modularize review thread and issue fetching logic
  • Extract GraphQL response types and fetch functions for review threads from main.rs into src/review_threads.rs
  • Extract issue fetching function and related types from main.rs into src/issues.rs
  • Update main.rs and callers to import and use the new modules
src/review_threads.rs
src/issues.rs
src/main.rs
Extract summary generation and banner printing into a helper module
  • Move summarize_files, write_summary, print_summary, and print_end_banner functions from main.rs to src/summary.rs
  • Adjust main.rs to call print_summary and print_end_banner from the summary module
src/summary.rs
src/main.rs
Isolate configuration loading with reference fallback
  • Relocate missing_reference helper and load_with_reference_fallback function into src/config.rs
  • Remove inline config fallback code from main.rs and update imports
src/config.rs
src/main.rs
Centralize test environment utilities
  • Extract set_var and remove_var functions into src/test_utils.rs
  • Replace duplicated test helpers in main.rs tests with imports from test_utils
src/test_utils.rs
src/main.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
Copy Markdown

coderabbitai Bot commented Aug 7, 2025

Note

Other AI code review bot(s) detected

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

Summary by CodeRabbit

  • New Features
    • Added support for loading configurations with improved handling of missing reference fields.
    • Introduced the ability to fetch GitHub issues and pull request review threads, including detailed comment retrieval.
    • Implemented summary generation and printing for review comments grouped by file path.
  • Refactor
    • Modularised application logic by extracting configuration, issue fetching, review thread handling, and summary generation into separate modules, resulting in a cleaner main file.
  • Chores
    • Added utilities for safely manipulating environment variables during tests.

Walkthrough

Modularise the codebase by extracting configuration loading, GitHub issue fetching, review thread retrieval, summary generation, and test utilities into dedicated modules. Remove local definitions from main.rs and re-export necessary functions and types from the new modules. Update imports and relocate related tests and helpers accordingly.

Changes

Cohort / File(s) Change Summary
Configuration Module
src/config.rs
Add a module for configuration loading helpers, including a public function to load configuration with a fallback for missing reference fields.
GitHub Issues Module
src/issues.rs
Add a module to fetch GitHub issues via GraphQL, define public Issue struct, and expose an async function to retrieve issues by number.
Review Threads Module
src/review_threads.rs
Add a module to fetch unresolved PR review threads and comments from GitHub GraphQL, define data structures mirroring API responses, and implement pagination logic.
Summary Utilities
src/summary.rs
Add a module for summarising review comments by file, formatting summaries, and printing end banners, with comprehensive tests for summarisation logic.
Test Utilities
src/test_utils.rs
Add a module with utilities for manipulating environment variables in tests, including safe wrappers for setting and removing variables.
Main File Refactor
src/main.rs
Remove local API/data structure definitions and test helpers, re-export functions/types from new modules, update imports, and relocate or remove related tests.

Sequence Diagram(s)

sequenceDiagram
    participant CLI
    participant Config
    participant Issues
    participant ReviewThreads
    participant Summary

    CLI->>Config: load_with_reference_fallback(args)
    Config-->>CLI: Result<Config>
    CLI->>Issues: fetch_issue(client, repo, number)
    Issues-->>CLI: Issue
    CLI->>ReviewThreads: fetch_review_threads(client, repo, pr_number)
    ReviewThreads-->>CLI: Vec<ReviewThread>
    CLI->>Summary: summarize_files(threads)
    Summary-->>CLI: Vec<(file, count)>
    CLI->>Summary: print_summary(summary)
    Summary-->>CLI: (prints to stdout)
    CLI->>Summary: print_end_banner()
    Summary-->>CLI: (prints to stdout)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

  • Refine subcommand merging ortho-config#78: Refines the underlying ortho_config crate’s subcommand merging logic, enabling CLI-only required values and deprecating older helpers; directly relates to the new configuration module’s fallback handling.

Poem

Modules now stand, proud and tall,
Each with a duty, answering the call.
Issues and threads, fetched with care,
Summaries written, logic laid bare.
Config loads softly, tests set the scene—
Refactored and tidy, the code is pristine!
🦀✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/refactor-src/main.rs-to-reduce-line-count

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

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

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

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

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

### Comment 1
<location> `src/review_threads.rs:151` </location>
<code_context>
-    repo: &RepoInfo,
-    number: u64,
-) -> Result<Vec<ReviewThread>, VkError> {
-    let mut threads = paginate(|cursor| fetch_thread_page(client, repo, number, cursor)).await?;
-    threads.retain(|t| !t.is_resolved);
-
</code_context>

<issue_to_address>
Potential performance issue: all threads are fetched before filtering unresolved ones.

If possible, apply the unresolved filter in the GraphQL query to minimize data transfer and improve efficiency.

Suggested implementation:

```rust
    let mut threads = paginate(|cursor| fetch_thread_page(client, repo, number, cursor, Some(false))).await?;

```

section.

Here are the code changes:

<file_operations>
<file_operation operation="edit" file_path="src/review_threads.rs">
<<<<<<< SEARCH
    let mut threads = paginate(|cursor| fetch_thread_page(client, repo, number, cursor)).await?;
    threads.retain(|t| !t.is_resolved);
=======
    let mut threads = paginate(|cursor| fetch_thread_page(client, repo, number, cursor, Some(false))).await?;
>>>>>>> REPLACE
</file_operation>
</file_operations>

<additional_changes>
1. Update the signature of `fetch_thread_page` to accept an additional parameter, e.g., `only_unresolved: Option<bool>`.
2. Update the GraphQL query in `fetch_thread_page` (and possibly in `THREADS_QUERY`) to include a filter for unresolved threads, if supported by the GitHub API. For example, add a `isResolved: false` argument if available.
3. Pass the `only_unresolved` parameter through to the query construction.
4. Remove the `.retain(|t| !t.is_resolved);` line entirely, as shown above.
5. If the GitHub API does not support server-side filtering, document this and revert to client-side filtering.
</issue_to_address>

### Comment 2
<location> `src/review_threads.rs:13` </location>
<code_context>
-    body: String,
-}
-
-#[derive(Debug, Deserialize, Default)]
-struct ReviewThreadConnection {
-    nodes: Vec<ReviewThread>,
</code_context>

<issue_to_address>
Consider replacing the multiple connection and wrapper structs with a single generic Connection<T> and NodeWrapper<T> to reduce boilerplate.

Here’s one way to collapse much of that boilerplate without losing any functionality:

1. Introduce a single, generic `Connection<T>` and a tiny `NodeWrapper<T>`:

```rust
#[derive(Debug, Deserialize)]
struct Connection<T> {
    nodes: Vec<T>,
    #[serde(rename = "pageInfo")]
    page_info: PageInfo,
}

#[derive(Debug, Deserialize)]
struct NodeWrapper<T> {
    node: Option<T>,
}
```

2. Alias your two current connection types to that:

```rust
type ReviewThreadConnection = Connection<ReviewThread>;
type CommentConnection      = Connection<ReviewComment>;
```

3. Kill `CommentNode`/`CommentNodeWrapper` entirely and simplify your two fetch functions:

```rust
async fn fetch_comment_page(
    client: &GraphQLClient,
    id: &str,
    cursor: Option<String>,
) -> Result<(Vec<ReviewComment>, PageInfo), VkError> {
    // Use our generic NodeWrapper + Connection
    let NodeWrapper { node } = client
        .run_query(COMMENT_QUERY, json!({ "id": id, "cursor": cursor }))
        .await?;
    let Connection { nodes, page_info } = node
        .ok_or_else(|| VkError::BadResponse(format!("Missing comment node id={id}")))?;
    Ok((nodes, page_info))
}

async fn fetch_thread_page(
    client: &GraphQLClient,
    repo: &RepoInfo,
    number: u64,
    cursor: Option<String>,
) -> Result<(Vec<ReviewThread>, PageInfo), VkError> {
    #[derive(Deserialize)]
    struct PullRequestData {
        #[serde(rename = "reviewThreads")]
        review_threads: ReviewThreadConnection,
    }
    #[derive(Deserialize)]
    struct RepoData {
        #[serde(rename = "pullRequest")]
        pull_request: PullRequestData,
    }
    #[derive(Deserialize)]
    struct ThreadData {
        repository: RepoData,
    }

    let ThreadData { repository } = client
        .run_query(
            THREADS_QUERY,
            json!({
                "owner": repo.owner,
                "name":  repo.name,
                "number": number,
                "cursor": cursor,
            }),
        )
        .await?;
    let Connection { nodes, page_info } = repository
        .pull_request
        .review_threads;
    Ok((nodes, page_info))
}
```

4. Your `ReviewThread` stays the same but now reuses `CommentConnection`:

```rust
#[derive(Debug, Deserialize)]
pub struct ReviewThread {
    pub id: String,
    #[serde(rename = "isResolved")]
    pub is_resolved: bool,
    pub comments: CommentConnection,
}
```

By doing this you:

- Remove 4–5 tiny wrapper structs.
- Collapse two connection types into one generic.
- Keep pagination/merge logic exactly as-is.
- Retain full serde support (and error paths).
</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/review_threads.rs
Comment thread src/review_threads.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 7, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 7, 2025

✅ Actions performed

Review triggered.

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

Copy link
Copy Markdown

@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)
src/review_threads.rs (2)

151-152: Performance: Apply unresolved filter in GraphQL query

Fetching all threads before filtering wastes bandwidth and processing time.


13-38: Reduce boilerplate with generic Connection pattern

The multiple wrapper structs create unnecessary complexity.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b56fad and 718decc.

📒 Files selected for processing (6)
  • src/config.rs (1 hunks)
  • src/issues.rs (1 hunks)
  • src/main.rs (3 hunks)
  • src/review_threads.rs (1 hunks)
  • src/summary.rs (1 hunks)
  • src/test_utils.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.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/test_utils.rs
  • src/review_threads.rs
  • src/config.rs
  • src/issues.rs
  • src/summary.rs
  • src/main.rs
🧬 Code Graph Analysis (2)
src/config.rs (1)
src/main.rs (2)
  • load_with_reference_fallback (202-202)
  • load_with_reference_fallback (206-206)
src/main.rs (8)
src/api/mod.rs (1)
  • paginate (238-254)
src/config.rs (1)
  • load_with_reference_fallback (26-41)
src/issues.rs (1)
  • fetch_issue (34-50)
src/review_threads.rs (1)
  • fetch_review_threads (146-179)
src/summary.rs (4)
  • print_end_banner (79-81)
  • print_summary (74-76)
  • summarize_files (26-34)
  • write_summary (57-71)
src/printer/mod.rs (2)
  • print_reviews (136-145)
  • write_thread (103-118)
src/ref_parser.rs (2)
  • parse_issue_reference (120-125)
  • parse_pr_reference (131-136)
src/test_utils.rs (2)
  • remove_var (17-19)
  • set_var (8-10)
🔇 Additional comments (3)
src/issues.rs (1)

1-51: Well-structured module with clear separation of concerns

The module properly encapsulates GitHub issue fetching with appropriate internal/public visibility and comprehensive documentation.

src/main.rs (2)

110-112: Fix grammar in documentation

Correct the verb form for consistency.

-/// This attempts to initialise the client with the provided `transcript`.
+/// This attempts to initialise the client with the provided `transcript`.

Wait, actually the text is already using "initialise" which is correct British English. The documentation is fine as is.


24-30: Restrict internal-only re-exports or confirm public API

All re-exported items under src/main.rs:24-30 are only consumed by internal modules (src/printer/mod.rs and src/diff.rs) and no external usage was detected. If these aren’t part of your public API, narrow their visibility to the crate:

--- a/src/main.rs
+++ b/src/main.rs
@@ lines 24-30
-pub use crate::api::{GraphQLClient, paginate};
-pub use config::load_with_reference_fallback;
-pub use issues::{Issue, fetch_issue};
-pub use review_threads::{
-    CommentConnection, PageInfo, ReviewComment, ReviewThread, User, fetch_review_threads,
-};
-pub use summary::{print_end_banner, print_summary, summarize_files, write_summary};
+pub(crate) use crate::api::{GraphQLClient, paginate};
+pub(crate) use config::load_with_reference_fallback;
+pub(crate) use issues::{Issue, fetch_issue};
+pub(crate) use review_threads::{
+    CommentConnection, PageInfo, ReviewComment, ReviewThread, User, fetch_review_threads,
+};
+pub(crate) use summary::{print_end_banner, print_summary, summarize_files, write_summary};

Confirm whether any external consumers rely on these re-exports before changing visibility.

Comment thread src/config.rs
Comment thread src/main.rs Outdated
Comment thread src/review_threads.rs Outdated
Comment thread src/review_threads.rs Outdated
Comment thread src/summary.rs
Comment thread src/test_utils.rs
Copy link
Copy Markdown

@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: 2

♻️ Duplicate comments (4)
src/test_utils.rs (2)

6-7: Enforce serial execution at call-site

The docs warn that callers “must ensure tests … run serially”, yet the module provides no compile-time or runtime guard. Export a wrapper macro/attribute or integrate the serial_test crate here to guarantee single-threaded execution and prevent race conditions.


18-29: Drop unnecessary unsafe and rely on safe stdlib calls

std::env::{set_var, remove_var} are already safe. Wrapping them in an unsafe block merely advertises undefined behaviour without gaining anything. Eliminate the unsafe blocks and the accompanying (now misleading) safety comments.

 pub fn set_var<K: AsRef<std::ffi::OsStr>, V: AsRef<std::ffi::OsStr>>(key: K, value: V) {
-    // SAFETY: Tests using this helper run serially.
-    unsafe { std::env::set_var(key, value) };
+    std::env::set_var(key, value);
 }
 …
 pub fn remove_var<K: AsRef<std::ffi::OsStr>>(key: K) {
-    // SAFETY: Tests using this helper run serially.
-    unsafe { std::env::remove_var(key) };
+    std::env::remove_var(key);
 }
src/config.rs (1)

10-13: Remove redundant clone in missing_reference

Cloning FigmentError is wasteful. Iterate over a borrowed view instead:

-    // FigmentError implements IntoIterator only for owned values, so clone.
-    err.clone()
-        .into_iter()
+    err.iter()                 // or &*err if only IntoIterator is impl’d for &FigmentError

This avoids copying potentially large error structures.

src/review_threads.rs (1)

140-143: Push unresolved-only filter into the GraphQL query

GitHub’s API can filter review threads via isResolved: false. Apply the filter in THREADS_QUERY and drop the retain call to slash bandwidth and latency.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 718decc and b1677c4.

📒 Files selected for processing (5)
  • src/config.rs (1 hunks)
  • src/main.rs (3 hunks)
  • src/review_threads.rs (1 hunks)
  • src/summary.rs (1 hunks)
  • src/test_utils.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: 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.
Use predicate functions for conditional criteria with more than two branches.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
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.
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.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
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.

Files:

  • src/test_utils.rs
  • src/config.rs
  • src/summary.rs
  • src/review_threads.rs
  • src/main.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/test_utils.rs
  • src/config.rs
  • src/summary.rs
  • src/review_threads.rs
  • src/main.rs
🧬 Code Graph Analysis (3)
src/config.rs (1)
src/main.rs (2)
  • load_with_reference_fallback (206-206)
  • load_with_reference_fallback (210-210)
src/review_threads.rs (1)
src/api/mod.rs (3)
  • paginate (238-254)
  • new (90-97)
  • with_endpoint (107-125)
src/main.rs (8)
src/api/mod.rs (1)
  • paginate (238-254)
src/config.rs (1)
  • load_with_reference_fallback (27-42)
src/issues.rs (1)
  • fetch_issue (34-50)
src/review_threads.rs (1)
  • fetch_review_threads (135-169)
src/summary.rs (4)
  • print_end_banner (81-83)
  • print_summary (74-78)
  • summarize_files (26-34)
  • write_summary (57-71)
src/printer/mod.rs (2)
  • print_reviews (136-145)
  • write_thread (103-118)
src/ref_parser.rs (2)
  • parse_issue_reference (120-125)
  • parse_pr_reference (131-136)
src/test_utils.rs (2)
  • remove_var (26-29)
  • set_var (18-21)
🔍 MCP Research (1 server)

Context7:

  • Issue leynos/ortho-config#78 is related to the PR's new src/config.rs module. It refines the underlying ortho_config crate's subcommand merging logic to allow CLI-only required values and deprecates older helpers. This directly supports the PR's approach of wrapping ortho_config's load_and_merge_subcommand_for function to handle missing reference fields gracefully by falling back to CLI arguments without error. This indicates that the PR depends on and complements improvements made in the ortho_config crate for configuration loading robustness. (related_prs)

  • The PR modularizes the main module by extracting core functionalities into dedicated components, including:

    • src/config.rs for configuration loading with reference fallback.
    • src/issues.rs for GitHub issue fetching via GraphQL.
    • src/review_threads.rs for fetching unresolved pull request review threads and comments.
    • src/summary.rs for generating and printing summaries of review comments.
    • src/test_utils.rs for environment variable manipulation utilities in tests.
      This modularization improves code organization and maintainability by separating concerns into focused modules. (pr_summary)
  • The src/config.rs module introduces a public function load_with_reference_fallback that attempts to load and merge configuration for CLI argument structs implementing OrthoConfig and related traits. If the loading fails due to a missing reference field, it returns the original CLI arguments without error, providing a fallback mechanism. For other errors, it returns the error as-is. This function is annotated to suppress Clippy warnings about large error types due to verbose configuration errors. (pr_summary)

  • The main module src/main.rs is refactored to remove local definitions and functions related to configuration loading, issue fetching, review thread fetching, and summary printing. Instead, it re-exports these functionalities from the new dedicated modules, reflecting the modularization effort. (pr_summary)

Comment thread src/main.rs
Comment thread src/summary.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 9, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 9, 2025

✅ Actions performed

Review triggered.

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

Copy link
Copy Markdown

@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 b1677c4 and 5295e31.

📒 Files selected for processing (4)
  • src/config.rs (1 hunks)
  • src/main.rs (3 hunks)
  • src/summary.rs (1 hunks)
  • src/test_utils.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: 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.
Use predicate functions for conditional criteria with more than two branches.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
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.
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.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
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.

Files:

  • src/test_utils.rs
  • src/summary.rs
  • src/config.rs
  • src/main.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/test_utils.rs
  • src/summary.rs
  • src/config.rs
  • src/main.rs
🧬 Code Graph Analysis (1)
src/config.rs (1)
src/main.rs (2)
  • load_with_reference_fallback (206-206)
  • load_with_reference_fallback (210-210)
🔇 Additional comments (3)
src/config.rs (1)

1-42: Configuration helper looks sound

Logic correctly falls back when only reference is missing, documentation and #[expect] annotation follow guidelines.

src/summary.rs (1)

1-88: Summary utilities meet requirements

Counting, ordering, I/O handling, and tests align with previous feedback.

src/main.rs (1)

231-232: Confirm dev-dependency presence. serial_test appears under [dev-dependencies] in Cargo.toml at version "3.2.0". No further changes required.

Comment thread src/test_utils.rs
@leynos leynos merged commit 05a80af into main Aug 9, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant