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

Add GolangCI Lint Configuration for Better Code Quality #1078

Merged
merged 5 commits into from
Feb 20, 2025
Merged

Add GolangCI Lint Configuration for Better Code Quality #1078

merged 5 commits into from
Feb 20, 2025

Conversation

osterman
Copy link
Member

@osterman osterman commented Feb 19, 2025

what

This PR improves our golangci-lint configuration to enforce better coding standards, catch common mistakes, and ensure consistency in our Go codebase.

  • Function Length Enforcement (funlen)

    • Limits functions to 50 lines to improve readability and maintainability.
  • Forbidden Function Calls (forbidigo)

    • Allows blocking specific function calls (e.g., deprecated logging functions).
  • Enabling Additional Linters

    • gocritic: Adds several static analysis checks for code quality.
    • errcheck: Ensures all errors are properly handled.
    • gofumpt: Standardizes formatting beyond gofmt.
    • govet: Detects suspicious constructs.
    • staticcheck: Flags performance and correctness issues.
    • revive: A configurable linter for Go.
    • misspell: Detects common spelling mistakes.
  • Custom gocritic Checks

    • Enables key rules such as:
      • rangeValCopy: Detects unnecessary copies in range loops.
      • hugeParam: Warns on large parameters that should be passed by reference.
      • commentedOutCode: Finds commented-out code blocks.
      • nestingReduce: Suggests ways to reduce nesting complexity.
      • preferFilepathJoin: Enforces using filepath.Join() instead of manual concatenation.
  • Excludes Test Files from Function Length Check (funlen)

    • Test files (_test.go) are ignored for function length enforcement.
  • Output Formatting Improved

    • Uses colored-line-number format for better readability in logs.

Why

  • Prevents oversized functions, making code easier to read and refactor.
  • Ensures error handling is not skipped, improving reliability.
  • Standardizes code formatting across the team.
  • Detects common pitfalls like unnecessary copies, deep nesting, and improper path handling.

Summary by CodeRabbit

  • Chore
    • Added an automated linting job to the CI workflow.
    • Updated the package management configuration to include the "golangci-lint" tool.
  • Refactor
    • Improved the logging system for greater clarity and consistency, with legacy log methods now deprecated.
  • New Features
    • Introduced a new configuration for enhanced code quality checks with multiple linters.

@osterman osterman requested a review from a team as a code owner February 19, 2025 23:02
Copy link

mergify bot commented Feb 19, 2025

Important

Cloud Posse Engineering Team Review Required

This pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes.

To expedite this process, reach out to us on Slack in the #pr-reviews channel.

@mergify mergify bot added triage Needs triage needs-cloudposse Needs Cloud Posse assistance labels Feb 19, 2025
@samtholiya
Copy link
Collaborator

Let us add the makefile command for easy access on local dev environment

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new GitHub Actions job to run golangci-lint in the CI pipeline, add a dependency for golangci-lint in the Brewfile for Homebrew installations, and update the logging module in the Go code. In the logging file, the alias has been updated from l to log with related functions marked as deprecated. The overall control flow remains consistent while enhancing clarity and integration of linting and logging practices.

Changes

File(s) Change Summary
.github/.../test.yml Added new job lint-golangci running on ubuntu-latest with steps for checking out the repository (using actions/checkout@v4 with full history) and running golangci-lint (using reviewdog/action-golangci-lint@v2).
Brewfile Added dependency entry for brew "golangci-lint".
pkg/.../log_utils.go Updated logging alias from l to log in various functions and marked several functions as deprecated in favor of the new logging methods.
.golangci.yml Added configuration for golangci-lint, including settings for linters, timeouts, and output format.

Suggested labels

minor, patch

Possibly related PRs

  • ci: format Go code by autofix.ci #991: The changes in the main PR, which introduce a new linting job in the GitHub Actions workflow, are related to the retrieved PR that also involves modifications to GitHub Actions workflows, specifically for formatting Go code, indicating a focus on code quality and consistency in CI processes.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e84cb7b and 6c1b5ec.

📒 Files selected for processing (1)
  • .golangci.yml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: runner / golangci-lint
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (7)
.golangci.yml (7)

1-3: Header Comments and Documentation

The header provides clear context and links directly to the official configuration documentation. This introductory section is concise and informative.


4-7: Lint Run Configuration

The run section is set up nicely with a 5-minute timeout, and including test files in the analysis is well noted. Later exclusion rules ensure that only the relevant parts (like funlen) ignore tests, so overall this configuration balances thoroughness with practicality.


8-19: Enabled Linters

The list of linters enabled—such as funlen, forbidigo, gocritic, and others—is comprehensive and clearly targets multiple aspects of code quality. This setup aligns very well with our objectives to improve maintainability and error detection.


20-23: Function Length Enforcement

The configuration for the funlen linter, limiting functions to 50 lines, is exactly in line with our objectives. This promotes readability and keeps functions focused and manageable.


24-37: Custom gocritic Checks

The custom checks under the gocritic settings do a solid job of targeting common pitfalls:

  • Checks like rangeValCopy and hugeParam help prevent performance issues.
  • The rules addressing commented-out code, empty declarations, and proper usage of filepath.Join() are well chosen.

This detailed configuration should help the team catch subtle issues during code reviews.


38-43: Test File Exclusion Rule

Excluding test files from the funlen check by targeting _test.go is a smart choice since test files can often be longer without harming production code quality. This exclusion helps reduce false positives and maintain focus on critical files.


44-47: Enhanced Output Formatting

The output configuration using colored-line-number enhances readability significantly by making it easier to locate problematic lines in logs. This small but effective tweak will certainly help during reviews.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 or @auto-summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @auto-title 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.

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

🔭 Outside diff range comments (1)
.github/workflows/test.yml (1)

492-499: ⚠️ Potential issue

Update release job dependencies.

The release job's needs section should include the new 'lint-golangci' job.

Apply this change:

  release:
-   needs: [test, lint, mock, k3s, localstack, docker, validate]
+   needs: [test, lint, mock, k3s, localstack, docker, validate, lint-golangci]
    if: github.event_name == 'push'
    uses: cloudposse/.github/.github/workflows/shared-go-auto-release.yml@main
    with:
      publish: false
      format: binary
🧹 Nitpick comments (2)
pkg/utils/log_utils.go (1)

32-86: Consider consolidating deprecated functions.

While marking functions as deprecated is good practice, consider consolidating these utility functions into a single deprecated wrapper that internally calls the new logging functions. This would reduce code duplication and make future removal easier.

Example consolidation:

// Deprecated: Use the log package directly. These utilities will be removed in a future release.
type DeprecatedLogger struct{}

func (d DeprecatedLogger) PrintErrorInColor(message string) {
    messageColor := theme.Colors.Error
    _, _ = messageColor.Fprint(os.Stderr, message)
}

func (d DeprecatedLogger) LogErrorAndExit(err error) {
    log.Error(err)
    var exitError *exec.ExitError
    if errors.As(err, &exitError) {
        os.Exit(exitError.ExitCode())
    }
    os.Exit(1)
}

// ... other methods ...

// Provide a single instance
var Legacy = DeprecatedLogger{}
.github/workflows/test.yml (1)

480-491: Consider optimizing the lint job configuration.

The lint job setup looks good, but a few optimizations could be made:

  1. Full history fetch might not be necessary for linting
  2. Consider adding a configuration file path

Suggested changes:

  lint-golangci:
    name: runner / golangci-lint
    runs-on: ubuntu-latest
    steps:
      - name: Check out code into the Go module directory
        uses: actions/checkout@v4
-       with:
-         fetch-depth: 0

      - name: Lint with golangci-lint
        uses: reviewdog/action-golangci-lint@v2
+       with:
+         golangci_lint_flags: "--config=.golangci.yml"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between baaf8c1 and e84cb7b.

📒 Files selected for processing (3)
  • .github/workflows/test.yml (1 hunks)
  • Brewfile (1 hunks)
  • pkg/utils/log_utils.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: [mock-macos] tests/fixtures/scenarios/complete
  • GitHub Check: [mock-macos] examples/demo-vendoring
  • GitHub Check: [mock-windows] tests/fixtures/scenarios/complete
  • GitHub Check: [mock-windows] examples/demo-vendoring
  • GitHub Check: [mock-windows] examples/demo-context
  • GitHub Check: [mock-windows] examples/demo-component-versions
  • GitHub Check: [mock-linux] examples/demo-vendoring
  • GitHub Check: [localstack] demo-localstack
  • GitHub Check: Acceptance Tests (macos-latest, macos)
  • GitHub Check: Acceptance Tests (windows-latest, windows)
  • GitHub Check: Acceptance Tests (ubuntu-latest, linux)
  • GitHub Check: [k3s] demo-helmfile
  • GitHub Check: Summary
🔇 Additional comments (2)
Brewfile (1)

2-2: LGTM! Adding golangci-lint dependency.

The addition of golangci-lint to the Brewfile ensures consistent linting tooling across development environments.

pkg/utils/log_utils.go (1)

10-10: LGTM! More descriptive package alias.

Changed from 'l' to 'log' which improves code readability.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 19, 2025
@mergify mergify bot removed the triage Needs triage label Feb 19, 2025
@aknysh aknysh added the no-release Do not create a new release (wait for additional code changes) label Feb 19, 2025
aknysh
aknysh previously approved these changes Feb 19, 2025
Copy link
Member

@aknysh aknysh left a comment

Choose a reason for hiding this comment

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

LGTM

@samtholiya
Copy link
Collaborator

Looking at timeout error for golang-ci.
I realised
Considering The repo is growing a lot we should split website and cli if possible.
Let me know if we have any particular reason to keep it together apart from we ship website and change together.
But that can be done in seperate repositories as well

@osterman
Copy link
Member Author

We definitely do not want to break website out. It's critical that every new feature is documented, and that doesn't happen when it requires 2 PRs.

Can you elaborate on the problem?

@samtholiya
Copy link
Collaborator

samtholiya commented Feb 20, 2025

We definitely do not want to break website out. It's critical that every new feature is documented, and that doesn't happen when it requires 2 PRs.

Agreed

Can you elaborate on the problem?

I mean the problem is not so critical to be solved it was just more of linters, file watchers load reduction. But we have workarounds for that so all good.

@osterman osterman dismissed stale reviews from aknysh and coderabbitai[bot] via 6c1b5ec February 20, 2025 01:42
@aknysh aknysh merged commit 846e2f0 into main Feb 20, 2025
46 checks passed
@aknysh aknysh deleted the golint branch February 20, 2025 02:27
@mergify mergify bot removed the needs-cloudposse Needs Cloud Posse assistance label Feb 20, 2025
@osterman
Copy link
Member Author

To run it locally, do one of:

Lint files that have changed (for me it erroneously includes unstaged files)

golangci-lint run --new-from-rev=HEAD`

Lint only go files in VCS:

git ls-files '*.go' | xargs -n1 dirname | sort -u | xargs golangci-lint run

Note, we have a lot of clean up to do.

Copy link

These changes were released in v1.163.0.

@coderabbitai coderabbitai bot mentioned this pull request Feb 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-release Do not create a new release (wait for additional code changes)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants