Skip to content

Fix lint #85

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Fix lint #85

wants to merge 1 commit into from

Conversation

harisudarsan1
Copy link

@harisudarsan1 harisudarsan1 commented Apr 29, 2025

What this PR introduces:

  1. It removes the incorrect linters like gofmt.
  2. It fixes lint errors specifically due to errcheck linter and excludes the IO.close calls
  3. Revive linter is disabled because of many lint errors(around 50) due to revive
  4. Fixes staticcheck errors like applying demorgans law

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling across various commands and components, ensuring that errors during file operations, HTTP response handling, and external command execution are now properly captured and reported.
    • Enhanced test reliability by explicitly checking for errors during iteration steps in tests.
  • Documentation
    • Added and improved documentation comments for several exported functions, structs, and packages to clarify their purpose and usage.
  • Refactor
    • Refactored conditional logic for improved clarity and maintainability in select functions.
    • Updated configuration and linter settings for better code quality enforcement.
  • Style
    • Adjusted code to explicitly discard unused return values, reducing warnings and improving code clarity.

Signed-off-by: Harisudarsan <[email protected]>
Copy link

coderabbitai bot commented Apr 29, 2025

Walkthrough

This set of changes primarily introduces improved error handling, explicit resource cleanup, and enhanced documentation across various components. Several functions now check and propagate errors that were previously ignored, especially for file operations, HTTP response body closures, and command executions. Configuration files and code comments were updated for clarity and maintainability. Some code blocks were refactored for readability, such as switching from chained if-else statements to switch cases. Additionally, linter settings were updated to refine static analysis behavior, and minor logic adjustments were made to validation checks.

Changes

File(s) Change Summary
.golangci.yml Updated linter configuration: enabled/disabled specific linters, added settings for errcheck, and updated govet settings.
cmd/query.go Modified fetchData to propagate errors from copying response body to stdout for non-JSON output.
cmd/tail.go Added error handling for JSON serialization in record printing.
main.go Added error handling for version printing, propagating or logging errors as appropriate.
pkg/config/config.go Added comments to exported methods; improved error handling for file close in WriteConfigToFile.
pkg/helm/helm.go Added error handling for repoAdd and file lock unlock; updated chart path lookup method.
pkg/http/http.go Added documentation comments to exported struct and function.
pkg/installer/installer.go Refactored if-else to switch; added error handling for TCP close, process kill, and browser command execution.
pkg/iterator/iterator.go Added package-level comment.
pkg/iterator/iterator_test.go Added error checks in iteration; simplified time equality checks.
pkg/model/defaultprofile/profile.go
pkg/model/timerange.go
Explicitly discarded return values from fmt.Fprint to avoid unused variable warnings.
pkg/model/query.go
pkg/model/savedQueries.go
Replaced defer resp.Body.Close() with error-checked deferred functions for HTTP response body closure.
pkg/model/role/role.go Updated Valid() logic for roles to use explicit conjunction of negations.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant HTTPServer

    User->>CLI: Run command (e.g., fetchData, version, tail)
    CLI->>HTTPServer: Make HTTP request (if applicable)
    HTTPServer-->>CLI: Respond with data
    CLI->>CLI: Handle response (decode, print, etc.)
    CLI->>CLI: Check for errors (file close, copy, process, etc.)
    alt Error occurs
        CLI->>User: Print/log error, exit or propagate
    else Success
        CLI->>User: Output result
    end
Loading

Poem

In burrows deep, where code does dwell,
The rabbits checked each error well.
With comments clear and linter’s might,
They tidied up both left and right.
Now every close and print and call,
Gets handled safe—no bug too small!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in 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.

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

@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 (4)
.golangci.yml (1)

19-19: Added nilnesserr linter.

Good addition of the nilnesserr linter to catch nil error returns. However, there's a trailing space at the end of this line.

-    - nilnesserr 
+    - nilnesserr
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 19-19: trailing spaces

(trailing-spaces)

pkg/config/config.go (1)

116-116: Improved function documentation, but contains a typo.

The comment helpfully explains the function's purpose, but contains a typo - "retrurns" should be "returns".

-// GetProfile retrurns the parseable profile by reading the config
+// GetProfile returns the parseable profile by reading the config
pkg/installer/installer.go (1)

903-906: Added proper error handling for command execution.

Good improvement to error handling by checking and handling errors from the cmd.Start() call. Note that the error handling is a bit severe - it calls log.Fatalf which will terminate the program. Consider whether a less drastic approach might be appropriate here.

