Skip to content

Commit

Permalink
GOCBC-902: Improve linting abilities
Browse files Browse the repository at this point in the history
Motivation
----------
We've been using the same linting for quite some time now and IDEs
are beginning to flag up issues that our CI isn't. We should improve
our linting.

Changes
-------
Replace all existing linting with golangci-lint which covers the
linters we were using and many more.
Pick a sensible set of linters for now, allowing us to add more in
the future.
Make various code fixes to satisfy the linters.

Change-Id: Ic74071f24975c9ba756713051647e6355c779ae6
Reviewed-on: http://review.couchbase.org/c/gocb/+/129730
Reviewed-by: Brett Lawson <brett19@gmail.com>
Tested-by: Charles Dixon <chvckd@gmail.com>
  • Loading branch information
chvck committed Jun 9, 2020
1 parent 93416ed commit c2b0124
Show file tree
Hide file tree
Showing 25 changed files with 57 additions and 162 deletions.
18 changes: 18 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
run:
modules-download-mode: readonly
tests: false
skip-files:
- logging.go # Logging has some utility functions that are useful to have around which get flagged up
linters:
enable:
- bodyclose
- golint
- gosec
- unconvert
linters-settings:
golint:
set-exit-status: true
min-confidence: 0.81
errcheck:
check-type-assertions: true
check-blank: true
26 changes: 4 additions & 22 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
devsetup:
go get "github.com/kisielk/errcheck"
go get "golang.org/x/lint/golint"
go get "github.com/gordonklaus/ineffassign"
go get "github.com/client9/misspell/cmd/misspell"
go get github.com/golangci/golangci-lint/cmd/golangci-lint
go get github.com/vektra/mockery/.../
git submodule update --remote --init --recursive

Expand All @@ -14,23 +11,8 @@ fasttest:
cover:
go test -coverprofile=cover.out ./

checkerrs:
errcheck -blank -asserts -ignoretests *.go

checkfmt:
! gofmt -l -d *.go 2>&1 | read

checkvet:
go vet *.go

checkiea:
ineffassign -n .

checkspell:
misspell -error *.*

lint: checkfmt checkerrs checkvet checkiea checkspell
golint -set_exit_status -min_confidence 0.81 *.go
lint:
golangci-lint run -v

check: lint
go test -short -cover -race ./
Expand All @@ -54,4 +36,4 @@ updatemocks:
mockery -name waitUntilReadyProvider -output . -testonly -inpkg
# pendingOp is manually mocked

.PHONY: all test devsetup fasttest lint cover checkerrs checkfmt checkvet checkiea checkspell check bench updatetestcases updatemocks
.PHONY: all test devsetup fasttest lint cover check bench updatetestcases updatemocks
13 changes: 0 additions & 13 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,6 @@ func (ca CertificateAuthenticator) Credentials(req AuthCredsRequest) ([]UserPass
}}, nil
}

func getSingleCredential(auth Authenticator, req AuthCredsRequest) (UserPassPair, error) {
creds, err := auth.Credentials(req)
if err != nil {
return UserPassPair{}, err
}

if len(creds) != 1 {
return UserPassPair{}, gocbcore.ErrInvalidCredentials
}

return creds[0], nil
}

