Skip to content

Commit 2a59dfb

Browse files
authored
enable staticcheck QFxxxx rules (go-gitea#34064)
1 parent 5564c39 commit 2a59dfb

Some content is hidden

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

47 files changed

+179
-143
lines changed

Diff for: .golangci.yml

-5
Original file line numberDiff line numberDiff line change
@@ -86,13 +86,8 @@ linters:
8686
- -ST1003
8787
- -ST1005
8888
- -QF1001
89-
- -QF1002
90-
- -QF1003
9189
- -QF1006
92-
- -QF1007
9390
- -QF1008
94-
- -QF1009
95-
- -QF1012
9691
testifylint:
9792
disable:
9893
- go-require

Diff for: cmd/doctor.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -144,11 +144,12 @@ func setupDoctorDefaultLogger(ctx *cli.Context, colorize bool) {
144144
setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr)
145145

146146
logFile := ctx.String("log-file")
147-
if logFile == "" {
147+
switch logFile {
148+
case "":
148149
return // if no doctor log-file is set, do not show any log from default logger
149-
} else if logFile == "-" {
150+
case "-":
150151
setupConsoleLogger(log.TRACE, colorize, os.Stdout)
151-
} else {
152+
default:
152153
logFile, _ = filepath.Abs(logFile)
153154
writeMode := log.WriterMode{Level: log.TRACE, WriterOption: log.WriterFileOption{FileName: logFile}}
154155
writer, err := log.NewEventWriter("console-to-file", "file", writeMode)

Diff for: models/actions/runner.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,10 @@ func (r *ActionRunner) BelongsToOwnerType() types.OwnerType {
8686
return types.OwnerTypeRepository
8787
}
8888
if r.OwnerID != 0 {
89-
if r.Owner.Type == user_model.UserTypeOrganization {
89+
switch r.Owner.Type {
90+
case user_model.UserTypeOrganization:
9091
return types.OwnerTypeOrganization
91-
} else if r.Owner.Type == user_model.UserTypeIndividual {
92+
case user_model.UserTypeIndividual:
9293
return types.OwnerTypeIndividual
9394
}
9495
}

Diff for: models/db/engine_init.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,10 @@ func newXORMEngine() (*xorm.Engine, error) {
4242
if err != nil {
4343
return nil, err
4444
}
45-
if setting.Database.Type == "mysql" {
45+
switch setting.Database.Type {
46+
case "mysql":
4647
engine.Dialect().SetParams(map[string]string{"rowFormat": "DYNAMIC"})
47-
} else if setting.Database.Type == "mssql" {
48+
case "mssql":
4849
engine.Dialect().SetParams(map[string]string{"DEFAULT_VARCHAR": "nvarchar"})
4950
}
5051
engine.SetSchema(setting.Database.Schema)

Diff for: models/repo/repo.go

+7-6
Original file line numberDiff line numberDiff line change
@@ -425,32 +425,33 @@ func (repo *Repository) MustGetUnit(ctx context.Context, tp unit.Type) *RepoUnit
425425
return ru
426426
}
427427

428-
if tp == unit.TypeExternalWiki {
428+
switch tp {
429+
case unit.TypeExternalWiki:
429430
return &RepoUnit{
430431
Type: tp,
431432
Config: new(ExternalWikiConfig),
432433
}
433-
} else if tp == unit.TypeExternalTracker {
434+
case unit.TypeExternalTracker:
434435
return &RepoUnit{
435436
Type: tp,
436437
Config: new(ExternalTrackerConfig),
437438
}
438-
} else if tp == unit.TypePullRequests {
439+
case unit.TypePullRequests:
439440
return &RepoUnit{
440441
Type: tp,
441442
Config: new(PullRequestsConfig),
442443
}
443-
} else if tp == unit.TypeIssues {
444+
case unit.TypeIssues:
444445
return &RepoUnit{
445446
Type: tp,
446447
Config: new(IssuesConfig),
447448
}
448-
} else if tp == unit.TypeActions {
449+
case unit.TypeActions:
449450
return &RepoUnit{
450451
Type: tp,
451452
Config: new(ActionsConfig),
452453
}
453-
} else if tp == unit.TypeProjects {
454+
case unit.TypeProjects:
454455
cfg := new(ProjectsConfig)
455456
cfg.ProjectsMode = ProjectsModeNone
456457
return &RepoUnit{

Diff for: models/unittest/fscopy.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func SyncFile(srcPath, destPath string) error {
2828
}
2929

3030
if src.Size() == dest.Size() &&
31-
src.ModTime() == dest.ModTime() &&
31+
src.ModTime().Equal(dest.ModTime()) &&
3232
src.Mode() == dest.Mode() {
3333
return nil
3434
}

Diff for: models/user/search.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,14 @@ func (opts *SearchUserOptions) toSearchQueryBase(ctx context.Context) *xorm.Sess
4545
var cond builder.Cond
4646
cond = builder.Eq{"type": opts.Type}
4747
if opts.IncludeReserved {
48-
if opts.Type == UserTypeIndividual {
48+
switch opts.Type {
49+
case UserTypeIndividual:
4950
cond = cond.Or(builder.Eq{"type": UserTypeUserReserved}).Or(
5051
builder.Eq{"type": UserTypeBot},
5152
).Or(
5253
builder.Eq{"type": UserTypeRemoteUser},
5354
)
54-
} else if opts.Type == UserTypeOrganization {
55+
case UserTypeOrganization:
5556
cond = cond.Or(builder.Eq{"type": UserTypeOrganizationReserved})
5657
}
5758
}

Diff for: models/webhook/hooktask.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,8 @@ func MarkTaskDelivered(ctx context.Context, task *HookTask) (bool, error) {
198198
func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, olderThan time.Duration, numberToKeep int) error {
199199
log.Trace("Doing: CleanupHookTaskTable")
200200

201-
if cleanupType == OlderThan {
201+
switch cleanupType {
202+
case OlderThan:
202203
deleteOlderThan := time.Now().Add(-olderThan).UnixNano()
203204
deletes, err := db.GetEngine(ctx).
204205
Where("is_delivered = ? and delivered < ?", true, deleteOlderThan).
@@ -207,7 +208,7 @@ func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType,
207208
return err
208209
}
209210
log.Trace("Deleted %d rows from hook_task", deletes)
210-
} else if cleanupType == PerWebhook {
211+
case PerWebhook:
211212
hookIDs := make([]int64, 0, 10)
212213
err := db.GetEngine(ctx).
213214
Table("webhook").

Diff for: modules/git/grep.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,14 @@ func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepO
6262
var results []*GrepResult
6363
cmd := NewCommand("grep", "--null", "--break", "--heading", "--line-number", "--full-name")
6464
cmd.AddOptionValues("--context", fmt.Sprint(opts.ContextLineNumber))
65-
if opts.GrepMode == GrepModeExact {
65+
switch opts.GrepMode {
66+
case GrepModeExact:
6667
cmd.AddArguments("--fixed-strings")
6768
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
68-
} else if opts.GrepMode == GrepModeRegexp {
69+
case GrepModeRegexp:
6970
cmd.AddArguments("--perl-regexp")
7071
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
71-
} else /* words */ {
72+
default: /* words */
7273
words := strings.Fields(search)
7374
cmd.AddArguments("--fixed-strings", "--ignore-case")
7475
for i, word := range words {

Diff for: modules/git/log_name_status.go

+12-9
Original file line numberDiff line numberDiff line change
@@ -118,11 +118,12 @@ func (g *LogNameStatusRepoParser) Next(treepath string, paths2ids map[string]int
118118
g.buffull = false
119119
g.next, err = g.rd.ReadSlice('\x00')
120120
if err != nil {
121-
if err == bufio.ErrBufferFull {
121+
switch err {
122+
case bufio.ErrBufferFull:
122123
g.buffull = true
123-
} else if err == io.EOF {
124+
case io.EOF:
124125
return nil, nil
125-
} else {
126+
default:
126127
return nil, err
127128
}
128129
}
@@ -132,11 +133,12 @@ func (g *LogNameStatusRepoParser) Next(treepath string, paths2ids map[string]int
132133
if bytes.Equal(g.next, []byte("commit\000")) {
133134
g.next, err = g.rd.ReadSlice('\x00')
134135
if err != nil {
135-
if err == bufio.ErrBufferFull {
136+
switch err {
137+
case bufio.ErrBufferFull:
136138
g.buffull = true
137-
} else if err == io.EOF {
139+
case io.EOF:
138140
return nil, nil
139-
} else {
141+
default:
140142
return nil, err
141143
}
142144
}
@@ -214,11 +216,12 @@ diffloop:
214216
}
215217
g.next, err = g.rd.ReadSlice('\x00')
216218
if err != nil {
217-
if err == bufio.ErrBufferFull {
219+
switch err {
220+
case bufio.ErrBufferFull:
218221
g.buffull = true
219-
} else if err == io.EOF {
222+
case io.EOF:
220223
return &ret, nil
221-
} else {
224+
default:
222225
return nil, err
223226
}
224227
}

Diff for: modules/git/repo_ref.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@ func (repo *Repository) GetRefs() ([]*Reference, error) {
1919
// refType should only be a literal "branch" or "tag" and nothing else
2020
func (repo *Repository) ListOccurrences(ctx context.Context, refType, commitSHA string) ([]string, error) {
2121
cmd := NewCommand()
22-
if refType == "branch" {
22+
switch refType {
23+
case "branch":
2324
cmd.AddArguments("branch")
24-
} else if refType == "tag" {
25+
case "tag":
2526
cmd.AddArguments("tag")
26-
} else {
27+
default:
2728
return nil, util.NewInvalidArgumentErrorf(`can only use "branch" or "tag" for refType, but got %q`, refType)
2829
}
2930
stdout, _, err := cmd.AddArguments("--no-color", "--sort=-creatordate", "--contains").AddDynamicArguments(commitSHA).RunStdString(ctx, &RunOpts{Dir: repo.Path})

Diff for: modules/git/url/url.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,13 @@ func ParseRepositoryURL(ctx context.Context, repoURL string) (*RepositoryURL, er
133133
}
134134
}
135135

136-
if parsed.URL.Scheme == "http" || parsed.URL.Scheme == "https" {
136+
switch parsed.URL.Scheme {
137+
case "http", "https":
137138
if !httplib.IsCurrentGiteaSiteURL(ctx, repoURL) {
138139
return ret, nil
139140
}
140141
fillPathParts(strings.TrimPrefix(parsed.URL.Path, setting.AppSubURL))
141-
} else if parsed.URL.Scheme == "ssh" || parsed.URL.Scheme == "git+ssh" {
142+
case "ssh", "git+ssh":
142143
domainSSH := setting.SSH.Domain
143144
domainCur := httplib.GuessCurrentHostDomain(ctx)
144145
urlDomain, _, _ := net.SplitHostPort(parsed.URL.Host)
@@ -166,9 +167,10 @@ func MakeRepositoryWebLink(repoURL *RepositoryURL) string {
166167
// now, let's guess, for example:
167168
// * [email protected]:owner/submodule.git
168169
// * https://github.com/example/submodule1.git
169-
if repoURL.GitURL.Scheme == "http" || repoURL.GitURL.Scheme == "https" {
170+
switch repoURL.GitURL.Scheme {
171+
case "http", "https":
170172
return strings.TrimSuffix(repoURL.GitURL.String(), ".git")
171-
} else if repoURL.GitURL.Scheme == "ssh" || repoURL.GitURL.Scheme == "git+ssh" {
173+
case "ssh", "git+ssh":
172174
hostname, _, _ := net.SplitHostPort(repoURL.GitURL.Host)
173175
hostname = util.IfZero(hostname, repoURL.GitURL.Host)
174176
urlPath := strings.TrimSuffix(repoURL.GitURL.Path, ".git")

Diff for: modules/gtprof/trace_builtin.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func (t *traceBuiltinSpan) toString(out *strings.Builder, indent int) {
4040
if t.ts.endTime.IsZero() {
4141
out.WriteString(" duration: (not ended)")
4242
} else {
43-
out.WriteString(fmt.Sprintf(" duration=%.4fs", t.ts.endTime.Sub(t.ts.startTime).Seconds()))
43+
fmt.Fprintf(out, " duration=%.4fs", t.ts.endTime.Sub(t.ts.startTime).Seconds())
4444
}
4545
for _, a := range t.ts.attributes {
4646
out.WriteString(" ")

Diff for: modules/indexer/code/gitgrep/gitgrep.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,10 @@ func indexSettingToGitGrepPathspecList() (list []string) {
2626

2727
func PerformSearch(ctx context.Context, page int, repoID int64, gitRepo *git.Repository, ref git.RefName, keyword string, searchMode indexer.SearchModeType) (searchResults []*code_indexer.Result, total int, err error) {
2828
grepMode := git.GrepModeWords
29-
if searchMode == indexer.SearchModeExact {
29+
switch searchMode {
30+
case indexer.SearchModeExact:
3031
grepMode = git.GrepModeExact
31-
} else if searchMode == indexer.SearchModeRegexp {
32+
case indexer.SearchModeRegexp:
3233
grepMode = git.GrepModeRegexp
3334
}
3435
res, err := git.GrepSearch(ctx, gitRepo, keyword, git.GrepOptions{

Diff for: modules/log/event_writer_base.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ func (b *EventWriterBaseImpl) Run(ctx context.Context) {
105105
case io.WriterTo:
106106
_, err = msg.WriteTo(b.OutputWriteCloser)
107107
default:
108-
_, err = b.OutputWriteCloser.Write([]byte(fmt.Sprint(msg)))
108+
_, err = fmt.Fprint(b.OutputWriteCloser, msg)
109109
}
110110
if err != nil {
111111
FallbackErrorf("unable to write log message of %q (%v): %v", b.Name, err, event.Msg)

Diff for: modules/markup/common/linkify.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,10 @@ func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Cont
8585
} else if lastChar == ')' {
8686
closing := 0
8787
for i := m[1] - 1; i >= m[0]; i-- {
88-
if line[i] == ')' {
88+
switch line[i] {
89+
case ')':
8990
closing++
90-
} else if line[i] == '(' {
91+
case '(':
9192
closing--
9293
}
9394
}

Diff for: modules/markup/markdown/goldmark.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,10 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa
8080
// many places render non-comment contents with no mode=document, then these contents also use comment's hard line break setting
8181
// especially in many tests.
8282
markdownLineBreakStyle := ctx.RenderOptions.Metas["markdownLineBreakStyle"]
83-
if markdownLineBreakStyle == "comment" {
83+
switch markdownLineBreakStyle {
84+
case "comment":
8485
v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInComments)
85-
} else if markdownLineBreakStyle == "document" {
86+
case "document":
8687
v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInDocuments)
8788
}
8889
}
@@ -155,7 +156,7 @@ func (r *HTMLRenderer) renderDocument(w util.BufWriter, source []byte, node ast.
155156
if entering {
156157
_, err = w.WriteString("<div")
157158
if err == nil {
158-
_, err = w.WriteString(fmt.Sprintf(` lang=%q`, val))
159+
_, err = fmt.Fprintf(w, ` lang=%q`, val)
159160
}
160161
if err == nil {
161162
_, err = w.WriteRune('>')

Diff for: modules/markup/markdown/math/inline_parser.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,11 @@ func (parser *inlineParser) Parse(parent ast.Node, block text.Reader, pc parser.
7070
startMarkLen = 1
7171
stopMark = parser.endBytesSingleDollar
7272
if len(line) > 1 {
73-
if line[1] == '$' {
73+
switch line[1] {
74+
case '$':
7475
startMarkLen = 2
7576
stopMark = parser.endBytesDoubleDollar
76-
} else if line[1] == '`' {
77+
case '`':
7778
pos := 1
7879
for ; pos < len(line) && line[pos] == '`'; pos++ {
7980
}
@@ -121,9 +122,10 @@ func (parser *inlineParser) Parse(parent ast.Node, block text.Reader, pc parser.
121122
i++
122123
continue
123124
}
124-
if line[i] == '{' {
125+
switch line[i] {
126+
case '{':
125127
depth++
126-
} else if line[i] == '}' {
128+
case '}':
127129
depth--
128130
}
129131
}

Diff for: modules/markup/mdstripper/mdstripper.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -107,11 +107,12 @@ func (r *stripRenderer) processAutoLink(w io.Writer, link []byte) {
107107
}
108108

109109
var sep string
110-
if parts[3] == "issues" {
110+
switch parts[3] {
111+
case "issues":
111112
sep = "#"
112-
} else if parts[3] == "pulls" {
113+
case "pulls":
113114
sep = "!"
114-
} else {
115+
default:
115116
// Process out of band
116117
r.links = append(r.links, linkStr)
117118
return

Diff for: modules/references/references.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -462,11 +462,12 @@ func findAllIssueReferencesBytes(content []byte, links []string) []*rawReference
462462
continue
463463
}
464464
var sep string
465-
if parts[3] == "issues" {
465+
switch parts[3] {
466+
case "issues":
466467
sep = "#"
467-
} else if parts[3] == "pulls" {
468+
case "pulls":
468469
sep = "!"
469-
} else {
470+
default:
470471
continue
471472
}
472473
// Note: closing/reopening keywords not supported with URLs

Diff for: modules/setting/storage.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -210,8 +210,8 @@ func getStorageTargetSection(rootCfg ConfigProvider, name, typ string, sec Confi
210210
targetSec, _ := rootCfg.GetSection(storageSectionName + "." + name)
211211
if targetSec != nil {
212212
targetType := targetSec.Key("STORAGE_TYPE").String()
213-
switch {
214-
case targetType == "":
213+
switch targetType {
214+
case "":
215215
if targetSec.Key("PATH").String() == "" { // both storage type and path are empty, use default
216216
return getDefaultStorageSection(rootCfg), targetSecIsDefault, nil
217217
}

0 commit comments

Comments
 (0)