Skip to content

enable staticcheck QFxxxx rules #34064

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,8 @@ linters:
- -ST1003
- -ST1005
- -QF1001
- -QF1002
- -QF1003
- -QF1006
- -QF1007
- -QF1008
- -QF1009
- -QF1012
testifylint:
disable:
- go-require
Expand Down
7 changes: 4 additions & 3 deletions cmd/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,12 @@ func setupDoctorDefaultLogger(ctx *cli.Context, colorize bool) {
setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr)

logFile := ctx.String("log-file")
if logFile == "" {
switch logFile {
case "":
return // if no doctor log-file is set, do not show any log from default logger
} else if logFile == "-" {
case "-":
setupConsoleLogger(log.TRACE, colorize, os.Stdout)
} else {
default:
logFile, _ = filepath.Abs(logFile)
writeMode := log.WriterMode{Level: log.TRACE, WriterOption: log.WriterFileOption{FileName: logFile}}
writer, err := log.NewEventWriter("console-to-file", "file", writeMode)
Expand Down
5 changes: 3 additions & 2 deletions models/actions/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,10 @@ func (r *ActionRunner) BelongsToOwnerType() types.OwnerType {
return types.OwnerTypeRepository
}
if r.OwnerID != 0 {
if r.Owner.Type == user_model.UserTypeOrganization {
switch r.Owner.Type {
case user_model.UserTypeOrganization:
return types.OwnerTypeOrganization
} else if r.Owner.Type == user_model.UserTypeIndividual {
case user_model.UserTypeIndividual:
return types.OwnerTypeIndividual
}
}
Expand Down
5 changes: 3 additions & 2 deletions models/db/engine_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@ func newXORMEngine() (*xorm.Engine, error) {
if err != nil {
return nil, err
}
if setting.Database.Type == "mysql" {
switch setting.Database.Type {
case "mysql":
engine.Dialect().SetParams(map[string]string{"rowFormat": "DYNAMIC"})
} else if setting.Database.Type == "mssql" {
case "mssql":
engine.Dialect().SetParams(map[string]string{"DEFAULT_VARCHAR": "nvarchar"})
}
engine.SetSchema(setting.Database.Schema)
Expand Down
13 changes: 7 additions & 6 deletions models/repo/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,32 +425,33 @@ func (repo *Repository) MustGetUnit(ctx context.Context, tp unit.Type) *RepoUnit
return ru
}

if tp == unit.TypeExternalWiki {
switch tp {
case unit.TypeExternalWiki:
return &RepoUnit{
Type: tp,
Config: new(ExternalWikiConfig),
}
} else if tp == unit.TypeExternalTracker {
case unit.TypeExternalTracker:
return &RepoUnit{
Type: tp,
Config: new(ExternalTrackerConfig),
}
} else if tp == unit.TypePullRequests {
case unit.TypePullRequests:
return &RepoUnit{
Type: tp,
Config: new(PullRequestsConfig),
}
} else if tp == unit.TypeIssues {
case unit.TypeIssues:
return &RepoUnit{
Type: tp,
Config: new(IssuesConfig),
}
} else if tp == unit.TypeActions {
case unit.TypeActions:
return &RepoUnit{
Type: tp,
Config: new(ActionsConfig),
}
} else if tp == unit.TypeProjects {
case unit.TypeProjects:
cfg := new(ProjectsConfig)
cfg.ProjectsMode = ProjectsModeNone
return &RepoUnit{
Expand Down
2 changes: 1 addition & 1 deletion models/unittest/fscopy.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func SyncFile(srcPath, destPath string) error {
}

if src.Size() == dest.Size() &&
src.ModTime() == dest.ModTime() &&
src.ModTime().Equal(dest.ModTime()) &&
src.Mode() == dest.Mode() {
return nil
}
Expand Down
5 changes: 3 additions & 2 deletions models/user/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,14 @@ func (opts *SearchUserOptions) toSearchQueryBase(ctx context.Context) *xorm.Sess
var cond builder.Cond
cond = builder.Eq{"type": opts.Type}
if opts.IncludeReserved {
if opts.Type == UserTypeIndividual {
switch opts.Type {
case UserTypeIndividual:
cond = cond.Or(builder.Eq{"type": UserTypeUserReserved}).Or(
builder.Eq{"type": UserTypeBot},
).Or(
builder.Eq{"type": UserTypeRemoteUser},
)
} else if opts.Type == UserTypeOrganization {
case UserTypeOrganization:
cond = cond.Or(builder.Eq{"type": UserTypeOrganizationReserved})
}
}
Expand Down
5 changes: 3 additions & 2 deletions models/webhook/hooktask.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,8 @@ func MarkTaskDelivered(ctx context.Context, task *HookTask) (bool, error) {
func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, olderThan time.Duration, numberToKeep int) error {
log.Trace("Doing: CleanupHookTaskTable")

if cleanupType == OlderThan {
switch cleanupType {
case OlderThan:
deleteOlderThan := time.Now().Add(-olderThan).UnixNano()
deletes, err := db.GetEngine(ctx).
Where("is_delivered = ? and delivered < ?", true, deleteOlderThan).
Expand All @@ -207,7 +208,7 @@ func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType,
return err
}
log.Trace("Deleted %d rows from hook_task", deletes)
} else if cleanupType == PerWebhook {
case PerWebhook:
hookIDs := make([]int64, 0, 10)
err := db.GetEngine(ctx).
Table("webhook").
Expand Down
7 changes: 4 additions & 3 deletions modules/git/grep.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,14 @@ func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepO
var results []*GrepResult
cmd := NewCommand("grep", "--null", "--break", "--heading", "--line-number", "--full-name")
cmd.AddOptionValues("--context", fmt.Sprint(opts.ContextLineNumber))
if opts.GrepMode == GrepModeExact {
switch opts.GrepMode {
case GrepModeExact:
cmd.AddArguments("--fixed-strings")
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
} else if opts.GrepMode == GrepModeRegexp {
case GrepModeRegexp:
cmd.AddArguments("--perl-regexp")
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
} else /* words */ {
default: /* words */
words := strings.Fields(search)
cmd.AddArguments("--fixed-strings", "--ignore-case")
for i, word := range words {
Expand Down
21 changes: 12 additions & 9 deletions modules/git/log_name_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,12 @@ func (g *LogNameStatusRepoParser) Next(treepath string, paths2ids map[string]int
g.buffull = false
g.next, err = g.rd.ReadSlice('\x00')
if err != nil {
if err == bufio.ErrBufferFull {
switch err {
case bufio.ErrBufferFull:
g.buffull = true
} else if err == io.EOF {
case io.EOF:
return nil, nil
} else {
default:
return nil, err
}
}
Expand All @@ -132,11 +133,12 @@ func (g *LogNameStatusRepoParser) Next(treepath string, paths2ids map[string]int
if bytes.Equal(g.next, []byte("commit\000")) {
g.next, err = g.rd.ReadSlice('\x00')
if err != nil {
if err == bufio.ErrBufferFull {
switch err {
case bufio.ErrBufferFull:
g.buffull = true
} else if err == io.EOF {
case io.EOF:
return nil, nil
} else {
default:
return nil, err
}
}
Expand Down Expand Up @@ -214,11 +216,12 @@ diffloop:
}
g.next, err = g.rd.ReadSlice('\x00')
if err != nil {
if err == bufio.ErrBufferFull {
switch err {
case bufio.ErrBufferFull:
g.buffull = true
} else if err == io.EOF {
case io.EOF:
return &ret, nil
} else {
default:
return nil, err
}
}
Expand Down
7 changes: 4 additions & 3 deletions modules/git/repo_ref.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ func (repo *Repository) GetRefs() ([]*Reference, error) {
// refType should only be a literal "branch" or "tag" and nothing else
func (repo *Repository) ListOccurrences(ctx context.Context, refType, commitSHA string) ([]string, error) {
cmd := NewCommand()
if refType == "branch" {
switch refType {
case "branch":
cmd.AddArguments("branch")
} else if refType == "tag" {
case "tag":
cmd.AddArguments("tag")
} else {
default:
return nil, util.NewInvalidArgumentErrorf(`can only use "branch" or "tag" for refType, but got %q`, refType)
}
stdout, _, err := cmd.AddArguments("--no-color", "--sort=-creatordate", "--contains").AddDynamicArguments(commitSHA).RunStdString(ctx, &RunOpts{Dir: repo.Path})
Expand Down
10 changes: 6 additions & 4 deletions modules/git/url/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,13 @@ func ParseRepositoryURL(ctx context.Context, repoURL string) (*RepositoryURL, er
}
}

if parsed.URL.Scheme == "http" || parsed.URL.Scheme == "https" {
switch parsed.URL.Scheme {
case "http", "https":
if !httplib.IsCurrentGiteaSiteURL(ctx, repoURL) {
return ret, nil
}
fillPathParts(strings.TrimPrefix(parsed.URL.Path, setting.AppSubURL))
} else if parsed.URL.Scheme == "ssh" || parsed.URL.Scheme == "git+ssh" {
case "ssh", "git+ssh":
domainSSH := setting.SSH.Domain
domainCur := httplib.GuessCurrentHostDomain(ctx)
urlDomain, _, _ := net.SplitHostPort(parsed.URL.Host)
Expand Down Expand Up @@ -166,9 +167,10 @@ func MakeRepositoryWebLink(repoURL *RepositoryURL) string {
// now, let's guess, for example:
// * [email protected]:owner/submodule.git
// * https://github.com/example/submodule1.git
if repoURL.GitURL.Scheme == "http" || repoURL.GitURL.Scheme == "https" {
switch repoURL.GitURL.Scheme {
case "http", "https":
return strings.TrimSuffix(repoURL.GitURL.String(), ".git")
} else if repoURL.GitURL.Scheme == "ssh" || repoURL.GitURL.Scheme == "git+ssh" {
case "ssh", "git+ssh":
hostname, _, _ := net.SplitHostPort(repoURL.GitURL.Host)
hostname = util.IfZero(hostname, repoURL.GitURL.Host)
urlPath := strings.TrimSuffix(repoURL.GitURL.Path, ".git")
Expand Down
2 changes: 1 addition & 1 deletion modules/gtprof/trace_builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (t *traceBuiltinSpan) toString(out *strings.Builder, indent int) {
if t.ts.endTime.IsZero() {
out.WriteString(" duration: (not ended)")
} else {
out.WriteString(fmt.Sprintf(" duration=%.4fs", t.ts.endTime.Sub(t.ts.startTime).Seconds()))
fmt.Fprintf(out, " duration=%.4fs", t.ts.endTime.Sub(t.ts.startTime).Seconds())
}
for _, a := range t.ts.attributes {
out.WriteString(" ")
Expand Down
5 changes: 3 additions & 2 deletions modules/indexer/code/gitgrep/gitgrep.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ func indexSettingToGitGrepPathspecList() (list []string) {

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) {
grepMode := git.GrepModeWords
if searchMode == indexer.SearchModeExact {
switch searchMode {
case indexer.SearchModeExact:
grepMode = git.GrepModeExact
} else if searchMode == indexer.SearchModeRegexp {
case indexer.SearchModeRegexp:
grepMode = git.GrepModeRegexp
}
res, err := git.GrepSearch(ctx, gitRepo, keyword, git.GrepOptions{
Expand Down
2 changes: 1 addition & 1 deletion modules/log/event_writer_base.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func (b *EventWriterBaseImpl) Run(ctx context.Context) {
case io.WriterTo:
_, err = msg.WriteTo(b.OutputWriteCloser)
default:
_, err = b.OutputWriteCloser.Write([]byte(fmt.Sprint(msg)))
_, err = fmt.Fprint(b.OutputWriteCloser, msg)
}
if err != nil {
FallbackErrorf("unable to write log message of %q (%v): %v", b.Name, err, event.Msg)
Expand Down
5 changes: 3 additions & 2 deletions modules/markup/common/linkify.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,10 @@ func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Cont
} else if lastChar == ')' {
closing := 0
for i := m[1] - 1; i >= m[0]; i-- {
if line[i] == ')' {
switch line[i] {
case ')':
closing++
} else if line[i] == '(' {
case '(':
closing--
}
}
Expand Down
7 changes: 4 additions & 3 deletions modules/markup/markdown/goldmark.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,10 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa
// many places render non-comment contents with no mode=document, then these contents also use comment's hard line break setting
// especially in many tests.
markdownLineBreakStyle := ctx.RenderOptions.Metas["markdownLineBreakStyle"]
if markdownLineBreakStyle == "comment" {
switch markdownLineBreakStyle {
case "comment":
v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInComments)
} else if markdownLineBreakStyle == "document" {
case "document":
v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInDocuments)
}
}
Expand Down Expand Up @@ -155,7 +156,7 @@ func (r *HTMLRenderer) renderDocument(w util.BufWriter, source []byte, node ast.
if entering {
_, err = w.WriteString("<div")
if err == nil {
_, err = w.WriteString(fmt.Sprintf(` lang=%q`, val))
_, err = fmt.Fprintf(w, ` lang=%q`, val)
}
if err == nil {
_, err = w.WriteRune('>')
Expand Down
10 changes: 6 additions & 4 deletions modules/markup/markdown/math/inline_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,11 @@ func (parser *inlineParser) Parse(parent ast.Node, block text.Reader, pc parser.
startMarkLen = 1
stopMark = parser.endBytesSingleDollar
if len(line) > 1 {
if line[1] == '$' {
switch line[1] {
case '$':
startMarkLen = 2
stopMark = parser.endBytesDoubleDollar
} else if line[1] == '`' {
case '`':
pos := 1
for ; pos < len(line) && line[pos] == '`'; pos++ {
}
Expand Down Expand Up @@ -121,9 +122,10 @@ func (parser *inlineParser) Parse(parent ast.Node, block text.Reader, pc parser.
i++
continue
}
if line[i] == '{' {
switch line[i] {
case '{':
depth++
} else if line[i] == '}' {
case '}':
depth--
}
}
Expand Down
7 changes: 4 additions & 3 deletions modules/markup/mdstripper/mdstripper.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,12 @@ func (r *stripRenderer) processAutoLink(w io.Writer, link []byte) {
}

var sep string
if parts[3] == "issues" {
switch parts[3] {
case "issues":
sep = "#"
} else if parts[3] == "pulls" {
case "pulls":
sep = "!"
} else {
default:
// Process out of band
r.links = append(r.links, linkStr)
return
Expand Down
7 changes: 4 additions & 3 deletions modules/references/references.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,11 +462,12 @@ func findAllIssueReferencesBytes(content []byte, links []string) []*rawReference
continue
}
var sep string
if parts[3] == "issues" {
switch parts[3] {
case "issues":
sep = "#"
} else if parts[3] == "pulls" {
case "pulls":
sep = "!"
} else {
default:
continue
}
// Note: closing/reopening keywords not supported with URLs
Expand Down
4 changes: 2 additions & 2 deletions modules/setting/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,8 @@ func getStorageTargetSection(rootCfg ConfigProvider, name, typ string, sec Confi
targetSec, _ := rootCfg.GetSection(storageSectionName + "." + name)
if targetSec != nil {
targetType := targetSec.Key("STORAGE_TYPE").String()
switch {
case targetType == "":
switch targetType {
case "":
if targetSec.Key("PATH").String() == "" { // both storage type and path are empty, use default
return getDefaultStorageSection(rootCfg), targetSecIsDefault, nil
}
Expand Down
Loading