Skip to content

Commit d932d50

Browse files
nrwiersmamanugupt1
andauthored
chore: lint code with golangci-lint (#1828)
* feat: add golangci-lint linting * chore: fix linter issues * feat: add linting into the workflow * docs: update lint docs * fix: cr suggestions * fix: remove old formatting and vetting scripts * fix: add docker make target * fix: action go caching * fix: depreciated actions checkout version * fix: cr suggestion * fix: cr suggestions --------- Co-authored-by: Manu Gupta <[email protected]>
1 parent 66582ee commit d932d50

File tree

134 files changed

+596
-600
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

134 files changed

+596
-600
lines changed

.github/workflows/ci.yml

+13-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@ on:
33
- push
44
- pull_request
55
jobs:
6+
lint:
7+
runs-on: ubuntu-latest
8+
steps:
9+
- uses: actions/checkout@v3
10+
- name: Set up Go
11+
uses: actions/setup-go@v3
12+
with:
13+
go-version-file: 'go.mod'
14+
cache: true
15+
- name: Lint code
16+
run: make lint-docker
17+
618
build:
719
env:
820
ATHENS_MONGO_STORAGE_URL: mongodb://localhost:27017
@@ -53,7 +65,7 @@ jobs:
5365
with:
5466
go-version-file: 'go.mod'
5567
cache: true
56-
- name: Run linter
68+
- name: Verify changes
5769
run: make verify
5870
- name: Unit tests
5971
run: go test -v -race ./...

.golangci.yml

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
run:
2+
tests: false
3+
timeout: 5m
4+
5+
linters-settings:
6+
cyclop:
7+
max-complexity: 12
8+
skip-tests: true
9+
gofumpt:
10+
extra-rules: true
11+
12+
linters:
13+
enable-all: true
14+
disable:
15+
- interfacer # deprecated
16+
- scopelint # deprecated
17+
- maligned # deprecated
18+
- golint # deprecated
19+
- structcheck # deprecated
20+
- deadcode # deprecated
21+
- varcheck # deprecated
22+
- nosnakecase # deprecated
23+
- ifshort # deprecated
24+
- errchkjson
25+
- exhaustive
26+
- exhaustivestruct
27+
- exhaustruct
28+
- forcetypeassert
29+
- funlen
30+
- gochecknoglobals
31+
- gochecknoinits
32+
- goconst
33+
- godox
34+
- goerr113
35+
- gomnd
36+
- ireturn
37+
- lll
38+
- musttag
39+
- nilnil
40+
- nlreturn
41+
- nonamedreturns
42+
- tagliatelle
43+
- varnamelen
44+
- wrapcheck
45+
- wsl
46+
- cyclop # TODO: turn this back on later
47+
- gocognit # TODO: turn this back on later
48+
- forbidigo # TODO: turn this back on later
49+
50+
issues:
51+
exclude-use-default: false
52+
exclude:
53+
- 'package-comments: should have a package comment'
54+
- 'ST1000: at least one file in a package should have a package comment'
55+
- 'G204: Subprocess launched with a potential tainted input or cmd arguments'
56+
- 'G204: Subprocess launched with variable'
57+
- 'G402: TLS MinVersion too low.'
58+
- 'const `op` is unused'
59+
exclude-rules:
60+
- path: cmd/proxy/main.go
61+
text: 'G108: Profiling endpoint is automatically exposed on /debug/pprof'
62+
- path: pkg/stash/stasher.go
63+
linters:
64+
- contextcheck
65+
- path: pkg/stash/with_azureblob.go # False positive
66+
linters:
67+
- bodyclose
68+
- path: pkg/storage/azureblob/azureblob.go # False positive
69+
linters:
70+
- bodyclose
71+
- path: pkg/storage/compliance/*
72+
linters:
73+
- thelper
74+
- gosec
75+
- errcheck
76+
- path: pkg/index/compliance/*
77+
linters:
78+
- thelper
79+
- gosec
80+
- errcheck

DEVELOPMENT.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -234,10 +234,10 @@ Then open [http://localhost:1313](http://localhost:1313/).
234234

235235
# Linting
236236

237-
In our CI/CD pass, we use govet, so feel free to run it locally beforehand:
237+
In our CI/CD pass, we use golangci-lint, so feel free to run it locally beforehand:
238238

239239
```
240-
go vet ./...
240+
make lint
241241
```
242242

243243
# For People Doing a Release

Makefile

+10-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
VERSION = "unset"
22
DATE=$(shell date -u +%Y-%m-%d-%H:%M:%S-%Z)
33

4+
GOLANGCI_LINT_VERSION=v1.51.2
5+
46
ifndef GOLANG_VERSION
57
override GOLANG_VERSION = 1.19
68
endif
@@ -43,10 +45,16 @@ docs: ## build the docs docker image
4345
setup-dev-env:
4446
$(MAKE) dev
4547

48+
.PHONY: lint
49+
lint:
50+
@golangci-lint run ./...
51+
52+
.PHONY: lint-docker
53+
lint-docker:
54+
@docker run -t --rm -v $(CURDIR):/app -w /app golangci/golangci-lint:$(GOLANGCI_LINT_VERSION) golangci-lint run ./...
55+
4656
.PHONY: verify
4757
verify: ## verify athens codebase
48-
./scripts/check_gofmt.sh
49-
./scripts/check_govet.sh
5058
./scripts/check_deps.sh
5159
./scripts/check_conflicts.sh
5260

cmd/proxy/actions/app.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import (
1616
"go.opencensus.io/plugin/ochttp"
1717
)
1818

19-
// Service is the name of the service that we want to tag our processes with
19+
// Service is the name of the service that we want to tag our processes with.
2020
const Service = "proxy"
2121

2222
// App is where all routes and middleware for the proxy
@@ -126,7 +126,7 @@ func App(conf *config.Config) (http.Handler, error) {
126126

127127
store, err := GetStorage(conf.StorageType, conf.Storage, conf.TimeoutDuration(), client)
128128
if err != nil {
129-
err = fmt.Errorf("error getting storage configuration (%s)", err)
129+
err = fmt.Errorf("error getting storage configuration: %w", err)
130130
return nil, err
131131
}
132132

@@ -140,7 +140,7 @@ func App(conf *config.Config) (http.Handler, error) {
140140
lggr,
141141
conf,
142142
); err != nil {
143-
err = fmt.Errorf("error adding proxy routes (%s)", err)
143+
err = fmt.Errorf("error adding proxy routes: %w", err)
144144
return nil, err
145145
}
146146

cmd/proxy/actions/app_proxy.go

+6-5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package actions
22

33
import (
44
"context"
5+
"errors"
56
"fmt"
67
"net/http"
78
"net/url"
@@ -54,7 +55,7 @@ func addProxyRoutes(
5455
}
5556
supportPath := path.Join("/sumdb", sumdbURL.Host, "/supported")
5657
r.HandleFunc(supportPath, func(w http.ResponseWriter, r *http.Request) {
57-
w.WriteHeader(200)
58+
w.WriteHeader(http.StatusOK)
5859
})
5960
sumHandler := sumdbProxy(sumdbURL, c.NoSumPatterns)
6061
pathPrefix := "/sumdb/" + sumdbURL.Host
@@ -63,7 +64,7 @@ func addProxyRoutes(
6364
)
6465
}
6566

66-
// Download Protocol
67+
// Download Protocol:
6768
// the download.Protocol and the stash.Stasher interfaces are composable
6869
// in a middleware fashion. Therefore you can separate concerns
6970
// by the functionality: a download.Protocol that just takes care
@@ -142,13 +143,13 @@ func getSingleFlight(l *log.Logger, c *config.Config, checker storage.Checker) (
142143
return stash.WithSingleflight, nil
143144
case "etcd":
144145
if c.SingleFlight == nil || c.SingleFlight.Etcd == nil {
145-
return nil, fmt.Errorf("Etcd config must be present")
146+
return nil, errors.New("etcd config must be present")
146147
}
147148
endpoints := strings.Split(c.SingleFlight.Etcd.Endpoints, ",")
148149
return stash.WithEtcd(endpoints, checker)
149150
case "redis":
150151
if c.SingleFlight == nil || c.SingleFlight.Redis == nil {
151-
return nil, fmt.Errorf("Redis config must be present")
152+
return nil, errors.New("redis config must be present")
152153
}
153154
return stash.WithRedisLock(
154155
&athensLoggerForRedis{logger: l},
@@ -158,7 +159,7 @@ func getSingleFlight(l *log.Logger, c *config.Config, checker storage.Checker) (
158159
c.SingleFlight.Redis.LockConfig)
159160
case "redis-sentinel":
160161
if c.SingleFlight == nil || c.SingleFlight.RedisSentinel == nil {
161-
return nil, fmt.Errorf("Redis config must be present")
162+
return nil, errors.New("redis config must be present")
162163
}
163164
return stash.WithRedisSentinelLock(
164165
&athensLoggerForRedis{logger: l},

cmd/proxy/actions/auth.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ func initializeAuthFile(path string) {
1919
return
2020
}
2121

22-
fileBts, err := os.ReadFile(path)
22+
fileBts, err := os.ReadFile(filepath.Clean(path))
2323
if err != nil {
2424
log.Fatalf("could not read %s: %v", path, err)
2525
}
@@ -31,7 +31,7 @@ func initializeAuthFile(path string) {
3131

3232
fileName := transformAuthFileName(filepath.Base(path))
3333
rcp := filepath.Join(hdir, fileName)
34-
if err := os.WriteFile(rcp, fileBts, 0600); err != nil {
34+
if err := os.WriteFile(rcp, fileBts, 0o600); err != nil {
3535
log.Fatalf("could not write to file: %v", err)
3636
}
3737
}
@@ -45,7 +45,7 @@ func netrcFromToken(tok string) {
4545
log.Fatalf("netrcFromToken: could not get homedir: %v", err)
4646
}
4747
rcp := filepath.Join(hdir, getNETRCFilename())
48-
if err := os.WriteFile(rcp, []byte(fileContent), 0600); err != nil {
48+
if err := os.WriteFile(rcp, []byte(fileContent), 0o600); err != nil {
4949
log.Fatalf("netrcFromToken: could not write to file: %v", err)
5050
}
5151
}

cmd/proxy/actions/basicauth.go

+3-9
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,8 @@ import (
88
"github.com/gorilla/mux"
99
)
1010

11-
var (
12-
// basicAuthExcludedPaths is a regular expression that matches paths that should not be protected by HTTP basic authentication.
13-
basicAuthExcludedPaths = regexp.MustCompile("^/(health|ready)z$")
14-
)
11+
// basicAuthExcludedPaths is a regular expression that matches paths that should not be protected by HTTP basic authentication.
12+
var basicAuthExcludedPaths = regexp.MustCompile("^/(health|ready)z$")
1513

1614
func basicAuth(user, pass string) mux.MiddlewareFunc {
1715
return func(h http.Handler) http.Handler {
@@ -40,9 +38,5 @@ func checkAuth(r *http.Request, user, pass string) bool {
4038
}
4139

4240
isPass := subtle.ConstantTimeCompare([]byte(pass), []byte(givenPass))
43-
if isPass != 1 {
44-
return false
45-
}
46-
47-
return true
41+
return isPass == 1
4842
}

cmd/proxy/actions/catalog.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ type catalogRes struct {
1818
NextPageToken string `json:"next,omitempty"`
1919
}
2020

21-
// catalogHandler implements GET baseURL/catalog
21+
// catalogHandler implements GET baseURL/catalog.
2222
func catalogHandler(s storage.Backend) http.HandlerFunc {
2323
const op errors.Op = "actions.CatalogHandler"
2424
cs, isCataloger := s.(storage.Cataloger)
@@ -54,7 +54,7 @@ func catalogHandler(s storage.Backend) http.HandlerFunc {
5454
}
5555

5656
// getLimitFromParam converts a URL query parameter into an int
57-
// otherwise converts defaultPageSize constant
57+
// otherwise converts defaultPageSize constant.
5858
func getLimitFromParam(param string) (int, error) {
5959
if param == "" {
6060
return defaultPageSize, nil

cmd/proxy/actions/home.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,5 @@ import (
55
)
66

77
func proxyHomeHandler(w http.ResponseWriter, r *http.Request) {
8-
w.Write([]byte(`"Welcome to The Athens Proxy"`))
8+
_, _ = w.Write([]byte(`"Welcome to The Athens Proxy"`))
99
}

cmd/proxy/actions/index.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313
"github.com/sirupsen/logrus"
1414
)
1515

16-
// indexHandler implements GET baseURL/index
16+
// indexHandler implements GET baseURL/index.
1717
func indexHandler(index index.Indexer) http.HandlerFunc {
1818
return func(w http.ResponseWriter, r *http.Request) {
1919
ctx := r.Context()

cmd/proxy/actions/robots.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"github.com/gomods/athens/pkg/config"
77
)
88

9-
// robotsHandler implements GET baseURL/robots.txt
9+
// robotsHandler implements GET baseURL/robots.txt.
1010
func robotsHandler(c *config.Config) http.HandlerFunc {
1111
return func(w http.ResponseWriter, r *http.Request) {
1212
http.ServeFile(w, r, c.RobotsFile)

cmd/proxy/actions/storage.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import (
2121
"github.com/spf13/afero"
2222
)
2323

24-
// GetStorage returns storage backend based on env configuration
24+
// GetStorage returns storage backend based on env configuration.
2525
func GetStorage(storageType string, storageConfig *config.Storage, timeout time.Duration, client *http.Client) (storage.Backend, error) {
2626
const op errors.Op = "actions.GetStorage"
2727
switch storageType {

cmd/proxy/actions/sumdb.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ func sumdbProxy(url *url.URL, nosumPatterns []string) http.Handler {
1717
req.URL.Host = url.Host
1818
}
1919
if len(nosumPatterns) > 0 {
20-
return noSumWrapper(rp, url.Host, nosumPatterns)
20+
return noSumWrapper(rp, nosumPatterns)
2121
}
2222
return rp
2323
}
2424

25-
func noSumWrapper(h http.Handler, host string, patterns []string) http.Handler {
25+
func noSumWrapper(h http.Handler, patterns []string) http.Handler {
2626
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2727
if strings.HasPrefix(r.URL.Path, "/lookup/") {
2828
for _, p := range patterns {

cmd/proxy/actions/sumdb_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ func TestNoSumPatterns(t *testing.T) {
9797
for _, tc := range noSumTestCases {
9898
t.Run(tc.name, func(t *testing.T) {
9999
w := httptest.NewRecorder()
100-
skipHandler := noSumWrapper(http.HandlerFunc(emptyHandler), "sum.golang.org", tc.patterns)
100+
skipHandler := noSumWrapper(http.HandlerFunc(emptyHandler), tc.patterns)
101101
req := httptest.NewRequest("GET", "/lookup/"+tc.given, nil)
102102
skipHandler.ServeHTTP(w, req)
103103
if tc.status != w.Code {

cmd/proxy/actions/version.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ import (
88
)
99

1010
func versionHandler(w http.ResponseWriter, r *http.Request) {
11-
json.NewEncoder(w).Encode(build.Data())
11+
_ = json.NewEncoder(w).Encode(build.Data())
1212
}

0 commit comments

Comments
 (0)