Skip to content

Run gopls modernize on the codebase #33739

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

Closed
wants to merge 4 commits into from
Closed
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
4 changes: 2 additions & 2 deletions cmd/cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ func runCert(c *cli.Context) error {
BasicConstraintsValid: true,
}

hosts := strings.Split(c.String("host"), ",")
for _, h := range hosts {
hosts := strings.SplitSeq(c.String("host"), ",")
for h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
Expand Down
2 changes: 1 addition & 1 deletion cmd/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func runRecreateTable(ctx *cli.Context) error {

args := ctx.Args()
names := make([]string, 0, ctx.NArg())
for i := 0; i < ctx.NArg(); i++ {
for i := range ctx.NArg() {
names = append(names, args.Get(i))
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/dump_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ func runDumpRepository(ctx *cli.Context) error {
opts.PullRequests = true
opts.ReleaseAssets = true
} else {
units := strings.Split(ctx.String("units"), ",")
for _, unit := range units {
units := strings.SplitSeq(ctx.String("units"), ",")
for unit := range units {
switch strings.ToLower(strings.TrimSpace(unit)) {
case "":
continue
Expand Down
4 changes: 2 additions & 2 deletions cmd/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ func hookPrintResult(output, isCreate bool, branch, url string) {
func pushOptions() map[string]string {
opts := make(map[string]string)
if pushCount, err := strconv.Atoi(os.Getenv(private.GitPushOptionCount)); err == nil {
for idx := 0; idx < pushCount; idx++ {
for idx := range pushCount {
opt := os.Getenv(fmt.Sprintf("GIT_PUSH_OPTION_%d", idx))
kv := strings.SplitN(opt, "=", 2)
if len(kv) == 2 {
Expand Down Expand Up @@ -740,7 +740,7 @@ func readPktLine(ctx context.Context, in *bufio.Reader, requestType pktLineType)

// read prefix
lengthBytes := make([]byte, 4)
for i := 0; i < 4; i++ {
for i := range 4 {
lengthBytes[i], err = in.ReadByte()
if err != nil {
return nil, fail(ctx, "Protocol: stdin error", "Pkt-Line: read stdin failed : %v", err)
Expand Down
3 changes: 2 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package cmd
import (
"fmt"
"os"
"slices"
"strings"

"code.gitea.io/gitea/modules/log"
Expand Down Expand Up @@ -75,7 +76,7 @@ func appGlobalFlags() []cli.Flag {
}

func prepareSubcommandWithConfig(command *cli.Command, globalFlags []cli.Flag) {
command.Flags = append(append([]cli.Flag{}, globalFlags...), command.Flags...)
command.Flags = slices.Concat(globalFlags, command.Flags)
command.Action = prepareWorkPathAndCustomConf(command.Action)
command.HideHelp = true
if command.Name != "help" {
Expand Down
4 changes: 2 additions & 2 deletions contrib/backport/backport.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,8 +342,8 @@ func determineRemote(ctx context.Context, forkUser string) (string, string, erro
fmt.Fprintf(os.Stderr, "Unable to list git remotes:\n%s\n", string(out))
return "", "", fmt.Errorf("unable to determine forked remote: %w", err)
}
lines := strings.Split(string(out), "\n")
for _, line := range lines {
lines := strings.SplitSeq(string(out), "\n")
for line := range lines {
fields := strings.Split(line, "\t")
name, remote := fields[0], fields[1]
// only look at pushers
Expand Down
2 changes: 1 addition & 1 deletion contrib/environment-to-ini/environment-to-ini.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func main() {

func runEnvironmentToIni(c *cli.Context) error {
// the config system may change the environment variables, so get a copy first, to be used later
env := append([]string{}, os.Environ()...)
env := os.Environ()
Comment on lines 82 to +83
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change was also erroneous.
Although the code itself should probably use the maps.Clone function anyway…

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reported upstream: golang/go#72009

Copy link
Member Author

@silverwind silverwind Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually no, I think the fix is correct. os.Environ() returns string[], so maps.Clone will not work.

I think it does not make sense to clone a string[] here, or do you? I think even if the environment changes after this call, the value will stay the same.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a gopls bug. os.Environ always returns a new slice, so no need to "clone"

setting.InitWorkPathAndCfgProvider(os.Getenv, setting.ArgWorkPathAndCustomConf{
WorkPath: c.String("work-path"),
CustomPath: c.String("custom-path"),
Expand Down
9 changes: 3 additions & 6 deletions models/actions/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
package actions

import (
"slices"

"code.gitea.io/gitea/modules/translation"

runnerv1 "code.gitea.io/actions-proto-go/runner/v1"
Expand Down Expand Up @@ -88,12 +90,7 @@ func (s Status) IsBlocked() bool {

// In returns whether s is one of the given statuses
func (s Status) In(statuses ...Status) bool {
for _, v := range statuses {
if s == v {
return true
}
}
return false
return slices.Contains(statuses, s)
}

func (s Status) AsResult() runnerv1.Result {
Expand Down
8 changes: 2 additions & 6 deletions models/activities/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net/url"
"path"
"slices"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -127,12 +128,7 @@ func (at ActionType) String() string {
}

func (at ActionType) InActions(actions ...string) bool {
for _, action := range actions {
if action == at.String() {
return true
}
}
return false
return slices.Contains(actions, at.String())
}

// Action represents user operation type and other information to
Expand Down
20 changes: 4 additions & 16 deletions models/activities/notification_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,7 @@ func (nl NotificationList) LoadRepos(ctx context.Context) (repo_model.Repository
repos := make(map[int64]*repo_model.Repository, len(repoIDs))
left := len(repoIDs)
for left > 0 {
limit := db.DefaultMaxInSize
if left < limit {
limit = left
}
limit := min(left, db.DefaultMaxInSize)
rows, err := db.GetEngine(ctx).
In("id", repoIDs[:limit]).
Rows(new(repo_model.Repository))
Expand Down Expand Up @@ -282,10 +279,7 @@ func (nl NotificationList) LoadIssues(ctx context.Context) ([]int, error) {
issues := make(map[int64]*issues_model.Issue, len(issueIDs))
left := len(issueIDs)
for left > 0 {
limit := db.DefaultMaxInSize
if left < limit {
limit = left
}
limit := min(left, db.DefaultMaxInSize)
rows, err := db.GetEngine(ctx).
In("id", issueIDs[:limit]).
Rows(new(issues_model.Issue))
Expand Down Expand Up @@ -377,10 +371,7 @@ func (nl NotificationList) LoadUsers(ctx context.Context) ([]int, error) {
users := make(map[int64]*user_model.User, len(userIDs))
left := len(userIDs)
for left > 0 {
limit := db.DefaultMaxInSize
if left < limit {
limit = left
}
limit := min(left, db.DefaultMaxInSize)
rows, err := db.GetEngine(ctx).
In("id", userIDs[:limit]).
Rows(new(user_model.User))
Expand Down Expand Up @@ -428,10 +419,7 @@ func (nl NotificationList) LoadComments(ctx context.Context) ([]int, error) {
comments := make(map[int64]*issues_model.Comment, len(commentIDs))
left := len(commentIDs)
for left > 0 {
limit := db.DefaultMaxInSize
if left < limit {
limit = left
}
limit := min(left, db.DefaultMaxInSize)
rows, err := db.GetEngine(ctx).
In("id", commentIDs[:limit]).
Rows(new(issues_model.Comment))
Expand Down
5 changes: 1 addition & 4 deletions models/activities/repo_activity.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,7 @@ func GetActivityStatsTopAuthors(ctx context.Context, repo *repo_model.Repository
return v[i].Commits > v[j].Commits
})

cnt := count
if cnt > len(v) {
cnt = len(v)
}
cnt := min(count, len(v))

return v[:cnt], nil
}
Expand Down
8 changes: 2 additions & 6 deletions models/auth/access_token_scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package auth

import (
"fmt"
"slices"
"strings"

"code.gitea.io/gitea/models/perm"
Expand Down Expand Up @@ -204,12 +205,7 @@ func GetRequiredScopes(level AccessTokenScopeLevel, scopeCategories ...AccessTok

// ContainsCategory checks if a list of categories contains a specific category
func ContainsCategory(categories []AccessTokenScopeCategory, category AccessTokenScopeCategory) bool {
for _, c := range categories {
if c == category {
return true
}
}
return false
return slices.Contains(categories, category)
}

// GetScopeLevelFromAccessMode converts permission access mode to scope level
Expand Down
8 changes: 2 additions & 6 deletions models/auth/oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"fmt"
"net"
"net/url"
"slices"
"strings"

"code.gitea.io/gitea/models/db"
Expand Down Expand Up @@ -511,12 +512,7 @@ func (grant *OAuth2Grant) IncreaseCounter(ctx context.Context) error {

// ScopeContains returns true if the grant scope contains the specified scope
func (grant *OAuth2Grant) ScopeContains(scope string) bool {
for _, currentScope := range strings.Split(grant.Scope, " ") {
if scope == currentScope {
return true
}
}
return false
return slices.Contains(strings.Split(grant.Scope, " "), scope)
}

// SetNonce updates the current nonce value of a grant
Expand Down
4 changes: 2 additions & 2 deletions models/db/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func contextSafetyCheck(e Engine) {
_ = e.SQL("SELECT 1").Iterate(&m{}, func(int, any) error {
callers := make([]uintptr, 32)
callerNum := runtime.Callers(1, callers)
for i := 0; i < callerNum; i++ {
for i := range callerNum {
if funcName := runtime.FuncForPC(callers[i]).Name(); funcName == "xorm.io/xorm.(*Session).Iterate" {
contextSafetyDeniedFuncPCs = append(contextSafetyDeniedFuncPCs, callers[i])
}
Expand All @@ -82,7 +82,7 @@ func contextSafetyCheck(e Engine) {
// it should be very fast: xxxx ns/op
callers := make([]uintptr, 32)
callerNum := runtime.Callers(3, callers) // skip 3: runtime.Callers, contextSafetyCheck, GetEngine
for i := 0; i < callerNum; i++ {
for i := range callerNum {
if slices.Contains(contextSafetyDeniedFuncPCs, callers[i]) {
panic(errors.New("using database context in an iterator would cause corrupted results"))
}
Expand Down
7 changes: 3 additions & 4 deletions models/db/name.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package db

import (
"fmt"
"slices"
"strings"
"unicode/utf8"

Expand Down Expand Up @@ -80,10 +81,8 @@ func IsUsableName(reservedNames, reservedPatterns []string, name string) error {
return util.SilentWrap{Message: "name is empty", Err: util.ErrInvalidArgument}
}

for i := range reservedNames {
if name == reservedNames[i] {
return ErrNameReserved{name}
}
if slices.Contains(reservedNames, name) {
return ErrNameReserved{name}
}

for _, pat := range reservedPatterns {
Expand Down
20 changes: 4 additions & 16 deletions models/dbfs/dbfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ func (f *file) readAt(fileMeta *dbfsMeta, offset int64, p []byte) (n int, err er
blobPos := int(offset % f.blockSize)
blobOffset := offset - int64(blobPos)
blobRemaining := int(f.blockSize) - blobPos
needRead := len(p)
if needRead > blobRemaining {
needRead = blobRemaining
}
needRead := min(len(p), blobRemaining)
if blobOffset+int64(blobPos)+int64(needRead) > fileMeta.FileSize {
needRead = int(fileMeta.FileSize - blobOffset - int64(blobPos))
}
Expand All @@ -66,14 +63,8 @@ func (f *file) readAt(fileMeta *dbfsMeta, offset int64, p []byte) (n int, err er
blobData = nil
}

canCopy := len(blobData) - blobPos
if canCopy <= 0 {
canCopy = 0
}
realRead := needRead
if realRead > canCopy {
realRead = canCopy
}
canCopy := max(len(blobData)-blobPos, 0)
realRead := min(needRead, canCopy)
if realRead > 0 {
copy(p[:realRead], fileData.BlobData[blobPos:blobPos+realRead])
}
Expand Down Expand Up @@ -113,10 +104,7 @@ func (f *file) Write(p []byte) (n int, err error) {
blobPos := int(f.offset % f.blockSize)
blobOffset := f.offset - int64(blobPos)
blobRemaining := int(f.blockSize) - blobPos
needWrite := len(p)
if needWrite > blobRemaining {
needWrite = blobRemaining
}
needWrite := min(len(p), blobRemaining)
buf := make([]byte, f.blockSize)
readBytes, err := f.readAt(fileMeta, blobOffset, buf)
if err != nil && !errors.Is(err, io.EOF) {
Expand Down
4 changes: 2 additions & 2 deletions models/git/protected_branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func init() {

// IsRuleNameSpecial return true if it contains special character
func IsRuleNameSpecial(ruleName string) bool {
for i := 0; i < len(ruleName); i++ {
for i := range len(ruleName) {
if syntax.Special(ruleName[i]) {
return true
}
Expand Down Expand Up @@ -246,7 +246,7 @@ func (protectBranch *ProtectedBranch) GetUnprotectedFilePatterns() []glob.Glob {

func getFilePatterns(filePatterns string) []glob.Glob {
extarr := make([]glob.Glob, 0, 10)
for _, expr := range strings.Split(strings.ToLower(filePatterns), ";") {
for expr := range strings.SplitSeq(strings.ToLower(filePatterns), ";") {
expr = strings.TrimSpace(expr)
if expr != "" {
if g, err := glob.Compile(expr, '.', '/'); err != nil {
Expand Down
3 changes: 2 additions & 1 deletion models/issues/assignees.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package issues
import (
"context"
"fmt"
"slices"

"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
Expand Down Expand Up @@ -162,7 +163,7 @@ func toggleUserAssignee(ctx context.Context, issue *Issue, assigneeID int64) (re

assigneeIn := IssueAssignees{AssigneeID: assigneeID, IssueID: issue.ID}
if found {
issue.Assignees = append(issue.Assignees[:i], issue.Assignees[i+1:]...)
issue.Assignees = slices.Delete(issue.Assignees, i, i+1)
_, err = db.DeleteByBean(ctx, &assigneeIn)
if err != nil {
return found, err
Expand Down
10 changes: 3 additions & 7 deletions models/issues/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"context"
"fmt"
"html/template"
"slices"
"strconv"
"unicode/utf8"

Expand Down Expand Up @@ -196,12 +197,7 @@ func (t CommentType) HasMailReplySupport() bool {
}

func (t CommentType) CountedAsConversation() bool {
for _, ct := range ConversationCountedCommentType() {
if t == ct {
return true
}
}
return false
return slices.Contains(ConversationCountedCommentType(), t)
}

// ConversationCountedCommentType returns the comment types that are counted as a conversation
Expand Down Expand Up @@ -614,7 +610,7 @@ func UpdateCommentAttachments(ctx context.Context, c *Comment, uuids []string) e
if err != nil {
return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %w", uuids, err)
}
for i := 0; i < len(attachments); i++ {
for i := range attachments {
attachments[i].IssueID = c.IssueID
attachments[i].CommentID = c.ID
if err := repo_model.UpdateAttachment(ctx, attachments[i]); err != nil {
Expand Down
Loading
Loading