Skip to content

Commit 74f0c84

Browse files
authored
Enable more revive linter rules (go-gitea#30608)
Noteable additions: - `redefines-builtin-id` forbid variable names that shadow go builtins - `empty-lines` remove unnecessary empty lines that `gofumpt` does not remove for some reason - `superfluous-else` eliminate more superfluous `else` branches Rules are also sorted alphabetically and I cleaned up various parts of `.golangci.yml`.
1 parent aff7b7b commit 74f0c84

Some content is hidden

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

76 files changed

+133
-188
lines changed

.golangci.yml

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
linters:
2+
enable-all: false
3+
disable-all: true
4+
fast: false
25
enable:
36
- bidichk
4-
# - deadcode # deprecated - https://github.com/golangci/golangci-lint/issues/1841
57
- depguard
68
- dupl
79
- errcheck
810
- forbidigo
911
- gocritic
10-
# - gocyclo # The cyclomatic complexety of a lot of functions is too high, we should refactor those another time.
1112
- gofmt
1213
- gofumpt
1314
- gosimple
@@ -17,20 +18,18 @@ linters:
1718
- nolintlint
1819
- revive
1920
- staticcheck
20-
# - structcheck # deprecated - https://github.com/golangci/golangci-lint/issues/1841
2121
- stylecheck
2222
- typecheck
2323
- unconvert
2424
- unused
25-
# - varcheck # deprecated - https://github.com/golangci/golangci-lint/issues/1841
2625
- wastedassign
27-
enable-all: false
28-
disable-all: true
29-
fast: false
3026

3127
run:
3228
timeout: 10m
3329

30+
output:
31+
sort-results: true
32+
3433
linters-settings:
3534
stylecheck:
3635
checks: ["all", "-ST1005", "-ST1003"]
@@ -47,27 +46,37 @@ linters-settings:
4746
errorCode: 1
4847
warningCode: 1
4948
rules:
49+
- name: atomic
50+
- name: bare-return
5051
- name: blank-imports
52+
- name: constant-logical-expr
5153
- name: context-as-argument
5254
- name: context-keys-type
5355
- name: dot-imports
56+
- name: duplicated-imports
57+
- name: empty-lines
58+
- name: error-naming
5459
- name: error-return
5560
- name: error-strings
56-
- name: error-naming
61+
- name: errorf
5762
- name: exported
63+
- name: identical-branches
5864
- name: if-return
5965
- name: increment-decrement
60-
- name: var-naming
61-
- name: var-declaration
66+
- name: indent-error-flow
67+
- name: modifies-value-receiver
6268
- name: package-comments
6369
- name: range
6470
- name: receiver-naming
71+
- name: redefines-builtin-id
72+
- name: string-of-int
73+
- name: superfluous-else
6574
- name: time-naming
75+
- name: unconditional-recursion
6676
- name: unexported-return
67-
- name: indent-error-flow
68-
- name: errorf
69-
- name: duplicated-imports
70-
- name: modifies-value-receiver
77+
- name: unreachable-code
78+
- name: var-declaration
79+
- name: var-naming
7180
gofumpt:
7281
extra-rules: true
7382
depguard:
@@ -93,8 +102,8 @@ issues:
93102
max-issues-per-linter: 0
94103
max-same-issues: 0
95104
exclude-dirs: [node_modules, public, web_src]
105+
exclude-case-sensitive: true
96106
exclude-rules:
97-
# Exclude some linters from running on tests files.
98107
- path: _test\.go
99108
linters:
100109
- gocyclo
@@ -112,19 +121,19 @@ issues:
112121
- path: cmd
113122
linters:
114123
- forbidigo
115-
- linters:
124+
- text: "webhook"
125+
linters:
116126
- dupl
117-
text: "webhook"
118-
- linters:
127+
- text: "`ID' should not be capitalized"
128+
linters:
119129
- gocritic
120-
text: "`ID' should not be capitalized"
121-
- linters:
130+
- text: "swagger"
131+
linters:
122132
- unused
123133
- deadcode
124-
text: "swagger"
125-
- linters:
134+
- text: "argument x is overwritten before first use"
135+
linters:
126136
- staticcheck
127-
text: "argument x is overwritten before first use"
128137
- text: "commentFormatting: put a space between `//` and comment text"
129138
linters:
130139
- gocritic

cmd/hook.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,7 @@ func hookPrintResult(output, isCreate bool, branch, url string) {
465465
fmt.Fprintf(os.Stderr, " %s\n", url)
466466
}
467467
fmt.Fprintln(os.Stderr, "")
468-
os.Stderr.Sync()
468+
_ = os.Stderr.Sync()
469469
}
470470

471471
func pushOptions() map[string]string {

models/asymkey/gpg_key_commit_verification.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,6 @@ func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerific
110110
Reason: "gpg.error.no_committer_account",
111111
}
112112
}
113-
114113
}
115114
}
116115

models/db/engine.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,6 @@ func NamesToBean(names ...string) ([]any, error) {
227227
// Need to map provided names to beans...
228228
beanMap := make(map[string]any)
229229
for _, bean := range tables {
230-
231230
beanMap[strings.ToLower(reflect.Indirect(reflect.ValueOf(bean)).Type().Name())] = bean
232231
beanMap[strings.ToLower(x.TableName(bean))] = bean
233232
beanMap[strings.ToLower(x.TableName(bean, true))] = bean

models/issues/review.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -345,11 +345,9 @@ func CreateReview(ctx context.Context, opts CreateReviewOptions) (*Review, error
345345
return nil, err
346346
}
347347
}
348-
349348
} else if opts.ReviewerTeam != nil {
350349
review.Type = ReviewTypeRequest
351350
review.ReviewerTeamID = opts.ReviewerTeam.ID
352-
353351
} else {
354352
return nil, fmt.Errorf("provide either reviewer or reviewer team")
355353
}

models/migrations/base/db.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,6 @@ func RecreateTable(sess *xorm.Session, bean any) error {
177177
log.Error("Unable to recreate uniques on table %s. Error: %v", tableName, err)
178178
return err
179179
}
180-
181180
case setting.Database.Type.IsMySQL():
182181
// MySQL will drop all the constraints on the old table
183182
if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
@@ -228,7 +227,6 @@ func RecreateTable(sess *xorm.Session, bean any) error {
228227
return err
229228
}
230229
sequenceMap[sequence] = sequenceData
231-
232230
}
233231

234232
// CASCADE causes postgres to drop all the constraints on the old table
@@ -293,9 +291,7 @@ func RecreateTable(sess *xorm.Session, bean any) error {
293291
return err
294292
}
295293
}
296-
297294
}
298-
299295
case setting.Database.Type.IsMSSQL():
300296
// MSSQL will drop all the constraints on the old table
301297
if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
@@ -308,7 +304,6 @@ func RecreateTable(sess *xorm.Session, bean any) error {
308304
log.Error("Unable to rename %s to %s. Error: %v", tempTableName, tableName, err)
309305
return err
310306
}
311-
312307
default:
313308
log.Fatal("Unrecognized DB")
314309
}