Consider using a less severe error handling approach instead of log.Fatalf:

-	err := cmd.Start()
-	if err != nil {
-		log.Fatalf("could not be be able to start the command %v", err)
-	}
+	err := cmd.Start()
+	if err != nil {
+		fmt.Printf("could not start the browser command: %v\n", err)
+		// Continue execution as the browser opening is not critical
+	}
main.go (1)

306-311: Enhanced error handling in version command.

The version command now properly checks for errors from pb.PrintVersion and handles them accordingly by printing an error message and exiting with a non-zero status code. This ensures that errors aren't silently ignored.

However, the error message suggests it failed to write to a file, which may be misleading as PrintVersion can fail for various reasons (fetching server information, JSON marshaling, etc.).

-			fmt.Printf("failed to write to file %v\n", err)
+			fmt.Printf("failed to print version information: %v\n", err)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b60e374 and 27d7c34.

📒 Files selected for processing (15)
  • .golangci.yml (1 hunks)
  • cmd/query.go (1 hunks)
  • cmd/tail.go (1 hunks)
  • main.go (2 hunks)
  • pkg/config/config.go (3 hunks)
  • pkg/helm/helm.go (3 hunks)
  • pkg/http/http.go (1 hunks)
  • pkg/installer/installer.go (4 hunks)
  • pkg/iterator/iterator.go (1 hunks)
  • pkg/iterator/iterator_test.go (10 hunks)
  • pkg/model/defaultprofile/profile.go (1 hunks)
  • pkg/model/query.go (1 hunks)
  • pkg/model/role/role.go (1 hunks)
  • pkg/model/savedQueries.go (3 hunks)
  • pkg/model/timerange.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
pkg/installer/installer.go (1)
pkg/installer/model.go (4)
  • LocalStore (45-45)
  • S3Store (43-43)
  • BlobStore (47-47)
  • GcsStore (49-49)
pkg/http/http.go (1)
pkg/config/config.go (1)
  • Profile (51-55)
main.go (1)
cmd/version.go (1)
  • PrintVersion (57-101)
🪛 YAMLlint (1.35.1)
.golangci.yml

[error] 19-19: trailing spaces

(trailing-spaces)

🔇 Additional comments (32)
pkg/iterator/iterator.go (1)

17-17: Good documentation addition!

Adding package documentation comments is a best practice in Go and helps users understand the purpose of the package. This comment provides clear context for the iterator package.

pkg/model/defaultprofile/profile.go (1)

82-82: Good error handling fix

Explicitly discarding the return values from fmt.Fprint using blank identifiers (_, _) satisfies the errcheck linter. This indicates that you're intentionally ignoring these values rather than accidentally forgetting to check them.

pkg/model/timerange.go (1)

83-83: Good error handling fix

Explicitly discarding the return values from fmt.Fprint using blank identifiers (_, _) satisfies the errcheck linter. This indicates that you're intentionally ignoring these values rather than accidentally forgetting to check them.

pkg/http/http.go (2)

27-27: Good documentation addition

Adding documentation for exported types is a Go best practice. This comment clearly explains the purpose of the HTTPClient struct.


33-33: Good documentation addition

Adding documentation for exported functions is a Go best practice. This comment clearly explains what the DefaultClient function does.

pkg/model/role/role.go (1)

68-68: Good application of De Morgan's law

This change makes the validation logic more explicit and readable by using a conjunction of negations instead of a negation of a disjunction. The logic is equivalent but clearer:

  • Before (implied): return !(strings.Contains(m.Stream.Value(), " ") || m.Stream.Value() == "")
  • After: return !strings.Contains(m.Stream.Value(), " ") && m.Stream.Value() != ""

This makes it immediately obvious that the stream value must not contain spaces AND must not be empty.

pkg/model/savedQueries.go (3)

125-125: Explicitly discard fmt.Fprint return values to satisfy linter.

Good change to explicitly discard the return values from fmt.Fprint using _, _. This prevents lint warnings about unused return values while making it clear that these values are intentionally ignored.


324-328: Improved error handling for HTTP response body closure.

Excellent change to check for errors when closing the response body. Following best practices, the deferred anonymous function now properly logs any errors that might occur during cleanup, preventing silent failures.


396-400: Improved error handling for HTTP response body closure.

Good implementation of proper error checking when closing the response body, consistent with the earlier change in this file. This pattern ensures resource cleanup issues are properly logged.