type coreAuthWrapper struct {
auth Authenticator
}
Expand Down
2 changes: 1 addition & 1 deletion cluster_analyticsindexes.go
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ func (am *AnalyticsIndexManager) GetPendingMutations(opts *GetPendingMutationsAn
req := mgmtRequest{
Service: ServiceTypeAnalytics,
Method: "GET",
Path: fmt.Sprintf("/analytics/node/agg/stats/remaining"),
Path: "/analytics/node/agg/stats/remaining",
IsIdempotent: true,
RetryStrategy: opts.RetryStrategy,
Timeout: timeout,
Expand Down
2 changes: 0 additions & 2 deletions cluster_analyticsquery.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,6 @@ type AnalyticsMetaData struct {
Metrics AnalyticsMetrics
Signature interface{}
Warnings []AnalyticsWarning

preparedName string
}

func (meta *AnalyticsMetaData) fromData(data jsonAnalyticsResponse) error {
Expand Down
2 changes: 1 addition & 1 deletion cluster_diag.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func (report *DiagnosticsResult) MarshalJSON() ([]byte, error) {

jsonReport.Services[serviceStr] = append(jsonReport.Services[serviceStr], jsonDiagnosticEntry{
ID: service.ID,
LastActivityUs: uint64(time.Now().Sub(service.LastActivity).Nanoseconds()),
LastActivityUs: uint64(time.Since(service.LastActivity).Nanoseconds()),
Remote: service.Remote,
Local: service.Local,
State: stateStr,
Expand Down
11 changes: 0 additions & 11 deletions cluster_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,6 @@ import (
gocbcore "github.com/couchbase/gocbcore/v9"
)

type queryCacheEntry struct {
enhanced bool
name string
encodedPlan string
}

type jsonQueryMetrics struct {
ElapsedTime string `json:"elapsedTime"`
ExecutionTime string `json:"executionTime"`
Expand Down Expand Up @@ -40,11 +34,6 @@ type jsonQueryResponse struct {
Prepared string `json:"prepared"`
}

type jsonQueryPrepData struct {
EncodedPlan string `json:"encoded_plan"`
Name string `json:"name"`
}

// QueryMetrics encapsulates various metrics gathered during a queries execution.
type QueryMetrics struct {
ElapsedTime time.Duration
Expand Down
16 changes: 0 additions & 16 deletions cluster_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,6 @@ type mockQueryRowReader struct {
mockQueryRowReaderBase
}

type mockPreparedQueryRowReader struct {
Dataset []jsonQueryPrepData
mockQueryRowReaderBase
}

type mockQueryRowReaderBase struct {
Meta []byte
MetaErr error
Expand All @@ -159,17 +154,6 @@ func (arr *mockQueryRowReader) NextRow() []byte {
return arr.Suite.mustConvertToBytes(arr.Dataset[idx])
}

func (arr *mockPreparedQueryRowReader) NextRow() []byte {
if arr.idx == len(arr.Dataset) {
return nil
}

idx := arr.idx
arr.idx++

return arr.Suite.mustConvertToBytes(arr.Dataset[idx])
}

func (arr *mockQueryRowReaderBase) MetaData() ([]byte, error) {
return arr.Meta, arr.MetaErr
}
Expand Down
4 changes: 2 additions & 2 deletions cluster_queryindexes.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ func (qm *QueryIndexManager) WatchIndexes(bucketName string, watchList []string,
span.Context(),
bucketName,
&GetAllQueryIndexesOptions{
Timeout: deadline.Sub(time.Now()),
Timeout: time.Until(deadline),
RetryStrategy: opts.RetryStrategy,
})
if err != nil {
Expand Down Expand Up @@ -551,7 +551,7 @@ func (qm *QueryIndexManager) WatchIndexes(bucketName string, watchList []string,
}

// wait till our next poll interval
time.Sleep(sleepDeadline.Sub(time.Now()))
time.Sleep(time.Until(sleepDeadline))
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions cluster_usermgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ func (um *UserManager) UpsertUser(user User, opts *UpsertUserOptions) error {
var reqRoleStrs []string
for _, roleData := range user.Roles {
if roleData.Bucket == "" {
reqRoleStrs = append(reqRoleStrs, fmt.Sprintf("%s", roleData.Name))
reqRoleStrs = append(reqRoleStrs, roleData.Name)
} else {
reqRoleStrs = append(reqRoleStrs, fmt.Sprintf("%s[%s]", roleData.Name, roleData.Bucket))
}
Expand Down Expand Up @@ -704,7 +704,7 @@ func (um *UserManager) UpsertGroup(group Group, opts *UpsertGroupOptions) error
var reqRoleStrs []string
for _, roleData := range group.Roles {
if roleData.Bucket == "" {
reqRoleStrs = append(reqRoleStrs, fmt.Sprintf("%s", roleData.Name))
reqRoleStrs = append(reqRoleStrs, roleData.Name)
} else {
reqRoleStrs = append(reqRoleStrs, fmt.Sprintf("%s[%s]", roleData.Name, roleData.Bucket))
}
Expand Down
5 changes: 0 additions & 5 deletions collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,6 @@ func (c *Collection) scopeName() string {
return c.scope
}

func (c *Collection) clone() *Collection {
newC := *c
return &newC
}

// Name returns the name of the collection.
func (c *Collection) Name() string {
return c.collectionName
Expand Down
10 changes: 4 additions & 6 deletions collection_bulk.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,10 @@ func (c *Collection) Do(ops []BulkOp, opts *BulkOpOptions) error {
}

for range ops {
select {
case item := <-signal:
// We're really just clearing the pendop from this thread,
// since it already completed, no cancel actually occurs
item.finish()
}
item := <-signal
// We're really just clearing the pendop from this thread,
// since it already completed, no cancel actually occurs
item.finish()
}
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion collection_crud.go
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,7 @@ func (c *Collection) GetAllReplicas(id string, opts *GetAllReplicaOptions) (docO
// Start a timer to close it after the deadline
go func() {
select {
case <-time.After(deadline.Sub(time.Now())):
case <-time.After(time.Until(deadline)):
// If we timeout, we should close the result
err := repRes.Close()
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions collection_dura.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func (c *Collection) waitForDurability(
persistCh := make(chan struct{}, numServers)

for replicaIdx := 0; replicaIdx < numServers; replicaIdx++ {
go c.observeOne(opm.TraceSpan(), docID, mt, replicaIdx, replicaCh, persistCh, subOpCancelCh, deadline.Sub(time.Now()))
go c.observeOne(opm.TraceSpan(), docID, mt, replicaIdx, replicaCh, persistCh, subOpCancelCh, time.Until(deadline))
}

numReplicated := uint(0)
Expand All @@ -156,7 +156,7 @@ func (c *Collection) waitForDurability(
numReplicated++
case <-persistCh:
numPersisted++
case <-time.After(deadline.Sub(time.Now())):
case <-time.After(time.Until(deadline)):
// deadline exceeded
close(subOpCancelCh)
return opm.EnhanceErr(ErrAmbiguousTimeout)
Expand Down
4 changes: 2 additions & 2 deletions collection_subdoc.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (c *Collection) internalLookupIn(
var subdocs []gocbcore.SubDocOp
for _, op := range ops {
if op.op == memd.SubDocOpGet && op.path == "" {
if op.isXattr != false {
if op.isXattr {
return nil, errors.New("invalid xattr fetch with no path")
}

Expand All @@ -53,7 +53,7 @@ func (c *Collection) internalLookupIn(
})
continue
} else if op.op == memd.SubDocOpDictSet && op.path == "" {
if op.isXattr != false {
if op.isXattr {
return nil, errors.New("invalid xattr set with no path")
}

Expand Down
2 changes: 0 additions & 2 deletions constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (

const (
goCbVersionStr = "v2.1.1"

persistenceTimeoutFloor = 1500
)

// QueryIndexType provides information on the type of indexer used for an index.
Expand Down
18 changes: 0 additions & 18 deletions constants_str.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,6 @@ func serviceTypeToString(service ServiceType) string {
return ""
}

func serviceTypeFromString(service string) ServiceType {
switch service {
case "mgmt":
return ServiceTypeManagement
case "kv":
return ServiceTypeKeyValue
case "views":
return ServiceTypeViews
case "query":
return ServiceTypeQuery
case "search":
return ServiceTypeSearch
case "analytics":
return ServiceTypeAnalytics
}
return ServiceType(0)
}

func clusterStateToString(state ClusterState) string {
switch state {
case ClusterStateOnline:
Expand Down
4 changes: 0 additions & 4 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ import (
gocbcore "github.com/couchbase/gocbcore/v9"
)

func newCliInternalError(message string) error {
return errors.New(message)
}

type wrappedError struct {
Message string
InnerError error
Expand Down
4 changes: 0 additions & 4 deletions error_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,6 @@ func makeGenericHTTPError(baseErr error, req *gocbcore.HTTPRequest, resp *gocbco
return err
}

func makeHTTPBadStatusError(message string, req *gocbcore.HTTPRequest, resp *gocbcore.HTTPResponse) error {
return makeGenericHTTPError(errors.New(message), req, resp)
}

func makeGenericMgmtError(baseErr error, req *mgmtRequest, resp *mgmtResponse) error {
if baseErr == nil {
logErrorf("makeGenericMgmtError got an empty error")
Expand Down
5 changes: 2 additions & 3 deletions results.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (d *GetResult) Expiry() *time.Duration {
}

func (d *GetResult) fromFullProjection(ops []LookupInSpec, result *LookupInResult, fields []string) error {
if fields == nil || len(fields) == 0 {
if len(fields) == 0 {
// This is a special case where user specified a full doc fetch with expiration.
d.contents = result.contents[0].data
return nil
Expand Down Expand Up @@ -101,7 +101,6 @@ func (d *GetResult) fromSubDoc(ops []LookupInSpec, result *LookupInResult) error

type subdocPath struct {
path string
elem int
isArray bool
}

Expand Down Expand Up @@ -207,6 +206,7 @@ func (d *GetResult) set(paths []subdocPath, content interface{}, value interface
cMap, ok := content.(map[string]interface{})
if !ok {
// this isn't possible but the linter won't play nice without it
logErrorf("Failed to assert projection content to a map")
}
cMap[path.path] = make(map[string]interface{})
return d.set(paths[1:], cMap[path.path], value)
Expand All @@ -219,7 +219,6 @@ func (d *GetResult) set(paths []subdocPath, content interface{}, value interface
type LookupInResult struct {
Result
contents []lookupInPartial
pathMap map[string]int
}

type lookupInPartial struct {
Expand Down
Loading

0 comments on commit c2b0124

Please sign in to comment.