models/migrations/v1_11/v111.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,6 @@ func AddBranchProtectionCanPushAndEnableWhitelist(x *xorm.Engine) error {
262262
for _, u := range units {
263263
var found bool
264264
for _, team := range teams {
265-
266265
var teamU []*TeamUnit
267266
var unitEnabled bool
268267
err = sess.Where("team_id = ?", team.ID).Find(&teamU)
@@ -331,7 +330,6 @@ func AddBranchProtectionCanPushAndEnableWhitelist(x *xorm.Engine) error {
331330
}
332331

333332
if !protectedBranch.EnableApprovalsWhitelist {
334-
335333
perm, err := getUserRepoPermission(sess, baseRepo, reviewer)
336334
if err != nil {
337335
return false, err

models/migrations/v1_20/v250.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ func ChangeContainerMetadataMultiArch(x *xorm.Engine) error {
104104

105105
// Convert to new metadata format
106106

107-
new := &MetadataNew{
107+
newMetadata := &MetadataNew{
108108
Type: old.Type,
109109
IsTagged: old.IsTagged,
110110
Platform: old.Platform,
@@ -119,7 +119,7 @@ func ChangeContainerMetadataMultiArch(x *xorm.Engine) error {
119119
Manifests: manifests,
120120
}
121121

122-
metadataJSON, err := json.Marshal(new)
122+
metadataJSON, err := json.Marshal(newMetadata)
123123
if err != nil {
124124
return err
125125
}

models/migrations/v1_6/v71.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,6 @@ func AddScratchHash(x *xorm.Engine) error {
6161
if _, err := sess.ID(tfa.ID).Cols("scratch_salt, scratch_hash").Update(tfa); err != nil {
6262
return fmt.Errorf("couldn't add in scratch_hash and scratch_salt: %w", err)
6363
}
64-
6564
}
6665
}
6766

models/migrations/v1_9/v85.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ func HashAppToken(x *xorm.Engine) error {
8181
if _, err := sess.ID(token.ID).Cols("token_hash, token_salt, token_last_eight, sha1").Update(token); err != nil {
8282
return fmt.Errorf("couldn't add in sha1, token_hash, token_salt and token_last_eight: %w", err)
8383
}
84-
8584
}
8685
}
8786

models/organization/team.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,9 +226,8 @@ func GetTeamIDsByNames(ctx context.Context, orgID int64, names []string, ignoreN
226226
if err != nil {
227227
if ignoreNonExistent {
228228
continue
229-
} else {
230-
return nil, err
231229
}
230+
return nil, err
232231
}
233232
ids = append(ids, u.ID)
234233
}

models/project/board.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,11 @@ func createBoardsForProjectsType(ctx context.Context, project *Project) error {
110110
var items []string
111111

112112
switch project.BoardType {
113-
114113
case BoardTypeBugTriage:
115114
items = setting.Project.ProjectBoardBugTriageType
116115

117116
case BoardTypeBasicKanban:
118117
items = setting.Project.ProjectBoardBasicKanbanType
119-
120118
case BoardTypeNone:
121119
fallthrough
122120
default:

models/repo/user_repo.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,6 @@ func GetReviewers(ctx context.Context, repo *Repository, doerID, posterID int64)
170170
// the owner of a private repo needs to be explicitly added.
171171
cond = cond.Or(builder.Eq{"`user`.id": repo.Owner.ID})
172172
}
173-
174173
} else {
175174
// This is a "public" repository:
176175
// Any user that has read access, is a watcher or organization member can be requested to review

models/user/user.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -988,9 +988,8 @@ func GetUserIDsByNames(ctx context.Context, names []string, ignoreNonExistent bo
988988
if err != nil {
989989
if ignoreNonExistent {
990990
continue
991-
} else {
992-
return nil, err
993991
}
992+
return nil, err
994993
}
995994
ids = append(ids, u.ID)
996995
}

modules/auth/password/password.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,16 @@ func NewComplexity() {
6363
func setupComplexity(values []string) {
6464
if len(values) != 1 || values[0] != "off" {
6565
for _, val := range values {
66-
if complex, ok := charComplexities[val]; ok {
67-
validChars += complex.ValidChars
68-
requiredList = append(requiredList, complex)
66+
if complexity, ok := charComplexities[val]; ok {
67+
validChars += complexity.ValidChars
68+
requiredList = append(requiredList, complexity)
6969
}
7070
}
7171
if len(requiredList) == 0 {
7272
// No valid character classes found; use all classes as default
73-
for _, complex := range charComplexities {
74-
validChars += complex.ValidChars
75-
requiredList = append(requiredList, complex)
73+
for _, complexity := range charComplexities {
74+
validChars += complexity.ValidChars
75+
requiredList = append(requiredList, complexity)
7676
}
7777
}
7878
}

modules/git/batch_reader.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -307,10 +307,10 @@ func ParseTreeLine(objectFormat ObjectFormat, rd *bufio.Reader, modeBuf, fnameBu
307307

308308
// Deal with the binary hash
309309
idx = 0
310-
len := objectFormat.FullLength() / 2
311-
for idx < len {
310+
length := objectFormat.FullLength() / 2
311+
for idx < length {
312312
var read int
313-
read, err = rd.Read(shaBuf[idx:len])
313+
read, err = rd.Read(shaBuf[idx:length])
314314
n += read
315315
if err != nil {
316316
return mode, fname, sha, n, err

modules/git/commit_reader.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,8 @@ readLoop:
4949
if len(line) > 0 && line[0] == ' ' {
5050
_, _ = signatureSB.Write(line[1:])
5151
continue
52-
} else {
53-
pgpsig = false
5452
}
53+
pgpsig = false
5554
}
5655

5756
if !message {

modules/git/pipeline/lfs_nogogit.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,6 @@ func FindLFSFile(repo *git.Repository, objectID git.ObjectID) ([]*LFSResult, err
232232
errChan <- err
233233
break
234234
}
235-
236235
}
237236
}()
238237

modules/git/repo_commit.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -251,18 +251,18 @@ func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions)
251251
return nil, err
252252
}
253253

254-
len := objectFormat.FullLength()
254+
length := objectFormat.FullLength()
255255
commits := []*Commit{}
256-
shaline := make([]byte, len+1)
256+
shaline := make([]byte, length+1)
257257
for {
258258
n, err := io.ReadFull(stdoutReader, shaline)
259-
if err != nil || n < len {
259+
if err != nil || n < length {
260260
if err == io.EOF {
261261
err = nil
262262
}
263263
return commits, err
264264
}
265-
objectID, err := NewIDFromString(string(shaline[0:len]))
265+
objectID, err := NewIDFromString(string(shaline[0:length]))
266266
if err != nil {
267267
return nil, err
268268
}

modules/git/submodule.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,6 @@ func getRefURL(refURL, urlPrefix, repoFullName, sshDomain string) string {
6464
// ex: [email protected]:go-gitea/gitea
6565
match := scpSyntax.FindAllStringSubmatch(refURI, -1)
6666
if len(match) > 0 {
67-
6867
m := match[0]
6968
refHostname := m[2]
7069
pth := m[3]

modules/indexer/code/bleve/bleve.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,6 @@ func (b *Indexer) addDelete(filename string, repo *repo_model.Repository, batch
191191
func (b *Indexer) Index(ctx context.Context, repo *repo_model.Repository, sha string, changes *internal.RepoChanges) error {
192192
batch := inner_bleve.NewFlushingBatch(b.inner.Indexer, maxBatchSize)
193193
if len(changes.Updates) > 0 {
194-
195194
// Now because of some insanity with git cat-file not immediately failing if not run in a valid git directory we need to run git rev-parse first!
196195
if err := git.EnsureValidGitRepository(ctx, repo.RepoPath()); err != nil {
197196
log.Error("Unable to open git repo: %s for %-v: %v", repo.RepoPath(), repo, err)
@@ -335,7 +334,6 @@ func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int
335334
if result, err = b.inner.Indexer.Search(facetRequest); err != nil {
336335
return 0, nil, nil, err
337336
}
338-
339337
}
340338
languagesFacet := result.Facets["languages"]
341339
for _, term := range languagesFacet.Terms.Terms() {

modules/indexer/issues/elasticsearch/elasticsearch.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,6 @@ func (b *Indexer) Search(ctx context.Context, options *internal.SearchOptions) (
145145
query := elastic.NewBoolQuery()
146146

147147
if options.Keyword != "" {
148-
149148
searchType := esMultiMatchTypePhrasePrefix
150149
if options.IsFuzzyKeyword {
151150
searchType = esMultiMatchTypeBestFields

0 commit comments

Comments
 (0)