pkg/helm/helm.go (5)

97-100: Fixed error handling for repoAdd call.

Good improvement to properly check and propagate errors from the repoAdd function. Previously, errors were being ignored, which could lead to silent failures and difficult-to-debug issues.


104-104: Updated chart location method call.

The change from using client.ChartPathOptions.LocateChart to client.LocateChart looks like an API update or improvement. This is a good change as it likely uses a more direct method.


164-168: Added error handling for file unlocking.

Good improvement to check for errors when unlocking the file. This prevents silent failures during resource cleanup operations, which is important for maintaining system integrity.


322-325: Fixed error handling for repoAdd call.

Good improvement to properly check and propagate errors from the repoAdd function in the Upgrade method, consistent with the earlier change in the Apply method.


330-330: Updated chart location method call.

The change from using client.ChartPathOptions.LocateChart to client.LocateChart is consistent with the earlier similar change in the Apply method.

pkg/iterator/iterator_test.go (4)

92-93: Simplified conditional check.

Good readability improvement by using != instead of !(x == y). The new expression is more straightforward and less error-prone.


101-104: Added error checking for iterator operations.

Great improvement to check for errors returned by iter.Next(). Previously, errors were ignored, but now they're properly checked and will cause the test to fail with a clear error message if there's an issue during iteration.

Also applies to: 121-124, 133-136, 145-148


166-169: Added error checking for iterator operations in descending test.

This change is consistent with the earlier improvements in the ascending test, ensuring that errors during iteration are properly caught and reported.

Also applies to: 186-189, 198-201, 210-213


229-229: Simplified conditional check.

Good readability improvement by using != instead of !(x == y), making the code more straightforward and cleaner.

.golangci.yml (4)

1-2: Updated to linter configuration version 2.

Good update to use the newer version of the golangci-lint configuration format.


5-11: Added errcheck exclusions for specific functions.

Good configuration to exclude specific functions from error checking. This is a pragmatic approach that focuses linting on important error checks while excluding cases where errors are typically safe to ignore (like io.Closer.Close).


15-15: Disabled revive linter.

As mentioned in the PR objectives, the revive linter was disabled due to a large number of lint errors (approximately 50) reported by it. This is a reasonable approach to incrementally improve code quality.


24-26: Enabled typecheck in govet.

Good configuration to explicitly enable typecheck in govet. This ensures type-related issues are caught during linting.

pkg/config/config.go (2)

57-57: Improved documentation with method purpose.

The added comment clearly explains the purpose of the GrpcAddr method, which helps with code clarity and documentation.


82-86: Properly handle file close errors.

Good improvement to error handling by checking and logging any errors that occur during file closing. This follows Go best practices and addresses potential "errcheck" linter errors.

pkg/installer/installer.go (3)

275-284: Improved code organization with switch statement.

Replacing the if-else chain with a switch statement improves code readability and maintainability. This is a good refactoring choice given the distinct cases for different store types.


871-874: Added proper error handling for connection closure.

Good improvement to error handling by checking and returning any errors that occur when closing the TCP connection. This addresses potential "errcheck" linter issues.


883-886: Added proper error handling for process termination.

Good improvement to error handling by checking and returning any errors that occur when killing the kubectl process. This addresses potential "errcheck" linter issues.

cmd/tail.go (1)

91-94: Added proper error handling for JSON conversion.

Good improvement to error handling by checking and returning any errors from the array.RecordToJSON function. This addresses potential "errcheck" linter issues and prevents the program from continuing with invalid data.

pkg/model/query.go (1)

555-559: Properly handle response body close errors.

Good improvement to error handling by checking and logging any errors that occur during response body closing. This follows Go best practices and addresses potential "errcheck" linter errors.

cmd/query.go (2)

146-147: Added proper formatting and maintained clear return path.

The addition of this blank line improves code readability by visually separating the print statement from the return statement.


149-150: Improved error handling for io.Copy operation.

The function now properly captures and returns any errors from copying the response body to stdout, rather than silently ignoring them. This change aligns with the PR's goal of fixing issues reported by the errcheck linter.

main.go (1)

61-62: Improved error handling for version printing.

The code now properly captures and returns any errors from pb.PrintVersion rather than ignoring them. This is consistent with the PR's goal of addressing errcheck linter issues.

@nitisht
Copy link
Member

nitisht commented Apr 29, 2025

Thanks @harisudarsan1 let me check this out

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.

2 participants