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: replace strings.SplitN(arg, sep, 2) with strings.Cut(arg, sep) #23954

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

healthyyyoung
Copy link

@healthyyyoung healthyyyoung commented Mar 10, 2025

Description

replace strings.SplitN(arg, sep, 2) with strings.Cut(arg, sep):

  1. Improved code readability with more idiomatic Go
  2. Better performance by avoiding temporary slice allocation

Closes: #XXXX


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

Summary by CodeRabbit

  • Refactor

    • Streamlined the processing of key-value inputs for command-line arguments, ensuring consistent and clear validation without altering the user experience.
    • Simplified the path parsing logic, enhancing efficiency while maintaining existing error handling.
  • Tests

    • Introduced a new test suite for validating the Set method of the compositeMapValue structure, covering various scenarios for input parsing and error handling.

@healthyyyoung healthyyyoung requested a review from a team as a code owner March 10, 2025 16:31
Copy link
Contributor

coderabbitai bot commented Mar 10, 2025

📝 Walkthrough

Walkthrough

This pull request modifies the Set method of the compositeMapValue[T] and genericMapValue structs to enhance the key-value parsing logic. The implementation now uses strings.Cut to extract the key and value from an input string, simplifying error handling by checking a boolean for success instead of validating slice length. Additionally, a new test file has been introduced to validate the functionality of the Set method through various test cases. A refactor of the parsePath function in the store package is also included, utilizing strings.Cut for path parsing.

Changes

File Change Summary
client/v2/autocli/flag/map.go Updated the Set method to use strings.Cut(arg, "=") for key-value extraction and simplified error handling.
client/v2/autocli/flag/map_test.go Introduced a new test file with unit tests for the Set method, covering valid and invalid input scenarios.
store/rootmulti/store.go Refactored the parsePath function to use strings.Cut for path parsing, simplifying control flow and error handling.
client/v2/autocli/flag/maps/generic.go Updated the Set method to use strings.Cut for key-value extraction, with improved variable naming for clarity.

Suggested reviewers

  • lucaslopezf
  • cool-develope
  • akhilkumarpilli

Possibly related PRs

  • refactor(client): use map.Copy for cleaner map handling #24022: The changes in the main PR and the retrieved PR are related as both involve modifications to the Set method in different structs (compositeMapValue and genericMapValue) within the same package, focusing on how key-value pairs are parsed and handled.

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be96987 and 85348ff.

📒 Files selected for processing (1)
  • client/v2/autocli/flag/maps/generic.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

  • client/v2/autocli/flag/maps/generic.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (3)
client/v2/autocli/flag/maps/generic.go (3)

32-33: Excellent improvement using strings.Cut instead of strings.SplitN!

This change improves code readability and performance by:

  1. Using strings.Cut which avoids temporary slice allocation
  2. Directly checking the boolean return value (found) for success
  3. Making the code more idiomatic in modern Go

The new approach is cleaner and follows Go best practices.


36-40: Good variable naming improvement

Changing from array indices to descriptive variable names (key and value) significantly improves code readability and maintainability.


28-52:

✅ Verification successful

Verify all instances of strings.SplitN with similar pattern

The code change looks good. According to the PR comments, there might be additional occurrences of strings.SplitN(arg, sep, 2) in the codebase that should also be updated for consistency.


🏁 Script executed:

#!/bin/bash
# Find all instances of strings.SplitN with similar pattern in Go files
rg -A 1 "strings\.SplitN\(.*?, \"=\", 2\)" --type go

Length of output: 52


Consistency Verification: No additional strings.SplitN instances found

After a refined search across the codebase for occurrences of strings.SplitN(… , "=", 2), no additional instances were discovered. It appears that the code in client/v2/autocli/flag/maps/generic.go is the only relevant location and has been updated appropriately.

  • Verified the pattern in the snippet and across Go files using a refined regular expression.
  • No other occurrences matching the pattern were found.

Based on these findings, the change seems to be complete with respect to this issue.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings 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.

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.

@healthyyyoung healthyyyoung changed the title optmize: replace strings.SplitN(arg, sep, 2) with strings.Cut(arg, sep) optimize: replace strings.SplitN(arg, sep, 2) with strings.Cut(arg, sep) Mar 10, 2025
@github-actions github-actions bot added the C:CLI label Mar 10, 2025
@healthyyyoung healthyyyoung changed the title optimize: replace strings.SplitN(arg, sep, 2) with strings.Cut(arg, sep) refactor: replace strings.SplitN(arg, sep, 2) with strings.Cut(arg, sep) Mar 10, 2025
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: 0

🧹 Nitpick comments (3)
client/v2/autocli/flag/map_test.go (3)

52-52: Consider adding documentation comments.

Adding a documentation comment to explain the purpose of this test function and how it relates to the strings.Cut implementation would improve readability.

+// TestCompositeMapValue_Set tests the Set method of compositeMapValue
+// which uses strings.Cut for parsing key-value pairs from input strings.
 func TestCompositeMapValue_Set(t *testing.T) {

53-111: Consider adding edge cases to test suite.

While the current test cases cover the main scenarios, consider adding tests for edge cases such as:

  • Empty input string
  • Input with no separator character
  • Input with multiple consecutive separators
 		{
 			name:  "value parsing fails",
 			input: "1=foo,2=bar",
 			resolver: func(s string) (int, error) {
 				return 1, nil
 			},
 			valueType: &mockType{err: errors.New("value error")},
 			expectErr: true,
 		},
+		{
+			name:  "empty input",
+			input: "",
+			resolver: func(s string) (int, error) {
+				return 0, nil
+			},
+			valueType: &mockType{},
+			expectErr: false,
+			expectVals: map[int]string{},
+		},
+		{
+			name:  "input with no separator",
+			input: "justkey",
+			resolver: func(s string) (int, error) {
+				return 0, nil
+			},
+			valueType: &mockType{},
+			expectErr: true,
+		},

127-139: Consider verifying specific error messages.

The tests currently check for error presence but don't verify specific error messages. Consider enhancing error verification to ensure the right type of error is being reported.

 			if tc.expectErr {
 				assert.Error(t, err)
+				// For specific test cases, verify the error message
+				if tc.name == "invalid format" {
+					assert.Contains(t, err.Error(), "invalid key-value pair")
+				}
 			} else {
 				assert.NoError(t, err)
 				
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6dab309 and 9232957.

📒 Files selected for processing (1)
  • client/v2/autocli/flag/map_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.go`: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

  • client/v2/autocli/flag/map_test.go
`**/*_test.go`: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

**/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

  • client/v2/autocli/flag/map_test.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (5)
client/v2/autocli/flag/map_test.go (5)

3-10: Well-organized imports following Go conventions.

Imports are correctly organized with standard library imports first, followed by third-party imports.


12-38: Good mock implementation for testing.

The mockValue struct and its methods are well-designed for testing purposes, implementing all necessary interfaces correctly.


40-50: Well-structured mock type implementation.

The mockType struct correctly implements methods needed to create mock values for testing. Good approach for test isolation.


53-111: Well-structured table-driven tests with good test coverage.

The test cases effectively cover valid input parsing, invalid format handling, key resolver failures, and value parsing errors. This is a good approach for comprehensive testing of the strings.Cut implementation.


113-142: Test execution logic is well-structured and complete.

The test execution properly initializes the compositeMapValue, calls the Set method, and checks for expected outcomes. The conversion of protoreflect.Value to string for comparison is a good approach for verification.

@aljo242
Copy link
Collaborator

aljo242 commented Mar 18, 2025

@healthyyyoung it looks like there are more occurrences of strings.SplitN(arg, sep, 2) than what is covered here. Can we change them all?

@healthyyyoung
Copy link
Author

healthyyyoung commented Mar 19, 2025

@healthyyyoung it looks like there are more occurrences of strings.SplitN(arg, sep, 2) than what is covered here. Can we change them all?

checked all @aljo242

@aljo242
Copy link
Collaborator

aljo242 commented Mar 20, 2025

Can we target release/v0.53.x for this?

@healthyyyoung
Copy link
Author

Can we target release/v0.53.x for this?

no problem!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants