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

Bump golangci-lint to v1.62.0 #3196

Merged
merged 1 commit into from
Nov 11, 2024
Merged

Bump golangci-lint to v1.62.0 #3196

merged 1 commit into from
Nov 11, 2024

Conversation

gaby
Copy link
Member

@gaby gaby commented Nov 11, 2024

Description

  • Bump golangci-lint to v1.62.0

Type of change

  • Code consistency (non-breaking change which improves code reliability and robustness)

@gaby gaby added this to the v3 milestone Nov 11, 2024
@gaby gaby requested a review from a team as a code owner November 11, 2024 01:34
@gaby gaby requested review from sixcolors, ReneWerner87 and efectn and removed request for a team November 11, 2024 01:34
@gaby gaby changed the title updates: bump golangci-lint to v1.62.0 Bump golangci-lint to v1.62.0 Nov 11, 2024
Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on updates to error handling and linting directives. Key modifications include an increment in the golangci-lint version in the Makefile, enhancements to test assertions in various test files to improve clarity and robustness, and updates to error handling comments in several middleware files. The overall structure and functionality of the codebase remain intact, with a focus on improving code quality and maintainability.

Changes

File Change Summary
Makefile Updated lint target to use golangci-lint version v1.62.0.
client/hooks_test.go Changed assertions in Test_Parser_Request_Header and Test_Parser_Request_Body from require.True to require.Contains. Added comments for linting exceptions.
client/response_test.go Updated assertions in Test_Response_Save to use require.JSONEq for JSON comparison instead of require.Equal.
ctx_test.go Updated assertions to require.JSONEq. Added benchmark tests and new test cases for context methods. Refactored for clarity.
log/default.go Added errcheck to the nolint directive in privateLogw method for error handling.
middleware/adaptor/adaptor.go Updated error handling for net.SplitHostPort with additional nolint:errcheck directive.
middleware/cache/heap.go Updated nolint comments in Push and removeInternal methods to include errcheck.
middleware/cache/manager.go Enhanced error handling in acquire, get, and getRaw methods, including nolint:errcheck comments.
middleware/limiter/manager.go Updated nolint comments in acquire and get methods to include errcheck.
middleware/logger/default_logger.go Added errcheck to comments for data.Timestamp.Load() calls. Minor adjustments in error handling comments.
middleware/logger/logger_test.go Updated assertions in Test_Logger_WithLatency to modify error message formatting.
middleware/logger/tags.go Updated error handling for TagTime function to include nolint:errcheck.
router.go Updated error handling in requestHandler to include //nolint:errcheck comment.

Possibly related PRs

  • Bump golangci-lint to v1.61.0 #3135: This PR is directly related as it also updates the golangci-lint tool version in the Makefile, specifically from v1.61.0 to v1.62.0, which aligns with the changes made in the main PR.

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐇 In the burrow where code does dwell,
Changes made, all is well.
Linting tools now shine so bright,
Tests refined, all feels right.
With each update, we hop and cheer,
For cleaner code, we hold so 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

codecov bot commented Nov 11, 2024

Codecov Report

Attention: Patch coverage is 88.88889% with 1 line in your changes missing coverage. Please review.

Project coverage is 82.72%. Comparing base (7126e48) to head (a97913b).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
middleware/cache/heap.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3196      +/-   ##
==========================================
- Coverage   82.76%   82.72%   -0.05%     
==========================================
  Files         114      114              
  Lines       11149    11149              
==========================================
- Hits         9228     9223       -5     
- Misses       1521     1525       +4     
- Partials      400      401       +1     
Flag Coverage Δ
unittests 82.72% <88.88%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

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

🧹 Outside diff range and nitpick comments (7)
middleware/cache/heap.go (1)

Line range hint 82-82: Remove unnecessary errcheck directive.

Similar to the Push method, the errcheck directive is unnecessary here as type assertions don't return an error value.

