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

Refactor docgen: improve error handling and file operations #6103

Merged
merged 2 commits into from
Mar 24, 2025

Conversation

Mehran-Seifalinia
Copy link
Contributor

@Mehran-Seifalinia Mehran-Seifalinia commented Mar 20, 2025

Moved the argument check to the start of main() so we don’t do any unnecessary work if the arguments aren’t provided. Also added proper error handling for encoder.Encode(jsonschemaData), since it was failing silently before.

Switched os.WriteFile to os.Create for better file handling and error reporting. To clean things up, I added a writeToFile() function to remove duplicate code.

For replacing schema paths, I used ReplaceAllString() instead of looping through matches—it’s cleaner and a bit more efficient. Also renamed r to t in the Namer function to make things clearer.

Proposed changes

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • Refactor
    • Streamlined the process for generating documentation and schema outputs.
    • Enhanced error messaging to provide clearer context when issues arise.
    • Optimized operations for a more reliable and maintainable output generation process.

Moved the argument check to the start of main() so we don’t do any unnecessary work if the arguments aren’t provided. Also added proper error handling for encoder.Encode(jsonschemaData), since it was failing silently before.

Switched os.WriteFile to os.Create for better file handling and error reporting. To clean things up, I added a writeToFile() function to remove duplicate code.

For replacing schema paths, I used ReplaceAllString() instead of looping through matches—it’s cleaner and a bit more efficient. Also renamed r to t in the Namer function to make things clearer.
@auto-assign auto-assign bot requested a review from dogancanbakir March 20, 2025 19:02
Copy link
Contributor

coderabbitai bot commented Mar 20, 2025

Walkthrough

The changes introduce a new function writeToFile(filename string, data []byte) in the documentation generation tool, which centralizes the logic for file creation and writing. The main function has been updated to utilize this new function for both YAML documentation and JSON schema outputs. Additionally, error messages have been improved to include filenames, and the JSON schema generation logic has been refined with a more concise inline function and a simplified string replacement method.

Changes

Files Change Summary
cmd/.../docgen.go - Added new function writeToFile(filename string, data []byte) to encapsulate file creation/writing logic.
- Updated main to use writeToFile for YAML and JSON schema outputs.
- Enhanced error messages to include filenames.
- Modified JSON schema generation with an inline function and simplified string replacement using pathRegex.ReplaceAllString.

Sequence Diagram(s)

sequenceDiagram
    participant M as Main Function
    participant W as writeToFile Function
    participant FS as File System

    M->>W: Invoke writeToFile(filename, data)
    W->>FS: Create/Open file with filename
    FS-->>W: Return file handle or error
    W->>FS: Write data to file
    FS-->>W: Confirm write or return error
    W-->>M: Return success/error status
Loading

Poem

From tunnels deep in lines of code,
I hop with glee on this new road.
A helper function makes things neat,
Files and errors now do meet.
With JSON and YAML in joyful rhyme,
The burrow sings—a change so prime!
🐰✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between cd26354 and e7a18ab.

📒 Files selected for processing (1)
  • cmd/docgen/docgen.go (1 hunks)
🔇 Additional comments (6)
cmd/docgen/docgen.go (6)

17-28: Good addition of a centralized file writing function.

Creating a dedicated function for file operations improves code maintainability and reduces duplication. The implementation properly handles file creation, writing, and error reporting with descriptive messages that include filenames.


35-40: Good refactoring of YAML documentation generation.

The code is now more readable with better variable naming and error messaging. Using the new writeToFile function centralizes the file operation logic.


43-49: Improved variable naming in the Namer function.

Changing the parameter name from r to t is a good practice as it better represents that the parameter is a type. This makes the code more self-documenting.


57-59: Enhanced error handling for JSON schema encoding.

Adding explicit error checking for encoder.Encode() is an important improvement. Previously, this error might have been silently ignored, which could lead to difficult-to-debug issues.


61-62: Simplified schema path replacement with more efficient code.

Using ReplaceAllString directly instead of iterating through matches is cleaner and more efficient. Combined with the centralized file writing function, this makes the code more maintainable.


3-13:

✅ Verification successful

Lint error: unused import "strings".

According to the PR comments, there's a lint error about an unused "strings" import, but this import is not present in the code shown here. Please verify if this issue has been resolved.


🏁 Script executed:

#!/bin/bash
# Check if there's an unused "strings" import
grep -n "strings" cmd/docgen/docgen.go

Length of output: 38


Verification complete: Unused "strings" import is resolved.

  • The grep check for the string "strings" in cmd/docgen/docgen.go produced no output, indicating that the unused import is no longer present.
  • Based on the evidence, the previously reported lint error has been resolved and no further action is necessary.

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

@GeorginaReeder
Copy link

Thanks for your contribution @Mehran-Seifalinia ! :)

@Mehran-Seifalinia
Copy link
Contributor Author

Do I need to change the code and submit it again to fix the Lint error, or will the development team handle resolving it?

@ehsandeep
Copy link
Member

Do I need to change the code and submit it again to fix the Lint error, or will the development team handle resolving it?

@Mehran-Seifalinia feel free to push additonal commit to resolve lint error:

  Running [/home/runner/golangci-lint-1.64.8-linux-amd64/golangci-lint config path] in [/home/runner/work/nuclei/nuclei] ...
  Running [/home/runner/golangci-lint-1.64.8-linux-amd64/golangci-lint run  --timeout=5m] in [/home/runner/work/nuclei/nuclei] ...
  cmd/docgen/docgen.go:1: : # github.com/projectdiscovery/nuclei/v3/cmd/docgen
  Error: cmd/docgen/docgen.go:9:2: "strings" imported and not used (typecheck)

- Remove importing string
@ehsandeep ehsandeep merged commit 63136c8 into projectdiscovery:dev Mar 24, 2025
19 checks passed
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.

4 participants