Skip to content

Refactor issue parsing and add GraphQL helper#18

Merged
leynos merged 4 commits intomainfrom
codex/refactor-parse_issue_reference-to-reduce-duplication
Jun 15, 2025
Merged

Refactor issue parsing and add GraphQL helper#18
leynos merged 4 commits intomainfrom
codex/refactor-parse_issue_reference-to-reduce-duplication

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jun 15, 2025

Summary

  • unify parsing logic for PRs and issues
  • add run_query helper for GraphQL requests
  • render issues with termimad
  • update tests and formatting

Testing

  • cargo clippy -- -D warnings
  • cargo test

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

Summary by Sourcery

Introduce a reusable GraphQL client, unify issue/PR parsing, and enhance output formatting

New Features:

  • Add GraphQLClient.run_query helper for executing typed GraphQL requests
  • Render issue titles and bodies using termimad for styled terminal output

Enhancements:

  • Consolidate PR and issue reference parsing into a single parse_reference function with a ResourceType enum
  • Refactor fetch_* functions to use GraphQLClient instead of manual reqwest calls and headers
  • Simplify parse_pr_reference and parse_issue_reference by delegating to the unified parser
  • Add GITHUB_GRAPHQL_URL constant and ResourceType enum to streamline API interactions

Tests:

  • Add tests for parse_pr_reference and parse_issue_reference covering both URL and numeric reference cases

Summary by CodeRabbit

  • Refactor
    • Streamlined GraphQL request handling for improved reliability and consistency.
    • Unified parsing logic for pull request and issue references, reducing duplication.
  • New Features
    • Enhanced issue display with improved markdown styling for better readability.
  • Tests
    • Added unit tests for pull request and issue number parsing with default repository support.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 15, 2025

Reviewer's Guide

This PR refactors GraphQL interactions by introducing a dedicated GraphQLClient with a generic run_query helper, consolidates pull request and issue reference parsing through a ResourceType-driven parse_reference routine, and enhances issue display with termimad-based markdown rendering.

Sequence Diagram for fetch_issue using GraphQLClient

sequenceDiagram
    participant Caller as "Caller (e.g., run_issue)"
    participant GQLClient as "GraphQLClient"
    participant GitHubAPI as "GitHub GraphQL API"

    Caller->>GQLClient: run_query(ISSUE_QUERY, variables)
    activate GQLClient
    GQLClient->>GitHubAPI: POST /graphql (query, variables)
    activate GitHubAPI
    GitHubAPI-->>GQLClient: JSON Response (IssueData)
    deactivate GitHubAPI
    GQLClient-->>Caller: Result<Issue, VkError>
    deactivate GQLClient
Loading

File-Level Changes

Change Details Files
Introduce GraphQLClient and run_query helper
  • Added GraphQLClient struct with new and with_endpoint constructors
  • Implemented run_query method to centralize GraphQL request handling and error processing
  • Replaced inline reqwest client usage in fetch_* functions with run_query calls
  • Extracted GITHUB_GRAPHQL_URL constant and removed redundant headers management
src/main.rs
Unify PR and issue reference parsing
  • Introduced ResourceType enum to distinguish between issues and pull requests
  • Refactored parse_reference into a generic function driven by ResourceType
  • Added parse_pr_reference and parse_issue_reference wrappers
  • Updated run_pr and run_issue to use the new parsing functions and removed old inline logic
src/main.rs
Enhance issue rendering with termimad
  • Integrated termimad MadSkin for markdown styling in terminal
  • Updated run_issue to print issue title in bold and render body via skin.print_text
  • Added spacing adjustments after rendering
src/main.rs
Update tests for parsing changes
  • Added unit tests for parse_pr_reference and parse_issue_reference with default repo context
  • Refactored existing tests to call the new parsing functions
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 Jun 15, 2025

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 1 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 3782010 and 15b990d.

📒 Files selected for processing (1)
  • src/main.rs (13 hunks)

Walkthrough

A generic asynchronous function was introduced to handle GraphQL requests and responses, consolidating repeated logic. Reference parsing for pull requests and issues was unified via a new generic function. Existing functions were refactored to use these abstractions. Output formatting and unit tests were improved, and a GitHub GraphQL endpoint constant was added.

Changes

File(s) Change Summary
src/main.rs Introduced run_query for unified GraphQL requests; refactored fetch functions to use it; consolidated PR/issue reference parsing via parse_reference and parse_pr_reference; improved markdown output for issues; added tests; added GraphQL endpoint constant.

Poem

In the warren of code, a new path was spun,
With queries now running, their logic as one.
Parsing made simple for issues and PRs,
Markdown now sparkles like twinkling stars.
Tests hop along, ensuring all’s right—
A rabbit’s delight in code, pure and bright! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

  • The fallback parsing logic for plain numeric inputs was removed from parse_reference, so passing just an issue/PR number now fails—reintroduce that branch or re-add it in parse_pr_reference/parse_issue_reference.
  • Consider parameterizing the GraphQL endpoint in run_query instead of hardcoding the URL to improve flexibility and testability.
  • To avoid cloning the entire header map on each request, either take headers by value or adjust run_query to borrow it without cloning.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The fallback parsing logic for plain numeric inputs was removed from `parse_reference`, so passing just an issue/PR number now fails—reintroduce that branch or re-add it in `parse_pr_reference`/`parse_issue_reference`.
- Consider parameterizing the GraphQL endpoint in `run_query` instead of hardcoding the URL to improve flexibility and testability.
- To avoid cloning the entire header map on each request, either take `headers` by value or adjust `run_query` to borrow it without cloning.

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.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 15, 2025

@sourcery-ai review

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

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

  • Consider replacing the raw &str resource_type parameter in parse_reference with a dedicated enum to catch typos at compile time and improve readability.
  • Since every run_query call uses the same GitHub endpoint and headers, you could wrap the client + headers into a small GraphQLClient struct that defaults to the GitHub URL to simplify invocation.
  • The #[allow(dead_code)] on the Unimplemented error variant can likely be removed once the refactor is complete or if that variant is no longer needed.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider replacing the raw &str resource_type parameter in parse_reference with a dedicated enum to catch typos at compile time and improve readability.
- Since every run_query call uses the same GitHub endpoint and headers, you could wrap the client + headers into a small GraphQLClient struct that defaults to the GitHub URL to simplify invocation.
- The #[allow(dead_code)] on the Unimplemented error variant can likely be removed once the refactor is complete or if that variant is no longer needed.

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.

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

🔭 Outside diff range comments (1)
src/main.rs (1)

630-638: 🛠️ Refactor suggestion

parse_reference misses “pulls” URLs & other variants

GitHub sometimes serves PR URLs as
https://github.com/owner/repo/pulls/42 (note the s).
The current check segments[2] == "pull" therefore rejects a valid reference.

-            if segments.len() >= 4 && segments[2] == resource_type {
+            if segments.len() >= 4
+                && (segments[2] == resource_type
+                    || (resource_type == "pull" && segments[2] == "pulls"))
+            {

Optionally extend the “issues” branch to tolerate the singular “issue” as well.

🧹 Nitpick comments (1)
src/main.rs (1)

145-171: run_query can attach headers more idiomatically (and a tad faster)

Iterating and inserting one-by-one is unnecessary; RequestBuilder::headers takes a whole HeaderMap:

-    let mut req = client.post(endpoint);
-    for (k, v) in headers {
-        req = req.header(k, v);
-    }
-    let resp: GraphQlResponse<T> = req
+    let resp: GraphQlResponse<T> = client
+        .post(endpoint)
+        .headers(headers.clone())
         .json(&json!({ "query": query, "variables": variables }))
         .send()
         .await?
         .json()
         .await?;

Keeps the code shorter and avoids a small per-header allocation.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 361172c and 3782010.

📒 Files selected for processing (1)
  • src/main.rs (13 hunks)

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

leynos commented Jun 15, 2025

@coderabbitai new github issue

630-638: 🛠️ Refactor suggestion

parse_reference misses “pulls” URLs & other variants

GitHub sometimes serves PR URLs as
https://github.com/owner/repo/pulls/42 (note the s).
The current check segments[2] == "pull" therefore rejects a valid reference.

-            if segments.len() >= 4 && segments[2] == resource_type {
+            if segments.len() >= 4
+                && (segments[2] == resource_type
+                    || (resource_type == "pull" && segments[2] == "pulls"))
+            {

Optionally extend the “issues” branch to tolerate the singular “issue” as well.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 15, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@leynos I'll create a GitHub issue for this parsing improvement. Let me set that up for you.


🏁 Script executed:

#!/bin/bash
# Create a GitHub issue for the parse_reference URL variant handling
gh issue create \
  --title "parse_reference function doesn't handle plural URL variants (pulls/issues)" \
  --body "## Problem

The \`parse_reference\` function in \`src/main.rs\` currently only checks for exact matches of resource types (\"pull\" or \"issues\") but doesn't handle GitHub's plural URL variants.

GitHub sometimes serves PR URLs as:
- \`https://github.com/owner/repo/pulls/42\` (note the 's')

The current check \`segments[2] == resource_type\` therefore rejects valid references.

## Suggested Fix

\`\`\`rust
// Current code (line 630-638)
if segments.len() >= 4 && segments[2] == resource_type {

// Suggested improvement
if segments.len() >= 4
    && (segments[2] == resource_type
        || (resource_type == \"pull\" && segments[2] == \"pulls\"))
{
\`\`\`

Optionally extend the \"issues\" branch to tolerate the singular \"issue\" as well.

## References

- PR: https://github.com/leynos/vk/pull/18
- Original comment: https://github.com/leynos/vk/pull/18#discussion_r1914477937" \
  --assignee leynos

Length of output: 1043


Perfect! I've successfully created GitHub issue #19 for the URL parsing improvement: #19

The issue includes:

  • Clear description of the problem with plural URL variants
  • Your suggested code fix
  • Backlinks to this PR and the original comment
  • Assignment to you as requested

The issue is now tracked and ready for implementation in a future PR.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 15, 2025

@sourcery-ai review

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

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

  • Rename ResourceType::Pull to ResourceType::PullRequest for clearer alignment with GitHub terminology and to avoid ambiguity.
  • Enhance parse_reference error reporting to distinguish between an unrecognized URL format and a mismatched resource type, making it easier to diagnose parsing failures.
  • Include contextual information (e.g., query name or variables) in GraphQLClient.run_query error handling so failed requests can be debugged more easily.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Rename ResourceType::Pull to ResourceType::PullRequest for clearer alignment with GitHub terminology and to avoid ambiguity.
- Enhance parse_reference error reporting to distinguish between an unrecognized URL format and a mismatched resource type, making it easier to diagnose parsing failures.
- Include contextual information (e.g., query name or variables) in GraphQLClient.run_query error handling so failed requests can be debugged more easily.

## Individual Comments

### Comment 1
<location> `src/main.rs:176` </location>
<code_context>
+        }
+    }
+
+    async fn run_query<V, T>(&self, query: &str, variables: V) -> Result<T, VkError>
+    where
+        V: serde::Serialize,
</code_context>

<issue_to_address>
Use DeserializeOwned for T bound in run_query

This change simplifies lifetime management and guarantees that T is fully owned.

Suggested implementation:

```rust
    async fn run_query<V, T>(&self, query: &str, variables: V) -> Result<T, VkError>
    where
        V: serde::Serialize,
        T: serde::de::DeserializeOwned,

```

```rust
use serde::de::DeserializeOwned;

```
</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/main.rs
}
}

async fn run_query<V, T>(&self, query: &str, variables: V) -> Result<T, VkError>
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion: Use DeserializeOwned for T bound in run_query

This change simplifies lifetime management and guarantees that T is fully owned.

Suggested implementation:

    async fn run_query<V, T>(&self, query: &str, variables: V) -> Result<T, VkError>
    where
        V: serde::Serialize,
        T: serde::de::DeserializeOwned,
use serde::de::DeserializeOwned;

@leynos leynos merged commit 1fb651e into main Jun 15, 2025
1 check 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