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

Exclude embedded fields in response header docs #656

Merged
merged 3 commits into from
Nov 22, 2024

Conversation

lucaspopp-wbd
Copy link
Contributor

@lucaspopp-wbd lucaspopp-wbd commented Nov 20, 2024

Ignore embedded fields when finding response headers (resolves #655)

Not sure if it’s intentional that any field regardless of if tagged with header is considered a response header. If that’s not your intent, we could simplify this by returning nil when header == “”

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Improved header processing logic to ignore embedded fields, ensuring only explicitly defined struct fields are considered for header extraction.
    • Added pagination headers to the API response structure, allowing for pagination information to be included.
  • Bug Fixes

    • Enhanced clarity and specificity in header handling within the API framework.
    • Expanded test coverage for cookie handling, middleware behavior, and request parameter validation.
    • Improved error handling in tests with additional assertions for invalid inputs.

Copy link

coderabbitai bot commented Nov 20, 2024

Walkthrough

The changes in this pull request modify the findHeaders function within the huma.go file. A new code block has been added to ignore embedded fields when processing struct fields for headers. This ensures that only explicitly defined fields are considered for header extraction, refining the header processing logic. The overall structure, method signatures, and error handling remain unchanged. Additionally, the huma_test.go file has been updated to include new test cases and enhancements related to pagination headers and various request scenarios.

Changes

File Change Summary
huma.go Modified findHeaders function to ignore embedded fields when processing structs for headers.
huma_test.go Added PaginationHeaders type, enhanced existing tests, and refined cookie handling and middleware tests. Updated OpenAPI documentation generation to exclude PaginationHeaders.

Assessment against linked issues

Objective Addressed Explanation
Ensure embedded structs do not appear in documentation (#[655])

Possibly related PRs

Suggested reviewers

  • danielgtaylor

Poem

In fields where headers lie,
We sift through structs, oh so spry!
With embedded bits set aside,
Clearer paths for data to glide.
A hop, a skip, we refine our way,
In code's embrace, we dance and play! 🐰✨

Warning

Rate limit exceeded

@lucaspopp-wbd has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 47 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 9c28010 and affa017.


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

codecov bot commented Nov 20, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 93.04%. Comparing base (bb5d167) to head (affa017).
Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #656   +/-   ##
=======================================
  Coverage   93.04%   93.04%           
=======================================
  Files          22       22           
  Lines        4901     4905    +4     
=======================================
+ Hits         4560     4564    +4     
  Misses        298      298           
  Partials       43       43           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.


🚨 Try these New Features:

@lucaspopp-wbd lucaspopp-wbd changed the title Exclude embedded fields in response headers Exclude embedded fields in response header docs Nov 20, 2024
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)
huma.go (2)

233-236: Add test coverage for embedded field exclusion.

The new code block that handles embedded field exclusion is not covered by tests. Please add test cases to verify:

  1. Embedded fields with header tags are correctly ignored
  2. Non-embedded fields with header tags are still processed

Would you like me to help generate test cases for this functionality?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 235-236: huma.go#L235-L236
Added lines #L235 - L236 were not covered by tests


233-236: Document the embedded field behavior.

Consider adding a comment to explain that embedded fields are intentionally ignored when processing headers.

Apply this diff to add documentation:

 func findHeaders(t reflect.Type) *findResult[*headerInfo] {
 	return findInType(t, nil, func(sf reflect.StructField, i []int) *headerInfo {
+		// Embedded (anonymous) fields are intentionally ignored when processing headers
 		if sf.Anonymous {
 			return nil
 		}
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 235-236: huma.go#L235-L236
Added lines #L235 - L236 were not covered by tests

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bb5d167 and d86c7a2.

📒 Files selected for processing (1)
  • huma.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
huma.go

[warning] 235-236: huma.go#L235-L236
Added lines #L235 - L236 were not covered by tests

🔇 Additional comments (1)
huma.go (1)

233-236: LGTM! The change correctly implements the exclusion of embedded fields.

The addition of the embedded field check aligns with the PR objective and prevents embedded fields from being processed as headers.

Let's verify the impact of this change on embedded structs:

✅ Verification successful

Let me search for embedded structs with header tags to verify the impact of ignoring embedded fields.


Let me try a different approach to search for embedded fields and header tags.


Let me try one more search to specifically look for header tags and embedded fields together.


Based on the search results, I can now provide a final response:

The change to ignore embedded fields is safe and does not impact header processing.

The codebase search shows that while there are many structs with header tags, none of them use embedded fields for header processing. The header tags are always explicitly defined on regular struct fields. This means ignoring embedded fields won't affect any existing header processing functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for embedded structs that might be affected by this change
# Look for struct types that are embedded in other structs and have header tags

ast-grep --pattern 'type $_ struct {
  $$$
  $_
  $$$
}'

Length of output: 58427


Script:

#!/bin/bash
# Search for embedded structs with header tags
ast-grep --pattern 'type $_ struct {
  $$$
  $_ `header:"$_"`
  $$$
}'

Length of output: 72


Script:

#!/bin/bash
# Search for struct definitions with embedded fields
rg -U "type.*struct.*{[\s\S]*?\s+\w+\s+`header:.*?`[\s\S]*?}" --type go

# Also search for anonymous (embedded) fields
rg "^\s+\w+(\.\w+)?\s*$" --type go

Length of output: 6222


Script:

#!/bin/bash
# Search for struct definitions with header tags
rg -U "type \w+ struct \{(\n[^\}]*?)*?\s+\w+\s+\`.*?header:.*?\`" --type go

# Search for embedded fields in the same files
rg "type \w+ struct \{[^}]*?\n\s+[A-Z]\w+(\.[A-Z]\w+)?\s*(\n|\})" --type go

Length of output: 5234

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 235-236: huma.go#L235-L236
Added lines #L235 - L236 were not covered by tests

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 (3)
huma_test.go (3)

1938-1940: Add documentation comment for exported struct PaginationHeaders

Consider adding a documentation comment for the exported struct PaginationHeaders to adhere to Go conventions and improve code readability.


1943-1946: Add documentation comment for exported struct Resp

Consider adding a documentation comment for the exported struct Resp to enhance code clarity and maintainability.


1973-1981: Enhance test ignore-anonymous-header-structs for more precise validation

While the current test checks that PaginationHeaders is not included in the OpenAPI output, consider adding an assertion to verify that the Link header is not documented. This makes the test more robust by directly checking the absence of the header.

Example:

assert.NotContains(t, openapiBody, `"link"`)

This ensures that the Link header field is not present in the OpenAPI documentation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d86c7a2 and 9c28010.

📒 Files selected for processing (1)
  • huma_test.go (2 hunks)

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 (1)
huma_test.go (1)

1974-1983: LGTM! Well-structured test case for embedded struct exclusion.

The test case effectively verifies that embedded structs are excluded from OpenAPI output while preserving the header fields. Consider adding additional test cases to verify:

  1. Multiple embedded structs
  2. Nested embedded structs
  3. Embedded structs with conflicting header fields
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9c28010 and affa017.

📒 Files selected for processing (1)
  • huma_test.go (2 hunks)
🔇 Additional comments (1)
huma_test.go (1)

1938-1942: LGTM! Clean type definition for testing embedded header fields.

The PaginationHeaders struct is well-defined with appropriate header tag for testing the exclusion of embedded fields from response headers.

Copy link
Owner

@danielgtaylor danielgtaylor left a comment

Choose a reason for hiding this comment

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

Thank you! 👍

@danielgtaylor danielgtaylor merged commit bfe8892 into danielgtaylor:main Nov 22, 2024
5 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.

Embedded struct in response showing up in docs
2 participants