Skip to content

Handle missing reference defaults#24

Merged
leynos merged 3 commits intomainfrom
codex/wrap-load_and_merge_subcommand-in-match
Jul 20, 2025
Merged

Handle missing reference defaults#24
leynos merged 3 commits intomainfrom
codex/wrap-load_and_merge_subcommand-in-match

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 20, 2025

Summary

  • use match to handle configuration errors when merging subcommands
  • fall back to CLI args when defaults omit reference
  • document the behaviour in the usage section

Testing

  • cargo clippy -- -D warnings
  • RUSTFLAGS="-D warnings" cargo test
  • markdownlint README.md docs/GITHUB_TOKEN.md
  • nixie README.md docs/GITHUB_TOKEN.md

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

Summary by Sourcery

Use match to catch missing reference defaults during subcommand configuration merging and fall back to CLI-provided values instead of erroring out, and document this behavior in the README.

Enhancements:

  • Catch OrthoError::Gathering errors with MissingField("reference") when merging subcommand defaults and use the original CLI args as fallback
  • Update README to explain that missing 'reference' in defaults is handled by falling back to CLI input

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 20, 2025

Reviewer's Guide

Introduces explicit matching of configuration merge errors to allow missing ‘reference’ defaults to fall back to CLI-provided values for both PR and Issue subcommands, and documents this behavior in the README.

Sequence diagram for handling missing 'reference' in subcommand defaults

sequenceDiagram
    participant Main as main()
    participant CLI as CLI Args
    participant Config as Config Loader
    participant SubCmd as Subcommand Handler
    participant Runner as run_pr/run_issue

    Main->>CLI: Parse CLI args
    Main->>Config: Load config defaults
    Main->>SubCmd: load_and_merge_subcommand_for()
    alt Success
        SubCmd-->>Main: Ok(args)
    else MissingField("reference")
        SubCmd-->>Main: Err(MissingField("reference"))
        Main->>CLI: Use CLI args as fallback
    else Other error
        SubCmd-->>Main: Err(e)
        Main-->>Main: Return error
    end
    Main->>Runner: run_pr/run_issue(args, repo)
Loading

File-Level Changes

Change Details Files
Add fallback for missing reference during subcommand config merging
  • Replace direct load_and_merge_subcommand_for call with a match that catches MissingField("reference") and returns the raw CLI struct
  • Propagate other errors into the main error path
src/main.rs
Document behavior of missing reference defaults
  • Add note in README usage section explaining that when config defaults omit reference, CLI args are used instead of aborting
README.md

Possibly linked issues


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 Jul 20, 2025

Summary by CodeRabbit

  • Documentation

    • Updated documentation to clarify that default values for subcommands can be loaded from configuration files and environment variables, and missing required fields like reference will no longer cause the tool to exit if provided via the command line.
  • Bug Fixes

    • Improved handling of missing reference fields in configuration, allowing the CLI tool to continue when the value is supplied directly on the command line.

Walkthrough

Update the documentation to clarify how the vk CLI tool handles missing required fields from configuration sources. Adjust the main program logic to suppress errors about missing the reference field in configuration or environment variables, falling back to command-line arguments instead of exiting early.

Changes

File(s) Change Summary
README.md Update documentation to explain new behaviour for missing reference field in config/env defaults.
src/main.rs Add missing_reference helper and load_with_reference_fallback to suppress missing reference errors and fallback to CLI args. Replace direct config loading calls with fallback version in main.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant ConfigLoader

    User->>CLI: Run vk with subcommand (Pr/Issue) and arguments
    CLI->>ConfigLoader: load_and_merge_subcommand_for(subcommand)
    ConfigLoader-->>CLI: Return error (MissingField("reference"))?
    alt MissingField("reference")
        CLI->>CLI: Use CLI arguments as-is
    else Other error
        CLI-->>User: Return error and exit
    else Success
        CLI->>CLI: Use merged config and CLI arguments
    end
    CLI-->>User: Execute subcommand
Loading

Possibly related PRs

  • Add OrthoConfig and subcommands #13: Adds foundational configuration loading and subcommand structure, which this PR extends by refining error handling for missing required fields.

Poem

When reference hides from config’s sight,
The CLI steps in to set things right.
No more abrupt and early ends—
The tool now flexes, makes amends.
With docs refreshed and logic neat,
This change ensures the flow’s complete!
🚀


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 59bdd97 and 8260616.

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

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • AGENTS.md

⚙️ CodeRabbit Configuration File

🔇 Additional comments (3)
src/main.rs (3)

3-4: Import additions support robust error handling.

The new figment error imports enable proper pattern matching instead of fragile string matching on debug format.


704-704: Correctly applies fallback mechanism for Pr subcommand.

The change properly implements the intended behaviour to handle missing reference configuration gracefully.


708-708: Correctly applies fallback mechanism for Issue subcommand.

The change maintains consistency with the Pr subcommand and properly implements the intended graceful handling of missing reference configuration.

✨ 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/wrap-load_and_merge_subcommand-in-match

🪧 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 auto-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 found some issues that need to be addressed.

  • Instead of matching on the debug-formatted error string for MissingField("reference"), consider adding a dedicated variant or helper in OrthoError to detect missing reference fields more robustly.
  • The fallback match logic for PR and Issue args is duplicated; extract it into a shared helper function to reduce repetition in main.rs.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Instead of matching on the debug-formatted error string for MissingField("reference"), consider adding a dedicated variant or helper in OrthoError to detect missing reference fields more robustly.
- The fallback match logic for PR and Issue args is duplicated; extract it into a shared helper function to reduce repetition in main.rs.

## Individual Comments

### Comment 1
<location> `src/main.rs:677` </location>
<code_context>
     match cli.command {
         Commands::Pr(pr_cli) => {
-            let args = load_and_merge_subcommand_for::<PrArgs>(&pr_cli)?;
+            let args = match load_and_merge_subcommand_for::<PrArgs>(&pr_cli) {
+                Ok(v) => v,
+                Err(OrthoError::Gathering(e))
</code_context>

<issue_to_address>
The match statement has more than two branches and should be refactored into a predicate function.

To adhere to the instruction, please extract the multi-branch match logic into a separate predicate function for clarity and maintainability.
</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 Outdated
match cli.command {
Commands::Pr(pr_cli) => {
let args = load_and_merge_subcommand_for::<PrArgs>(&pr_cli)?;
let args = match load_and_merge_subcommand_for::<PrArgs>(&pr_cli) {
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.

issue (review_instructions): The match statement has more than two branches and should be refactored into a predicate function.

To adhere to the instruction, please extract the multi-branch match logic into a separate predicate function for clarity and maintainability.

Review instructions:

Path patterns: **/*.rs

Instructions:
Move conditionals with >2 branches into a predicate function.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a55dd3 and 3e100db.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • src/main.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.md

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • AGENTS.md

⚙️ CodeRabbit Configuration File

**/*.rs

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • AGENTS.md

⚙️ CodeRabbit Configuration File

🔇 Additional comments (2)
src/main.rs (1)

3-3: Verify public exports of GatheringError in ortho_config
The grep didn’t locate a pub enum GatheringError or its variants in the ortho_config crate. Ensure the error type and its variants are publicly exposed so that calling crates can pattern-match on them.

  • Inspect the ortho_config crate’s source (e.g. src/lib.rs or the module defining GatheringError) and confirm it contains:
    pub enum GatheringError {
        MissingField(String),
        // …
    }
  • If GatheringError is defined in a submodule, add a pub use in lib.rs to re-export it:
    pub use gathering::GatheringError;
  • After exposing the enum, update the import in src/main.rs as needed:
    use ortho_config::{OrthoConfig, OrthoError, GatheringError, /* … */};
README.md (1)

28-31: Documentation accurately describes the new fallback behaviour.

The explanation clearly communicates that missing reference fields in configuration will gracefully fall back to CLI arguments rather than causing the tool to exit with an error. This aligns perfectly with the implementation changes.

Comment thread src/main.rs Outdated
Comment thread src/main.rs Outdated
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e100db and 59bdd97.

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

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • AGENTS.md

⚙️ CodeRabbit Configuration File

🔇 Additional comments (2)
src/main.rs (2)

3-4: LGTM! Imports support proper error handling.

The new imports enable robust pattern matching on configuration errors, replacing the fragile string matching approach mentioned in past reviews.


695-695: LGTM! Consistent application of fallback behaviour.

The changes correctly replace direct config loading with the new fallback function for both command types, addressing the fragile string matching issues from past reviews.

Also applies to: 699-699

Comment thread src/main.rs
Comment on lines +670 to +674
fn missing_reference(err: &FigmentError) -> bool {
err.clone()
.into_iter()
.any(|e| matches!(e.kind, FigmentKind::MissingField(ref f) if f == "reference"))
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Avoid unnecessary cloning in error iteration.

The function correctly uses pattern matching instead of fragile string matching, addressing past review concerns. However, cloning the error for iteration is inefficient.

Apply this diff to avoid cloning:

-fn missing_reference(err: &FigmentError) -> bool {
-    err.clone()
-        .into_iter()
-        .any(|e| matches!(e.kind, FigmentKind::MissingField(ref f) if f == "reference"))
-}
+fn missing_reference(err: &FigmentError) -> bool {
+    err.iter()
+        .any(|e| matches!(e.kind, FigmentKind::MissingField(ref f) if f == "reference"))
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main.rs around lines 670 to 674, the function missing_reference clones
the error before iterating, which is inefficient. Modify the function to iterate
over references to the error without cloning it, by using a method like iter()
or as_ref() on the error to avoid unnecessary cloning while preserving the
pattern matching logic.

Comment thread src/main.rs Outdated
Comment on lines +675 to +685
#[allow(clippy::result_large_err)]
fn load_with_reference_fallback<T>(cli_args: T) -> Result<T, OrthoError>
where
T: OrthoConfig + serde::Serialize + Default + clap::CommandFactory + Clone,
{
match load_and_merge_subcommand_for::<T>(&cli_args) {
Ok(v) => Ok(v),
Err(OrthoError::Gathering(e)) if missing_reference(&e) => Ok(cli_args),
Err(e) => Err(e),
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix coding guideline violations.

The function has two violations of the coding guidelines:

  1. Multi-branch conditional: The match statement has >2 branches and must be refactored into a predicate function per coding guidelines.
  2. Forbidden #[allow] attribute: Replace with narrowly scoped #[expect] with reason.

Apply this diff to address the violations:

+fn should_fallback_to_cli(result: &Result<(), OrthoError>) -> bool {
+    matches!(result, Err(OrthoError::Gathering(e)) if missing_reference(e))
+}
+
-#[allow(clippy::result_large_err)]
+#[expect(clippy::result_large_err, reason = "OrthoError size is determined by ortho_config crate")]
 fn load_with_reference_fallback<T>(cli_args: T) -> Result<T, OrthoError>
 where
     T: OrthoConfig + serde::Serialize + Default + clap::CommandFactory + Clone,
 {
-    match load_and_merge_subcommand_for::<T>(&cli_args) {
-        Ok(v) => Ok(v),
-        Err(OrthoError::Gathering(e)) if missing_reference(&e) => Ok(cli_args),
-        Err(e) => Err(e),
-    }
+    let result = load_and_merge_subcommand_for::<T>(&cli_args);
+    if should_fallback_to_cli(&result.as_ref().map(|_| ())) {
+        Ok(cli_args)
+    } else {
+        result
+    }
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main.rs around lines 675 to 685, refactor the match statement in
load_with_reference_fallback to eliminate the multi-branch conditional by
extracting the error condition into a separate predicate function that checks if
the error is a Gathering error with a missing reference. Also, remove the broad
#[allow(clippy::result_large_err)] attribute and replace it with a narrowly
scoped #[expect] attribute on the specific line or expression causing the lint,
including a reason for the expectation.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 20, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 20, 2025

✅ Actions performed

Review triggered.

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

@leynos leynos merged commit 37d1e52 into main Jul 20, 2025
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Jul 28, 2025
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