-	x := heap.Remove(h, realIdx).(heapEntry) //nolint:forcetypeassert,errcheck // Forced type assertion required to implement the heap.Interface interface
+	x := heap.Remove(h, realIdx).(heapEntry) //nolint:forcetypeassert // Forced type assertion required to implement the heap.Interface interface
🧰 Tools
🪛 golangci-lint

44-44: directive //nolint:forcetypeassert,errcheck // Forced type assertion required to implement the heap.Interface interface is unused for linter "errcheck"

(nolintlint)

🪛 GitHub Check: codecov/patch

[warning] 44-44: middleware/cache/heap.go#L44
Added line #L44 was not covered by tests

middleware/cache/manager.go (1)

Error handling should be implemented for storage operations in middleware packages

Based on the verification results, there are multiple instances of unhandled storage errors in middleware packages (cache, csrf, limiter) that need attention:

  • middleware/cache/manager.go: Unhandled errors in Get, Set, and Delete operations
  • middleware/csrf/storage_manager.go: Unhandled errors in Get, Set, and Delete operations
  • middleware/limiter/manager.go: Unhandled error in Set operation

The Storage interface in app.go clearly indicates that these operations can fail, and the main ctx.go properly handles storage errors, showing the expected pattern. The middleware implementations should follow the same approach.

🔗 Analysis chain

Line range hint 119-147: Consider implementing proper error handling for storage operations.

There's a pattern of unhandled errors in storage operations marked with TODO comments. These operations could fail in production (e.g., if using Redis/database storage) and the current implementation silently ignores such failures.

Let's verify the storage interface implementation to understand potential error scenarios:

Consider implementing one of these strategies:

  1. Bubble up errors to the caller for handling
  2. Add logging for storage failures
  3. Implement retry mechanisms for transient failures
  4. Add metrics/monitoring for storage operation failures

Would you like me to propose a specific implementation for any of these approaches?

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find the Storage interface definition and its implementations
ast-grep --pattern 'type Storage interface {
  $$$
}'

# Find all storage operation calls to see the error handling patterns
rg 'storage\.(Get|Set|Delete)' -A 2

Length of output: 3658

middleware/logger/default_logger.go (1)

34-34: Consider using a typed wrapper for atomic values

To improve type safety and eliminate the need for type assertions, consider creating a typed wrapper around atomic.Value specifically for string timestamps. This would move the type safety checks to initialization time rather than runtime.

Example approach for future consideration:

type AtomicString struct {
    value atomic.Value
}

func (a *AtomicString) Store(s string) {
    a.value.Store(s)
}

func (a *AtomicString) Load() string {
    return a.value.Load().(string)
}

Also applies to: 64-64

🧰 Tools
🪛 golangci-lint

34-34: directive //nolint:forcetypeassert,errcheck // Timestamp is always a string is unused for linter "errcheck"

(nolintlint)

middleware/adaptor/adaptor.go (1)

166-166: Consider a more robust error handling approach.

The current error handling uses direct type assertion which, while working, could be made more robust. Consider using errors.As for safer error type checking:

