Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

💝 Allow error handlers to access the Cobra' command object #4

Merged
merged 1 commit into from
Oct 18, 2024

Conversation

cardil
Copy link
Member

@cardil cardil commented Oct 18, 2024

Allow error handlers to access the Cobra' command object

Summary by CodeRabbit

  • New Features

    • Enhanced error handling capabilities by providing context about the command that triggered an error.
  • Bug Fixes

    • Updated error handler to improve processing and context management during error occurrences.
  • Tests

    • Adjusted test functions to align with the updated error handler signature, ensuring consistent testing practices.

Copy link

coderabbitai bot commented Oct 18, 2024

Walkthrough

The changes involve updates to the ErrorHandler type in app.go, allowing it to accept an additional parameter: a pointer to a cobra.Command. This modification provides context about the command that triggered an error, enhancing error handling. Correspondingly, the WithErrorHandler function in app_test.go is adjusted to accommodate this new signature, ensuring that tests remain valid while reflecting the updated functionality.

Changes

File(s) Change Summary
app.go Updated ErrorHandler type to accept a *cobra.Command pointer; modified ExecuteOrDie to pass the command context.
app_test.go Modified WithErrorHandler function call in TestExecuteOrDie to match the new ErrorHandler signature.

Possibly related PRs

  • 🎁 Custom error handler #3: The changes in this PR also involve modifications to the ErrorHandler type and its integration within the App struct, directly relating to the updates made in the main PR regarding error handling capabilities.

Suggested labels

enhancement

Poem

🐇 In the garden where errors bloom,
A handler now finds room,
With commands to guide the way,
Errors fade, come what may.
Hopping through code, we cheer,
Context brings us joy, oh dear! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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

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

🧹 Outside diff range and nitpick comments (2)
app.go (2)

25-25: LGTM: ErrorHandler signature update enhances functionality

The addition of the cmd *cobra.Command parameter to the ErrorHandler type signature is a good improvement. It allows error handlers to access the Cobra command object, providing more context for error handling. This change aligns well with the PR objective and enhances the flexibility of error handling in the application.

Consider renaming the cmd parameter to command for improved readability:

-type ErrorHandler func(err error, cmd *cobra.Command) bool
+type ErrorHandler func(err error, command *cobra.Command) bool

46-46: LGTM with a suggestion for improvement

The update to pass a.root as the second argument to ErrorHandler is consistent with the new type signature. This change allows the error handler to access the command context, which is a good improvement.

For multi-command applications, consider passing the specific command that caused the error instead of always passing the root command. This would provide more precise context to the error handler. You might need to modify the Execute method of the cobra.Command to track the current command. Here's a conceptual example of how this could be implemented:

func (a *App) Execute(options ...Option) error {
    // ... existing code ...
    var currentCmd *cobra.Command
    a.root.PersistentPreRun = func(cmd *cobra.Command, args []string) {
        currentCmd = cmd
    }
    err := a.root.Execute()
    if err != nil {
        return &commandError{err, currentCmd}
    }
    return nil
}

type commandError struct {
    err error
    cmd *cobra.Command
}

func (ce *commandError) Error() string {
    return ce.err.Error()
}

// In ExecuteOrDie
if a.ErrorHandler == nil || !a.ErrorHandler(err, ce.cmd) {
    a.defaultErrorHandler(err)
}

This approach would provide the specific command that caused the error to the error handler, rather than always passing the root command.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b266316 and 4790dfe.

📒 Files selected for processing (2)
  • app.go (2 hunks)
  • app_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
app_test.go (1)

27-29: LGTM! Consider adding a test case utilizing the new command parameter.

The change successfully implements the PR objective by allowing error handlers to access the Cobra command object. The use of _ for the unused parameter follows Go conventions.

To improve test coverage, consider adding a new test case that utilizes the *cobra.Command parameter in the error handler. This would ensure that the new functionality is properly tested.

Example:

commandline.WithErrorHandler(func(merr error, cmd *cobra.Command) bool {
    err = merr
    assert.Assert(t, cmd != nil, "Command should not be nil")
    assert.Equal(t, "example", cmd.Use)
    return false
}),

Let's verify if there are other usages of WithErrorHandler that might need updating:

✅ Verification successful

Verified! No additional usages of WithErrorHandler require changes.

The update to WithErrorHandler in app_test.go is isolated to this test file and does not affect other parts of the codebase. The test change aligns with the PR objective and maintains existing functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of WithErrorHandler
rg --type go 'WithErrorHandler\(' -C 3

Length of output: 547

app.go (1)

23-24: LGTM: Comment update is clear and consistent

The updated comment accurately reflects the changes made to the ErrorHandler type signature. It provides clear information about the new parameter (the Cobra command) and specifies that it's the command that threw the error. This addition enhances the documentation and helps users understand the context provided to the error handler.

@cardil cardil merged commit b448e1c into main Oct 18, 2024
3 checks passed
@cardil cardil deleted the feature/error-handler-cobra-access branch October 18, 2024 15:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant