Conversation
Reviewer's GuideThis PR refactors the printing logic by extracting all printing helpers into a new Class diagram for the new printer moduleclassDiagram
class printer {
+write_comment_body(out, skin, comment)
+write_comment(out, skin, comment)
+write_thread(out, skin, thread)
+print_reviews(skin, reviews)
+write_review(out, skin, review)
}
class ReviewComment
class ReviewThread
class PullRequestReview
class MadSkin
printer --> ReviewComment
printer --> ReviewThread
printer --> PullRequestReview
printer --> MadSkin
Class diagram showing reviews module after refactorclassDiagram
class reviews {
+latest_reviews(reviews)
}
class printer {
+write_review(out, skin, review)
+print_reviews(skin, reviews)
}
reviews ..> printer : uses (for printing)
reviews --> PullRequestReview
Class diagram showing main.rs printing usage after refactorclassDiagram
class main {
}
class printer {
+write_comment_body(out, skin, comment)
+write_review(out, skin, review)
+write_thread(out, skin, thread)
}
main ..> printer : uses printing helpers
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
Warning Rate limit exceeded@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 15 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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. 📒 Files selected for processing (1)
Summary by CodeRabbit
No changes to the user interface or core features are visible. WalkthroughDelegate all review comment and thread printing logic from Changes
Sequence Diagram(s)sequenceDiagram
participant Main
participant Printer
participant Reviews
Main->>Reviews: Fetch review data
Main->>Printer: write_thread(thread) / print_reviews(reviews)
Printer-->>Main: Formatted output to terminal
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Possibly related PRs
Poem
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Hey @leynos - I've reviewed your changes and found some issues that need to be addressed.
- Propagate errors from
skin.write_text_oninstead of ignoring them so render failures aren’t silently dropped. - Consider extracting the repeated author‐banner formatting into a shared helper to DRY up
write_comment_bodyandwrite_review. - You might make
print_reviewsaccept aWriteimpl instead of locking stdout directly to increase flexibility and testability.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Propagate errors from `skin.write_text_on` instead of ignoring them so render failures aren’t silently dropped.
- Consider extracting the repeated author‐banner formatting into a shared helper to DRY up `write_comment_body` and `write_review`.
- You might make `print_reviews` accept a `Write` impl instead of locking stdout directly to increase flexibility and testability.
## Individual Comments
### Comment 1
<location> `src/printer/mod.rs:118` </location>
<code_context>
+/// print_reviews(&MadSkin::default(), &[review]);
+/// ```
+pub fn print_reviews(skin: &MadSkin, reviews: &[PullRequestReview]) {
+ for r in reviews {
+ if let Err(e) = write_review(std::io::stdout().lock(), skin, r) {
+ eprintln!("error printing review: {e}");
+ }
</code_context>
<issue_to_address>
Locking stdout for each review may impact performance.
Locking stdout once before the loop and reusing the handle would improve efficiency and prevent output interleaving in multithreaded scenarios.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
pub fn print_reviews(skin: &MadSkin, reviews: &[PullRequestReview]) {
for r in reviews {
if let Err(e) = write_review(std::io::stdout().lock(), skin, r) {
eprintln!("error printing review: {e}");
}
=======
pub fn print_reviews(skin: &MadSkin, reviews: &[PullRequestReview]) {
let stdout = std::io::stdout();
let mut handle = stdout.lock();
for r in reviews {
if let Err(e) = write_review(&mut handle, skin, r) {
eprintln!("error printing review: {e}");
}
>>>>>>> REPLACE
</suggested_fix>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🔭 Outside diff range comments (1)
src/main.rs (1)
1-1224: Decompose this file - it exceeds the 400-line limit.This file contains 1224 lines, violating the coding guideline that "Files must not exceed 400 lines in length". Extract meaningful components into separate modules to reduce complexity and improve maintainability.
Consider decomposing by:
- Moving diff formatting functions to a separate module
- Extracting reference parsing logic
- Moving data structures to a types module
- Separating GraphQL query logic
♻️ Duplicate comments (1)
src/printer/mod.rs (1)
132-141: Performance concern resolved.This function now accepts a writer parameter, allowing the caller to handle stdout locking once rather than locking for each review. This addresses the performance concern from previous reviews.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (3)
src/html.rs(1 hunks)src/main.rs(3 hunks)src/printer/mod.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 usereturnin single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Prefer immutable data and avoid unnecessarymutbindings.
Handle errors with theResulttype instead of panicking where feasible.
Prefer semantic error enums: Derivestd::error::Error(via thethiserrorcrate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Useeyre::Reportfor 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 toeyreonly in the mainmain()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 usingArcto reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Avoidunsafecode 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.
Preferexpectoverallow.
Prefer.expect()over.unwrap().
Useconcat!()to combine long string literals rather than escaping newlines with a backslash.
Files:
src/html.rssrc/main.rssrc/printer/mod.rs
⚙️ CodeRabbit Configuration File
**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.
Adhere to single responsibility and CQRS
Place function attributes after doc comments.
Do not use
returnin single-line functions.Move conditionals with >2 branches into a predicate function.
Avoid
unsafeunless 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
rstestfixtures for shared setup and to avoid repetition between tests.Replace duplicated tests with
#[rstest(...)]parameterised cases.Prefer
mockallfor 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/html.rssrc/main.rssrc/printer/mod.rs
🔇 Additional comments (11)
src/html.rs (1)
68-72: LGTM! Improved pattern matching syntax.The
matches!macro provides better readability for this pattern match with guard condition.src/main.rs (4)
11-11: LGTM! Good modularisation.Adding the printer module improves separation of concerns by extracting all printing logic.
15-16: LGTM! Imports updated correctly.The import changes properly reflect the module restructuring, delegating printing responsibilities to the printer module.
566-570: Excellent performance improvement with stdout locking.Locking stdout once and reusing the handle prevents output interleaving and improves efficiency compared to locking for each review.
767-768: LGTM! Test imports updated appropriately.The test imports correctly reference the new printer module functions.
src/printer/mod.rs (6)
1-5: Excellent module documentation.The module-level documentation clearly explains the purpose and benefits of separating printing logic for testability.
12-20: LGTM! Clean helper function.The
write_author_linefunction provides good abstraction for consistent author formatting across different contexts.
38-53: Well-documented and structured function.Good use of
collapse_detailsfor HTML preprocessing and appropriate error handling withanyhow::Result.
70-79: LGTM! Clear separation of concerns.The function properly delegates diff formatting to the existing
format_comment_difffunction and handles the comment body separately.
99-114: Excellent logic for diff deduplication.The implementation correctly shows the diff only once for the first comment whilst ensuring all subsequent comments and URLs are displayed.
156-172: LGTM! Consistent formatting approach.The review formatting follows the same pattern as comment formatting with proper HTML detail collapsing and markdown rendering.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
src/printer/mod.rs (2)
116-141: Address the performance concern raised in previous reviews.The current implementation locks stdout for each review, which impacts performance and may cause output interleaving in multithreaded scenarios.
The performance issue identified in the past review comment remains valid. Lock stdout once before the loop and reuse the handle.
174-268: Test coverage addresses most scenarios but could be expanded.The existing tests cover basic formatting, author handling, HTML detail collapsing, and error propagation. However, the previous review comment suggesting more comprehensive coverage for different review states and scenarios remains relevant.
Expand test coverage to include different review states, reviews with and without authors, HTML detail collapsing behaviour, and error handling scenarios as suggested in the previous review.
Additionally, add tests for the
write_commentandwrite_threadfunctions to ensure complete coverage of the module's public API:#[test] fn write_comment_includes_diff_and_body() { let comment = ReviewComment { diff_hunk: "@@ -1 +1 @@\n-old\n+new".into(), body: "Good change".into(), author: Some(User { login: "reviewer".into() }), url: "https://example.com/comment".into(), ..Default::default() }; let skin = MadSkin::default(); let mut buf = Vec::new(); write_comment(&mut buf, &skin, &comment).expect("write comment"); let out = String::from_utf8(buf).expect("utf8"); assert!(out.contains("@@")); assert!(out.contains("reviewer")); assert!(out.contains("Good change")); } #[test] fn write_thread_shows_diff_only_once() { let comments = vec![ ReviewComment { diff_hunk: "@@ -1 +1 @@\n-old\n+new".into(), body: "First comment".into(), url: "https://example.com/1".into(), ..Default::default() }, ReviewComment { diff_hunk: "@@ -1 +1 @@\n-old\n+new".into(), body: "Second comment".into(), url: "https://example.com/2".into(), ..Default::default() } ]; let thread = ReviewThread { comments: CommentConnection { nodes: comments, ..Default::default() }, ..Default::default() }; let skin = MadSkin::default(); let mut buf = Vec::new(); write_thread(&mut buf, &skin, &thread).expect("write thread"); let out = String::from_utf8(buf).expect("utf8"); // Diff should appear only once assert_eq!(out.matches("@@").count(), 1); assert!(out.contains("First comment")); assert!(out.contains("Second comment")); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (1)
src/printer/mod.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 usereturnin single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Prefer immutable data and avoid unnecessarymutbindings.
Handle errors with theResulttype instead of panicking where feasible.
Prefer semantic error enums: Derivestd::error::Error(via thethiserrorcrate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Useeyre::Reportfor 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 toeyreonly in the mainmain()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 usingArcto reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Avoidunsafecode 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.
Preferexpectoverallow.
Prefer.expect()over.unwrap().
Useconcat!()to combine long string literals rather than escaping newlines with a backslash.
Files:
src/printer/mod.rs
⚙️ CodeRabbit Configuration File
**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.
Adhere to single responsibility and CQRS
Place function attributes after doc comments.
Do not use
returnin single-line functions.Move conditionals with >2 branches into a predicate function.
Avoid
unsafeunless 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
rstestfixtures for shared setup and to avoid repetition between tests.Replace duplicated tests with
#[rstest(...)]parameterised cases.Prefer
mockallfor 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/printer/mod.rs
🔇 Additional comments (5)
src/printer/mod.rs (5)
1-10: Module documentation and imports look excellent.The module-level documentation clearly explains the purpose and separation of concerns. Import organisation follows standard Rust conventions with good use of the crate prefix for internal modules.
22-53: Function implementation follows best practices.The documentation is comprehensive with a practical example, parameter handling is correct, and error propagation using
anyhow::Resultis appropriate. The use ofcollapse_detailsfor preprocessing comment bodies is well-integrated.
55-79: Function correctly combines diff formatting with comment body output.The implementation properly delegates to
format_comment_diffandwrite_comment_body, maintaining separation of concerns. Error handling is consistent throughout.
81-114: Thread printing logic correctly handles the diff-once requirement.The implementation elegantly uses an iterator to print the first comment with its diff, then subsequent comments without the diff. URL printing after each comment provides good traceability.
143-172: Review formatting function is well-structured.The function correctly formats the review state as a suffix, handles optional authors appropriately, and applies HTML detail collapsing consistently with other functions.
Summary
printermodulereviewsmodule to fetching helpers onlyTesting
make fmtmake lintmake testhttps://chatgpt.com/codex/tasks/task_e_688be428f84c8322986c38c04790b8b4
Summary by Sourcery
Extract printing logic into a dedicated
printermodule, relocate all comment/thread/review printing functions there, remove them frommain.rsandreviews.rs, and update imports and tests to use the new module.Enhancements:
printermodule to house functions for formatting and printing review comments, review threads, and reviews with termimad syntax highlighting.Chores:
main.rsandreviews.rsto restrict the reviews module to fetching logic.printermodule.