-		if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil && err.(*net.AddrError).Err == "missing port in address" { //nolint:errorlint,forcetypeassert // overlinting
+		if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil {
+			var addrErr *net.AddrError
+			if errors.As(err, &addrErr) && addrErr.Err == "missing port in address" {

This approach:

  • Eliminates the need for linting suppressions
  • Provides better type safety
  • Follows Go's error handling best practices
🧰 Tools
🪛 golangci-lint

166-166: directive //nolint:errorlint,forcetypeassert,errcheck // overlinting is unused for linter "errcheck"

(nolintlint)

client/hooks_test.go (1)

257-257: Remove unnecessary nolint directive

The //nolint:testifylint // test directive is unused and can be safely removed as the assertion is already using a recommended approach.

-		require.Equal(t, []byte(applicationJSON), req.RawRequest.Header.ContentType()) //nolint:testifylint // test
+		require.Equal(t, []byte(applicationJSON), req.RawRequest.Header.ContentType())
🧰 Tools
🪛 golangci-lint

257-257: directive //nolint:testifylint // test is unused for linter "testifylint"

(nolintlint)

middleware/logger/logger_test.go (1)

308-308: LGTM! More efficient test assertion.

The change improves the assertion by avoiding unnecessary string formatting when the test passes. The testify library handles the format string and arguments directly.

Consider applying this pattern to other test assertions in the codebase for consistency and efficiency.

ctx_test.go (1)

3552-3553: Enhance error assertion for unsupported JSON marshalling

Attempting to marshal a complex number with c.JSON(complex(1, 1)) will produce an error since complex numbers are not supported by JSON. Consider adding an assertion to check the specific error message to ensure accurate error handling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7126e48 and a97913b.

⛔ Files ignored due to path filters (1)
  • .github/workflows/linter.yml is excluded by !**/*.yml
📒 Files selected for processing (13)
  • Makefile (1 hunks)
  • client/hooks_test.go (5 hunks)
  • client/response_test.go (2 hunks)
  • ctx_test.go (5 hunks)
  • log/default.go (1 hunks)
  • middleware/adaptor/adaptor.go (1 hunks)
  • middleware/cache/heap.go (1 hunks)
  • middleware/cache/manager.go (1 hunks)
  • middleware/limiter/manager.go (1 hunks)
  • middleware/logger/default_logger.go (2 hunks)
  • middleware/logger/logger_test.go (2 hunks)
  • middleware/logger/tags.go (1 hunks)
  • router.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint
client/hooks_test.go

257-257: directive //nolint:testifylint // test is unused for linter "testifylint"

(nolintlint)


439-439: directive //nolint:testifylint // test is unused for linter "testifylint"

(nolintlint)

log/default.go

96-96: directive //nolint:forcetypeassert,errcheck // Keys must be strings is unused for linter "errcheck"

(nolintlint)

middleware/adaptor/adaptor.go

166-166: directive //nolint:errorlint,forcetypeassert,errcheck // overlinting is unused for linter "errcheck"

(nolintlint)

middleware/cache/heap.go

44-44: directive //nolint:forcetypeassert,errcheck // Forced type assertion required to implement the heap.Interface interface is unused for linter "errcheck"

(nolintlint)

middleware/limiter/manager.go

48-48: directive //nolint:forcetypeassert,errcheck // We store nothing else in the pool is unused for linter "errcheck"

(nolintlint)

middleware/logger/default_logger.go

34-34: directive //nolint:forcetypeassert,errcheck // Timestamp is always a string is unused for linter "errcheck"

(nolintlint)


64-64: directive //nolint:forcetypeassert,errcheck // Timestamp is always a string is unused for linter "errcheck"

(nolintlint)

middleware/logger/tags.go

203-203: directive //nolint:forcetypeassert,errcheck // We always store a string in here is unused for linter "errcheck"

(nolintlint)

router.go

237-237: directive //nolint:errcheck // It is fine to ignore the error here is unused for linter "errcheck"

(nolintlint)

🪛 GitHub Check: codecov/patch
middleware/cache/heap.go

[warning] 44-44: middleware/cache/heap.go#L44
Added line #L44 was not covered by tests

🔇 Additional comments (16)
Makefile (2)

38-38: Additional recommendations for linting tool update.

Since this is a linting tool update, please ensure:

  1. The new version has been tested locally to verify it doesn't introduce unexpected linting errors
  2. CI pipeline passes with the updated version
  3. Team is aware of any new linting rules introduced in v1.62.0

38-38: Verify golangci-lint version update.

The version bump from v1.61.0 to v1.62.0 looks good. Let's verify this is the latest stable version.

✅ Verification successful

Version update to golangci-lint v1.62.0 is verified and appropriate

The version bump from v1.61.0 to v1.62.0 is confirmed to be the latest stable release. The changelog shows primarily dependency updates and minor improvements, including:

  • New linters (iface, recvcheck)
  • Multiple dependency version bumps
  • Bug fixes for Go version detection and cross-compilation
  • No breaking changes identified
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify golangci-lint version is latest stable
# Expected: v1.62.0 should be the latest release

# Check the latest release tag
gh release view --repo golangci/golangci-lint --json tagName --jq .tagName

# Get the changelog for v1.62.0 to understand changes
gh release view v1.62.0 --repo golangci/golangci-lint --json body --jq .body

Length of output: 5798

middleware/cache/heap.go (1)

44-44: Add test coverage for heap interface implementation.

The Push method is part of the heap.Interface implementation but lacks test coverage. Consider adding tests to verify the correct behavior of the heap operations.

Would you like me to help generate comprehensive test cases for the heap operations?

🧰 Tools
🪛 golangci-lint

44-44: directive //nolint:forcetypeassert,errcheck // Forced type assertion required to implement the heap.Interface interface is unused for linter "errcheck"

(nolintlint)

🪛 GitHub Check: codecov/patch

[warning] 44-44: middleware/cache/heap.go#L44
Added line #L44 was not covered by tests

middleware/cache/manager.go (1)

53-53: LGTM: Appropriate linter directive for safe type assertion.

The addition of errcheck to the nolint directive is correct since the type assertion is safe here - the pool only stores *item objects via its New function.

middleware/logger/tags.go (1)

203-203: Verify the timestamp storage pattern.

The comment claims "We always store a string in here" for the timestamp. Let's verify this claim across the codebase to ensure the type assertion is indeed safe.

✅ Verification successful

Type assertion for Timestamp.Load() is safe

The timestamp handling pattern is consistent and safe throughout the codebase:

  • The Timestamp field is stored as atomic.Value in the Data struct
  • All stores are performed using time.Now().In(cfg.timeZoneLocation).Format(cfg.TimeFormat) which always returns a string
  • No other value types are stored in the Timestamp field

The comment "We always store a string in here" is accurate and the type assertion is safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all timestamp-related storage operations to verify the type consistency
echo "Searching for Timestamp storage patterns..."
rg -p "Timestamp\.Store\(" --type go

# Search for any potential timestamp type definitions
echo "Searching for Timestamp type definitions..."
ast-grep --pattern 'type $_ struct {
  $$$
  Timestamp $_
  $$$
}'

Length of output: 803


Script:

#!/bin/bash
# Let's check where and how Timestamp is being set
echo "Checking Timestamp initialization and storage..."
rg -p "Timestamp\." -B 3 -A 3 --type go

# Let's also check for any time-to-string conversions related to timestamp
echo "Checking time string formatting patterns..."
rg "time\." --type go | grep -i "format"

Length of output: 1696

🧰 Tools
🪛 golangci-lint

203-203: directive //nolint:forcetypeassert,errcheck // We always store a string in here is unused for linter "errcheck"

(nolintlint)

client/response_test.go (3)

378-378: LGTM! Improved JSON comparison in file path test.

The change from require.Equal to require.JSONEq is a good improvement as it properly handles JSON equality comparison, making the test more robust against formatting differences while still ensuring structural and value equality.


399-399: LGTM! Improved JSON comparison in io.Writer test.

Similarly, using require.JSONEq instead of require.Equal for the buffer content comparison is the correct approach for JSON validation.


378-378: Verify consistent JSON comparison updates across test files.

The changes to use JSONEq for JSON comparisons appear to be part of a broader effort to improve test assertions. Let's verify this pattern in other test files.

Also applies to: 399-399

✅ Verification successful

Let me check the actual JSON comparison patterns in these files to determine if they need similar updates.


No consistency issues found with JSON comparisons

The codebase shows appropriate usage of both require.Equal and require.JSONEq:

  • require.JSONEq is correctly used for comparing JSON content/responses
  • require.Equal is used for other cases like content-type headers, simple string comparisons, or array representations
  • The current usage in response_test.go follows the established pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other test files that might need similar JSON comparison updates
echo "Searching for potential JSON comparison patterns in tests..."
rg -l 'require\.Equal.*json' --type go --glob '*_test.go'

echo "Searching for existing JSONEq usage..."
rg -l 'require\.JSONEq' --type go --glob '*_test.go'

Length of output: 462


Script:

#!/bin/bash
# Check the actual JSON comparison patterns in test files
echo "Checking JSON comparisons in ctx_test.go..."
rg 'require\.Equal.*json|require\.JSONEq' -B2 -A2 ctx_test.go

echo -e "\nChecking JSON comparisons in helpers_test.go..."
rg 'require\.Equal.*json' -B2 -A2 helpers_test.go

echo -e "\nChecking JSON comparisons in client/hooks_test.go..."
rg 'require\.Equal.*json' -B2 -A2 client/hooks_test.go

echo -e "\nChecking JSON comparisons in client/client_test.go..."
rg 'require\.Equal.*json' -B2 -A2 client/client_test.go

echo -e "\nChecking JSON comparisons in client/request_test.go..."
rg 'require\.Equal.*json' -B2 -A2 client/request_test.go

Length of output: 4977

client/hooks_test.go (3)

300-301: LGTM! Improved assertion clarity

The change from require.True to require.Contains is a good improvement as it:

  • Provides more descriptive error messages on failure
  • Better expresses the intent of checking for substring presence

492-493: LGTM! Improved assertion clarity

The change from require.True to require.Contains enhances test readability and provides better error messages.


505-507: LGTM! Well-structured assertions

The changes improve the test by:

  • Using clearer require.Contains assertions
  • Separating checks for boundary, content, and form data into distinct assertions
middleware/logger/logger_test.go (1)

352-352: LGTM! Consistent with the previous change.

The assertion follows the same efficient pattern as the previous change, maintaining consistency across the test file.

ctx_test.go (4)

1192-1194: Approved: Correct expected XML output in test assertion

The test case correctly asserts the expected XML output generated by the AutoFormat function. The use of require.Equal is appropriate here.


3561-3563: Approved: Correct Content-Type header with custom content type

The test sets a custom content type application/problem+json. The assertions correctly verify that the response body and Content-Type header are as expected.


3615-3617: Approved: JSON serialization in benchmark test

The benchmark test correctly serializes the provided struct into JSON and asserts the output. The implementation is efficient and appropriate for benchmarking purposes.


3638-3640: Approved: Use of custom JSON encoder in test

The custom JSON encoder is effectively used to return a specific JSON output, and the test verifies this output correctly. This demonstrates proper customization of the JSON encoding process.

middleware/limiter/manager.go Show resolved Hide resolved
middleware/cache/heap.go Show resolved Hide resolved
middleware/logger/default_logger.go Show resolved Hide resolved
middleware/logger/default_logger.go Show resolved Hide resolved
log/default.go Show resolved Hide resolved
middleware/adaptor/adaptor.go Show resolved Hide resolved
middleware/logger/tags.go Show resolved Hide resolved
router.go Show resolved Hide resolved
client/hooks_test.go Show resolved Hide resolved
@gaby
Copy link
Member Author

gaby commented Nov 11, 2024

CodeRabbitAI is using golangci-lint 1.61.0 instead of 1.62.0

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: a97913b Previous: 7126e48 Ratio
Benchmark_Compress_Levels/Brotli_LevelBestCompression - B/op 6 B/op 0 B/op +∞
BenchmarkAppendMsgitem - MB/s 3224.49 MB/s 1846.77 MB/s 1.75

This comment was automatically generated by workflow using github-action-benchmark.

@ReneWerner87 ReneWerner87 merged commit dcdd2eb into main Nov 11, 2024
17 of 19 checks passed
@gaby gaby deleted the golangci-update branch November 16, 2024 04:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants