» Make grep CLI App in Go » 2. Development » 2.5 Add Lint

Add Lint

Lint refers to a tool or program that analyzes source code to find and report issues related to programming style, potential errors, and adherence to coding standards. The term "lint" originates from the name of a Unix utility called "lint" that was used to identify bugs and errors in C programming code.

Using linting tools in a Go project is a good practice for maintaining code quality and consistency. Linting tools analyze your code for potential errors, style issues, and adherence to coding standards.

There are several linting tools available for Go. Two popular ones are golangci-lint and Staticcheck. We'll use golangci-lint in this project since it's actually a Go linters aggregator.

Install it using:

# binary will be $(go env GOPATH)/bin/golangci-lint
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.55.2

golangci-lint --version

Know more about its installation at: https://golangci-lint.run/usage/install/

Create a file named .golangci.yml in the project's root directory. It's used as the configuration for golangci-lint.

.golangci.yml:

linters:
  enable:
    - deadcode
    - errcheck
    - goimports
    - golint
    - govet
    - ineffassign
    - staticcheck
    - structcheck
    - typecheck
    - unused
    - lll

# Custom Configuration for Some Linters
linters-settings:
  govet:
    check-shadowing: true
  golint:
    min-confidence: 0.8

# Exclude some generated files or directories
exclude:
  - vendor/
  - generated/

# Settings for golangci-lint
golangci-lint:
  build:
    tags: testing

And then run it:

golangci-lint run

You will get a list of lint issues:

pkg/grep/search.go:68:15: Error return value of `filepath.Walk` is not checked (errcheck)
        filepath.Walk(directoryPath, func(filePath string, info os.FileInfo, err error) error {
                     ^

Try to fix all of them and run golangci-lint again.

golangci-lint run

If nothing pops out, your code is in "good style" now.

Changes in pkg/grep/search.go:

@@ -65,7 +65,7 @@ func GrepCount(result MatchResult) int {
 
 func GrepRecursive(pattern string, directoryPath string, options *Options) (MatchResult, error) {
        results := make(MatchResult)
-       filepath.Walk(directoryPath, func(filePath string, info os.FileInfo, err error) error {
+       err := filepath.Walk(directoryPath, func(filePath string, info os.FileInfo, err error) error {
                if err != nil {
                        return nil
                }
@@ -79,6 +79,9 @@ func GrepRecursive(pattern string, directoryPath string, options *Options) (Matc
                }
                return nil
        })
+       if err != nil {
+               return nil, err
+       }
        return results, nil
 }
PrevNext