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

added structs comparison support #11

Merged
merged 3 commits into from
Oct 24, 2024
Merged

Conversation

kashifkhan0771
Copy link
Owner

@kashifkhan0771 kashifkhan0771 commented Oct 22, 2024

Added the support to compare two objects of same struct and return the results with old and new value

Summary by CodeRabbit

  • New Features

    • Introduced a new package for comparing struct instances, enabling users to easily identify changes between old and new data.
    • Added a Result structure to detail differences in field values.
  • Tests

    • Implemented test cases to validate the functionality of the new comparison feature, ensuring accuracy in detecting changes between struct instances.
    • Added tests for both simple and complex struct comparisons to verify expected outputs.

@kashifkhan0771 kashifkhan0771 self-assigned this Oct 22, 2024
@kashifkhan0771 kashifkhan0771 linked an issue Oct 22, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

A new Go package named structs has been introduced, which includes a type definition for Result and a function CompareStructs that compares two struct instances. The Result struct holds information about the differences between fields. Additionally, a test file structs_test.go has been created to validate the functionality of CompareStructs using various test cases involving simple and complex struct types.

Changes

File Change Summary
structs/structs.go Added type Result struct and func CompareStructs(old, new interface{}) ([]Result, error)
structs/structs_test.go Added type Test struct, type ComplexTest struct, and func TestCompareStructs(t *testing.T)

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CompareStructs
    participant Result

    User->>CompareStructs: Call CompareStructs(old, new)
    CompareStructs->>CompareStructs: Check if types match
    CompareStructs->>CompareStructs: Iterate over fields
    CompareStructs->>CompareStructs: Check for 'updateable' tag
    CompareStructs->>Result: Create Result if values differ
    CompareStructs-->>User: Return results slice and nil error
Loading

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c14c889 and 34a656b.

📒 Files selected for processing (2)
  • structs/structs.go (1 hunks)
  • structs/structs_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • structs/structs.go
  • structs/structs_test.go

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
Contributor

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

🧹 Outside diff range and nitpick comments (5)
structs/structs_test.go (2)

9-19: LGTM! Consider adding comments for better documentation.

The struct definitions for Test and ComplexTest are well-structured and appropriate for testing purposes. The use of updateable tags is a good practice for specifying which fields should be compared.

Consider adding comments to describe the purpose of each struct and field, especially for the updateable tags. This would improve code documentation and make it easier for other developers to understand the test setup.


21-88: LGTM! Consider adding more edge cases.

The TestCompareStructs function is well-structured using table-driven tests, which is a good practice in Go. The test cases cover both simple and complex struct comparisons, providing good coverage of the CompareStructs function's functionality.

Consider adding more test cases to cover edge cases and improve test coverage:

  1. Compare structs with unexported fields to ensure they're handled correctly.
  2. Test with empty structs or structs where no fields have changed.
  3. Test with structs containing pointer fields or interface fields.
  4. Add a negative test case where the input structs are of different types to ensure proper error handling.

Example of an additional test case:

{
    name: "compare structs with no changes",
    old:  Test{Name: "example", Age: 10, IsAdult: false},
    new:  Test{Name: "example", Age: 10, IsAdult: false},
    want: []Result{},
    wantErr: false,
},
structs/structs.go (3)

15-18: Follow Go documentation conventions for CompareStructs function

Comments for exported functions should begin with the function name and be in the form of a single-line comment. This enhances readability and adheres to Go's documentation standards.

Apply this diff to adjust the comment:

-/*
-CompareStructs compares two struct instances of the same type
-and returns a list of results with the old and new values of each field tagged with `updateable`.
-*/
+// CompareStructs compares two struct instances of the same type
+// and returns a list of results with the old and new values of each field tagged with `updateable`.

27-27: Optimize slice allocation for comparedResults

Pre-allocating the slice with an estimated capacity can improve performance by reducing memory allocations during appends.

Consider initializing the slice with the number of fields:

-var comparedResults = make([]Result, 0)
+var comparedResults = make([]Result, 0, oldValue.NumField())

40-44: Standardize struct tag naming to updatable

The tag updateable is less commonly used compared to updatable. Standardizing the tag name improves readability and aligns with conventional spelling.

Apply this diff to update the tag name throughout the code:

-// Check if the field has the `updateable` tag
-if tag, ok := field.Tag.Lookup("updateable"); ok && tag != "" {
+// Check if the field has the `updatable` tag
+if tag, ok := field.Tag.Lookup("updatable"); ok && tag != "" {

Ensure that the struct definitions using this tag are also updated accordingly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a1ff267 and 8111c79.

📒 Files selected for processing (2)
  • structs/structs.go (1 hunks)
  • structs/structs_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (3)
structs/structs_test.go (1)

1-88: Overall, good test structure with room for enhancement.

The structs_test.go file provides a solid foundation for testing the CompareStructs function. The use of table-driven tests and the coverage of both simple and complex struct comparisons are commendable. To further improve the quality and robustness of the tests, consider implementing the suggested additional test cases and adding more comprehensive documentation.

These enhancements will ensure that the CompareStructs function is thoroughly tested across a wide range of scenarios, increasing confidence in its reliability and correctness.

structs/structs.go (2)

20-22: ⚠️ Potential issue

Add type checks to prevent potential panics

The function assumes that old and new are structs. If non-struct types are passed, methods like NumField() will cause a panic. It's important to verify that the inputs are of kind reflect.Struct.

Apply this diff to add the necessary checks:

 if reflect.TypeOf(old) != reflect.TypeOf(new) {
   return nil, fmt.Errorf("both structs must be of the same type")
 }
+if reflect.ValueOf(old).Kind() != reflect.Struct || reflect.ValueOf(new).Kind() != reflect.Struct {
+  return nil, fmt.Errorf("both inputs must be structs")
+}

29-55: ⚠️ Potential issue

Handle nested structs and pointer fields

The current implementation does not account for nested structs or pointer fields within the structs being compared. This could lead to incomplete comparisons or runtime panics.

Consider enhancing the function to handle these cases, possibly by adding recursive comparison for nested structs and checking for pointer types. Here’s a conceptual example:

func compareValues(oldValue, newValue reflect.Value, fieldName string) Result {
  // Recursive comparison logic goes here
}

Would you like assistance in implementing recursive comparison?

structs/structs_test.go Outdated Show resolved Hide resolved
structs/structs.go Outdated Show resolved Hide resolved
structs/structs.go Show resolved Hide resolved
@shahzadhaider1
Copy link
Collaborator

Please rebase with main so it run all the checks

Repository owner deleted a comment from coderabbitai bot Oct 23, 2024
Repository owner deleted a comment from coderabbitai bot Oct 23, 2024
oldValue := reflect.ValueOf(old)
newValue := reflect.ValueOf(new)

var comparedResults = make([]Result, 0)
Copy link
Collaborator

Choose a reason for hiding this comment

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

We should initialize the slice with a capacity, possibly using make([]Result, 0, oldValue.NumField()). This avoids unnecessary memory allocations when appending items later, which improves performance.

Copy link
Owner Author

Choose a reason for hiding this comment

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

done

structs/structs.go Show resolved Hide resolved
structs/structs_test.go Show resolved Hide resolved
@shahzadhaider1
Copy link
Collaborator

Please rebase the branch as well as this branch is out-of-date with the base branch

Copy link
Contributor

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

🧹 Outside diff range and nitpick comments (1)
structs/structs_test.go (1)

9-19: Add documentation for struct types.

Consider adding documentation comments for both Test and ComplexTest types to explain their purpose and usage.

Example:

+// Test represents a basic structure with personal information used for testing struct comparison.
 type Test struct {
     Name    string `updateable:"name"`
     Age     int    `updateable:"age"`
     IsAdult bool   `updateable:"is_adult"`
 }

+// ComplexTest represents a structure containing nested Test data along with temporal and historical information.
 type ComplexTest struct {
     Data      Test      `updateable:"data"`
     UpdatedOn time.Time `updateable:"updated_on"`
     History   []string  `updateable:"history"`
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3894e95 and 667dbf1.

📒 Files selected for processing (2)
  • structs/structs.go (1 hunks)
  • structs/structs_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • structs/structs.go
🔇 Additional comments (2)
structs/structs_test.go (2)

1-7: LGTM!

Package name and imports are appropriate for the test file.


83-94: LGTM!

The test execution logic is well-structured and handles errors appropriately.

structs/structs_test.go Show resolved Hide resolved
structs/structs_test.go Show resolved Hide resolved
structs/structs_test.go Show resolved Hide resolved
Copy link
Collaborator

@shahzadhaider1 shahzadhaider1 left a comment

Choose a reason for hiding this comment

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

LGTM

@shahzadhaider1 shahzadhaider1 merged commit a18a065 into main Oct 24, 2024
1 check passed
@shahzadhaider1 shahzadhaider1 deleted the feat/compare-structs branch October 24, 2024 21:08
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.

Compare and Capture Changes for Struct Fields with updateable Tag
2 participants