From 81b6cff783db6954ac5ef992b9c09c77f730282b Mon Sep 17 00:00:00 2001 From: silverwind Date: Thu, 27 Feb 2025 11:54:13 +0100 Subject: [PATCH 1/4] Add gopls modernize formatting --- Makefile | 8 ++-- cmd/cert.go | 4 +- cmd/doctor.go | 2 +- cmd/dump_repo.go | 4 +- cmd/hook.go | 4 +- cmd/main.go | 3 +- contrib/backport/backport.go | 4 +- .../environment-to-ini/environment-to-ini.go | 2 +- models/actions/status.go | 9 ++-- models/activities/action.go | 8 +--- models/activities/notification_list.go | 20 ++------- models/activities/repo_activity.go | 5 +-- models/auth/access_token_scope.go | 8 +--- models/auth/oauth2.go | 8 +--- models/db/context.go | 4 +- models/db/name.go | 7 ++- models/dbfs/dbfile.go | 20 ++------- models/git/protected_branch.go | 4 +- models/issues/assignees.go | 3 +- models/issues/comment.go | 10 ++--- models/issues/comment_list.go | 35 +++------------ models/issues/content_history.go | 3 +- models/issues/issue_list.go | 45 ++++--------------- models/issues/issue_stats.go | 5 +-- models/issues/issue_test.go | 7 +-- models/issues/issue_update.go | 2 +- models/issues/issue_xref.go | 3 +- models/issues/review_list.go | 2 +- models/issues/tracked_time.go | 5 +-- models/migrations/base/db.go | 2 +- models/migrations/v1_11/v111.go | 7 ++- models/migrations/v1_11/v112.go | 2 +- models/migrations/v1_11/v115.go | 2 +- models/migrations/v1_12/v128.go | 3 +- models/migrations/v1_12/v134.go | 3 +- models/migrations/v1_20/v259.go | 2 +- models/organization/org_worktime.go | 2 +- models/perm/access/repo_permission.go | 2 +- models/project/column_test.go | 2 +- models/pull/review_state.go | 5 +-- models/repo/repo_list.go | 4 +- models/repo/repo_unit.go | 6 +-- models/repo/upload.go | 2 +- models/unit/unit.go | 17 ++----- models/unittest/consistency.go | 2 +- models/user/avatar.go | 2 +- models/user/email_address_test.go | 8 +--- models/user/user_list.go | 5 +-- models/user/user_test.go | 4 +- models/webhook/webhook.go | 2 +- modules/actions/workflows.go | 15 +++---- modules/auth/password/password.go | 2 +- modules/auth/password/password_test.go | 2 +- modules/auth/password/pwn/pwn.go | 2 +- modules/avatar/identicon/block.go | 4 +- modules/avatar/identicon/identicon.go | 4 +- modules/cache/cache.go | 2 +- modules/charset/charset.go | 2 +- modules/charset/charset_test.go | 2 +- modules/eventsource/messenger.go | 4 +- modules/git/commit_info_nogogit.go | 5 +-- modules/git/diff_test.go | 2 +- modules/git/foreachref/format.go | 2 +- modules/git/hook.go | 8 +--- modules/git/last_commit_cache.go | 2 +- modules/git/log_name_status.go | 8 ++-- modules/git/repo.go | 4 +- modules/git/repo_attribute.go | 2 +- modules/git/repo_commit.go | 4 +- modules/git/repo_index.go | 2 +- modules/git/repo_tag.go | 6 +-- modules/git/tree.go | 2 +- modules/git/tree_entry.go | 4 +- modules/git/tree_test.go | 2 +- modules/git/url/url.go | 2 +- modules/globallock/globallock_test.go | 2 +- modules/graceful/net_unix.go | 9 ++-- modules/hostmatcher/hostmatcher.go | 11 +++-- modules/httpcache/httpcache.go | 2 +- modules/indexer/code/bleve/token/path/path.go | 2 +- modules/indexer/code/git.go | 4 +- modules/indexer/code/search.go | 2 +- .../indexer/internal/elasticsearch/util.go | 2 +- modules/indexer/internal/meilisearch/util.go | 2 +- .../indexer/issues/internal/tests/tests.go | 2 +- modules/issue/template/template.go | 8 +--- modules/label/parser.go | 4 +- modules/log/event_format.go | 6 +-- modules/log/event_writer_base.go | 2 +- modules/log/flags.go | 2 +- modules/log/level_test.go | 6 +-- modules/markup/html.go | 9 +--- modules/markup/html_commit.go | 2 +- modules/markup/html_link.go | 4 +- modules/markup/markdown/markdown.go | 5 +-- modules/markup/markdown/markdown_test.go | 2 +- .../markup/markdown/math/block_renderer.go | 2 +- modules/markup/markdown/meta_test.go | 8 ++-- modules/markup/markdown/toc.go | 2 +- modules/markup/markdown/transform_heading.go | 2 +- modules/packages/npm/creator.go | 4 +- modules/packages/npm/metadata.go | 2 +- modules/packages/nuget/symbol_extractor.go | 2 +- modules/packages/rubygems/marshal.go | 4 +- modules/packages/swift/metadata.go | 2 +- modules/paginator/paginator.go | 2 +- modules/public/public.go | 2 +- modules/queue/base_levelqueue_common.go | 2 +- modules/queue/base_redis.go | 2 +- modules/queue/base_test.go | 4 +- modules/queue/manager.go | 5 +-- modules/queue/workerqueue_test.go | 28 ++++++------ modules/repository/init.go | 2 +- modules/reqctx/datastore.go | 5 +-- modules/setting/config_env.go | 2 +- modules/setting/cron.go | 2 +- modules/setting/indexer.go | 2 +- modules/setting/log.go | 4 +- modules/setting/mirror.go | 6 +-- modules/setting/repository.go | 3 +- modules/setting/storage.go | 8 +--- modules/structs/issue.go | 2 +- modules/structs/repo.go | 2 +- modules/structs/repo_actions.go | 2 +- modules/structs/user.go | 4 +- modules/structs/user_gpgkey.go | 4 +- modules/structs/user_key.go | 2 +- modules/templates/htmlrenderer.go | 2 +- modules/templates/scopedtmpl/scopedtmpl.go | 13 ++---- modules/templates/util_dict.go | 4 +- modules/templates/util_slice.go | 2 +- modules/testlogger/testlogger.go | 2 +- modules/translation/i18n/format.go | 2 +- modules/util/remove.go | 6 +-- .../util/rotatingfilewriter/writer_test.go | 2 +- modules/util/string.go | 4 +- modules/validation/helpers.go | 8 +--- modules/web/handler.go | 2 +- modules/web/middleware/binding.go | 4 +- modules/web/router.go | 6 +-- modules/web/router_path.go | 2 +- routers/api/actions/artifactsv4.go | 4 +- routers/api/packages/cargo/cargo.go | 5 +-- routers/api/packages/composer/composer.go | 5 +-- routers/api/v1/repo/action.go | 4 +- routers/api/v1/repo/compare.go | 2 +- routers/api/v1/repo/issue_dependency.go | 10 +---- routers/api/v1/repo/wiki.go | 10 +---- routers/common/db.go | 2 +- routers/install/install.go | 8 ++-- routers/web/admin/auths.go | 2 +- routers/web/admin/config.go | 2 +- routers/web/admin/diagnosis.go | 5 +-- routers/web/admin/notice.go | 5 +-- routers/web/admin/packages.go | 5 +-- routers/web/auth/openid.go | 5 +-- routers/web/devtest/mock_actions.go | 2 +- routers/web/explore/code.go | 8 ++-- routers/web/org/members.go | 5 +-- routers/web/org/projects.go | 5 +-- routers/web/repo/actions/actions.go | 6 +-- routers/web/repo/branch.go | 5 +-- routers/web/repo/commit.go | 12 ++--- routers/web/repo/compare.go | 2 +- routers/web/repo/editor.go | 2 +- routers/web/repo/fork.go | 3 +- routers/web/repo/githttp.go | 8 +--- routers/web/repo/issue.go | 6 +-- routers/web/repo/issue_comment.go | 2 +- routers/web/repo/issue_list.go | 5 +-- routers/web/repo/issue_new.go | 5 +-- routers/web/repo/issue_view.go | 9 ++-- routers/web/repo/milestone.go | 5 +-- routers/web/repo/packages.go | 5 +-- routers/web/repo/projects.go | 5 +-- routers/web/repo/repo.go | 2 +- routers/web/repo/setting/lfs.go | 12 ++--- routers/web/repo/wiki.go | 5 +-- routers/web/shared/actions/runners.go | 10 +---- routers/web/user/code.go | 8 ++-- routers/web/user/home.go | 9 ++-- routers/web/user/notification.go | 10 +---- routers/web/user/package.go | 10 +---- services/actions/job_emitter.go | 2 +- services/actions/rerun.go | 13 +++--- services/auth/source/oauth2/urlmapping.go | 10 ++--- services/context/api.go | 9 +--- services/context/permission.go | 7 ++- services/context/upload/upload.go | 2 +- services/convert/git_commit.go | 2 +- services/doctor/mergebase.go | 3 +- services/feed/feed_test.go | 2 +- services/forms/repo_form.go | 9 +--- services/gitdiff/csv.go | 14 +++--- services/gitdiff/gitdiff.go | 5 +-- services/gitdiff/gitdiff_test.go | 6 +-- services/gitdiff/highlightdiff.go | 2 +- services/gitdiff/highlightdiff_test.go | 2 +- services/lfs/locks.go | 10 +---- services/lfs/server.go | 5 +-- services/mailer/sender/message_test.go | 4 +- services/migrations/codecommit.go | 5 +-- services/migrations/dump.go | 2 +- services/migrations/gitea_uploader_test.go | 4 +- services/migrations/github.go | 6 +-- services/oauth2_provider/access_token.go | 2 +- services/org/team_test.go | 2 +- services/packages/arch/vercmp.go | 8 +--- services/packages/arch/vercmp_test.go | 2 +- services/pull/merge.go | 5 +-- services/repository/adopt_test.go | 2 +- .../repository/commitstatus/commitstatus.go | 2 +- services/repository/create.go | 4 +- services/repository/delete.go | 2 +- services/repository/files/file.go | 2 +- services/repository/files/temp_repo.go | 2 +- services/repository/files/tree.go | 6 +-- services/repository/files/update.go | 17 +++---- services/repository/gitgraph/graph_test.go | 27 +++-------- services/repository/push.go | 2 +- services/wiki/wiki_test.go | 4 +- tests/integration/actions_job_test.go | 4 +- .../api_helper_for_declarative_test.go | 2 +- tests/integration/api_issue_test.go | 12 ++--- tests/integration/api_packages_chef_test.go | 8 ++-- .../api_packages_container_test.go | 2 +- tests/integration/api_packages_debian_test.go | 2 +- tests/integration/api_packages_maven_test.go | 2 +- .../integration/api_repo_file_create_test.go | 4 +- tests/integration/auth_ldap_test.go | 2 +- tests/integration/compare_test.go | 2 +- tests/integration/dump_restore_test.go | 2 +- .../git_helper_for_declarative_test.go | 4 +- tests/integration/git_push_test.go | 12 ++--- tests/integration/gpg_git_test.go | 2 +- tests/integration/issue_test.go | 17 ++----- tests/integration/org_test.go | 2 +- tests/integration/project_test.go | 2 +- tests/integration/release_test.go | 2 +- tests/integration/repo_commits_test.go | 2 +- tests/integration/ssh_key_test.go | 2 +- tools/lint-go-gopls.sh | 4 +- 242 files changed, 458 insertions(+), 778 deletions(-) diff --git a/Makefile b/Makefile index e38fb801c318a..f1aa695767fdd 100644 --- a/Makefile +++ b/Makefile @@ -36,7 +36,8 @@ XGO_PACKAGE ?= src.techknowlogick.com/xgo@latest GO_LICENSES_PACKAGE ?= github.com/google/go-licenses@v1 GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@v1 ACTIONLINT_PACKAGE ?= github.com/rhysd/actionlint/cmd/actionlint@v1 -GOPLS_PACKAGE ?= golang.org/x/tools/gopls@v0.17.1 +GOPLS_PACKAGE ?= golang.org/x/tools/gopls@v0.18.1 +GOPLS_MODERNIZE_PACKAGE ?= golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@v0.18.1 DOCKER_IMAGE ?= gitea/gitea DOCKER_TAG ?= latest @@ -247,6 +248,7 @@ fmt: ## format the Go code -e 's/{{[ ]\{1,\}/{{/g' -e '/^[ ]\{1,\}}}/! s/[ ]\{1,\}}}/}}/g' \ -e 's/([ ]\{1,\}/(/g' -e '/^[ ]\{1,\})/! s/[ ]\{1,\})/)/g' \ $(TEMPLATES) + @$(GO) run $(GOPLS_MODERNIZE_PACKAGE) -fix ./... .PHONY: fmt-check fmt-check: fmt @@ -373,8 +375,8 @@ lint-go-vet: ## lint go files with vet .PHONY: lint-go-gopls lint-go-gopls: ## lint go files with gopls - @echo "Running gopls check..." - @GO=$(GO) GOPLS_PACKAGE=$(GOPLS_PACKAGE) tools/lint-go-gopls.sh $(GO_SOURCES_NO_BINDATA) + @echo "Running gopls..." + @GO=$(GO) GOPLS_PACKAGE=$(GOPLS_PACKAGE) GOPLS_MODERNIZE_PACKAGE=$(GOPLS_MODERNIZE_PACKAGE) tools/lint-go-gopls.sh $(GO_SOURCES_NO_BINDATA) .PHONY: lint-editorconfig lint-editorconfig: diff --git a/cmd/cert.go b/cmd/cert.go index 38241d71a3375..82c420873f436 100644 --- a/cmd/cert.go +++ b/cmd/cert.go @@ -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 { diff --git a/cmd/doctor.go b/cmd/doctor.go index e433f4adc5d3c..b9941745e1777 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -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)) } diff --git a/cmd/dump_repo.go b/cmd/dump_repo.go index 3a24cf6c5f029..aa69faec1905d 100644 --- a/cmd/dump_repo.go +++ b/cmd/dump_repo.go @@ -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 diff --git a/cmd/hook.go b/cmd/hook.go index 578380ab40db6..64b29d83b431f 100644 --- a/cmd/hook.go +++ b/cmd/hook.go @@ -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 { @@ -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) diff --git a/cmd/main.go b/cmd/main.go index 7251bd09a3fe3..f6191f46d9483 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -6,6 +6,7 @@ package cmd import ( "fmt" "os" + "slices" "strings" "code.gitea.io/gitea/modules/log" @@ -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" { diff --git a/contrib/backport/backport.go b/contrib/backport/backport.go index eb194374452c5..eedee7aed2ed8 100644 --- a/contrib/backport/backport.go +++ b/contrib/backport/backport.go @@ -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 diff --git a/contrib/environment-to-ini/environment-to-ini.go b/contrib/environment-to-ini/environment-to-ini.go index a7d7a6d293d95..4332dece7042b 100644 --- a/contrib/environment-to-ini/environment-to-ini.go +++ b/contrib/environment-to-ini/environment-to-ini.go @@ -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() setting.InitWorkPathAndCfgProvider(os.Getenv, setting.ArgWorkPathAndCustomConf{ WorkPath: c.String("work-path"), CustomPath: c.String("custom-path"), diff --git a/models/actions/status.go b/models/actions/status.go index eda2234137819..2b1d70613c71b 100644 --- a/models/actions/status.go +++ b/models/actions/status.go @@ -4,6 +4,8 @@ package actions import ( + "slices" + "code.gitea.io/gitea/modules/translation" runnerv1 "code.gitea.io/actions-proto-go/runner/v1" @@ -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 { diff --git a/models/activities/action.go b/models/activities/action.go index 52dffe07fdc93..b5478ebe9dea1 100644 --- a/models/activities/action.go +++ b/models/activities/action.go @@ -9,6 +9,7 @@ import ( "fmt" "net/url" "path" + "slices" "strconv" "strings" "time" @@ -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 diff --git a/models/activities/notification_list.go b/models/activities/notification_list.go index 0cbb91df3cb91..b47f5dc4041d5 100644 --- a/models/activities/notification_list.go +++ b/models/activities/notification_list.go @@ -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)) @@ -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)) @@ -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)) @@ -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)) diff --git a/models/activities/repo_activity.go b/models/activities/repo_activity.go index 3ccdbd47d3d7a..aeaa452c9e905 100644 --- a/models/activities/repo_activity.go +++ b/models/activities/repo_activity.go @@ -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 } diff --git a/models/auth/access_token_scope.go b/models/auth/access_token_scope.go index 897ff3fc9ee3d..4764820bdfd1f 100644 --- a/models/auth/access_token_scope.go +++ b/models/auth/access_token_scope.go @@ -5,6 +5,7 @@ package auth import ( "fmt" + "slices" "strings" "code.gitea.io/gitea/models/perm" @@ -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 diff --git a/models/auth/oauth2.go b/models/auth/oauth2.go index c270e4856e767..c2b669011649b 100644 --- a/models/auth/oauth2.go +++ b/models/auth/oauth2.go @@ -12,6 +12,7 @@ import ( "fmt" "net" "net/url" + "slices" "strings" "code.gitea.io/gitea/models/db" @@ -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 diff --git a/models/db/context.go b/models/db/context.go index 51627712b1167..69616ed870dd1 100644 --- a/models/db/context.go +++ b/models/db/context.go @@ -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]) } @@ -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")) } diff --git a/models/db/name.go b/models/db/name.go index e2165fd76bbad..2364661d88d81 100644 --- a/models/db/name.go +++ b/models/db/name.go @@ -5,6 +5,7 @@ package db import ( "fmt" + "slices" "strings" "unicode/utf8" @@ -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 { diff --git a/models/dbfs/dbfile.go b/models/dbfs/dbfile.go index dd27b5c36b798..eaf506fbe6bf6 100644 --- a/models/dbfs/dbfile.go +++ b/models/dbfs/dbfile.go @@ -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)) } @@ -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]) } @@ -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) { diff --git a/models/git/protected_branch.go b/models/git/protected_branch.go index a3caed73c40fa..ee5dcebd19477 100644 --- a/models/git/protected_branch.go +++ b/models/git/protected_branch.go @@ -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 } @@ -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 { diff --git a/models/issues/assignees.go b/models/issues/assignees.go index efd992cda2b5f..1b83690cca1e1 100644 --- a/models/issues/assignees.go +++ b/models/issues/assignees.go @@ -6,6 +6,7 @@ package issues import ( "context" "fmt" + "slices" "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" @@ -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 diff --git a/models/issues/comment.go b/models/issues/comment.go index ab9b2042f386f..9bef96d0ddfcc 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -9,6 +9,7 @@ import ( "context" "fmt" "html/template" + "slices" "strconv" "unicode/utf8" @@ -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 @@ -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 { diff --git a/models/issues/comment_list.go b/models/issues/comment_list.go index c483ada75aa23..f6c485449f60b 100644 --- a/models/issues/comment_list.go +++ b/models/issues/comment_list.go @@ -57,10 +57,7 @@ func (comments CommentList) loadLabels(ctx context.Context) error { commentLabels := make(map[int64]*Label, len(labelIDs)) left := len(labelIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := db.GetEngine(ctx). In("id", labelIDs[:limit]). Rows(new(Label)) @@ -107,10 +104,7 @@ func (comments CommentList) loadMilestones(ctx context.Context) error { milestoneMaps := make(map[int64]*Milestone, len(milestoneIDs)) left := len(milestoneIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) err := db.GetEngine(ctx). In("id", milestoneIDs[:limit]). Find(&milestoneMaps) @@ -146,10 +140,7 @@ func (comments CommentList) loadOldMilestones(ctx context.Context) error { milestoneMaps := make(map[int64]*Milestone, len(milestoneIDs)) left := len(milestoneIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) err := db.GetEngine(ctx). In("id", milestoneIDs[:limit]). Find(&milestoneMaps) @@ -184,10 +175,7 @@ func (comments CommentList) loadAssignees(ctx context.Context) error { assignees := make(map[int64]*user_model.User, len(assigneeIDs)) left := len(assigneeIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := db.GetEngine(ctx). In("id", assigneeIDs[:limit]). Rows(new(user_model.User)) @@ -256,10 +244,7 @@ func (comments CommentList) LoadIssues(ctx context.Context) error { issues := make(map[int64]*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(Issue)) @@ -313,10 +298,7 @@ func (comments CommentList) loadDependentIssues(ctx context.Context) error { issues := make(map[int64]*Issue, len(issueIDs)) left := len(issueIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := e. In("id", issueIDs[:limit]). Rows(new(Issue)) @@ -392,10 +374,7 @@ func (comments CommentList) LoadAttachments(ctx context.Context) (err error) { commentsIDs := comments.getAttachmentCommentIDs() left := len(commentsIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := db.GetEngine(ctx). In("comment_id", commentsIDs[:limit]). Rows(new(repo_model.Attachment)) diff --git a/models/issues/content_history.go b/models/issues/content_history.go index 31c80d2cea384..288009d4bad0a 100644 --- a/models/issues/content_history.go +++ b/models/issues/content_history.go @@ -6,6 +6,7 @@ package issues import ( "context" "fmt" + "slices" "code.gitea.io/gitea/models/avatars" "code.gitea.io/gitea/models/db" @@ -100,7 +101,7 @@ func KeepLimitedContentHistory(ctx context.Context, issueID, commentID int64, li log.Error("can not delete out-dated content history, err=%v", err) break } - res = append(res[:indexToDelete], res[indexToDelete+1:]...) + res = slices.Delete(res, indexToDelete, indexToDelete+1) outDatedCount-- } } diff --git a/models/issues/issue_list.go b/models/issues/issue_list.go index 6c74b533b3c54..26b93189b8bed 100644 --- a/models/issues/issue_list.go +++ b/models/issues/issue_list.go @@ -42,10 +42,7 @@ func (issues IssueList) LoadRepositories(ctx context.Context) (repo_model.Reposi repoMaps := 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) err := db.GetEngine(ctx). In("id", repoIDs[:limit]). Find(&repoMaps) @@ -116,10 +113,7 @@ func (issues IssueList) LoadLabels(ctx context.Context) error { issueIDs := issues.getIssueIDs() left := len(issueIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := db.GetEngine(ctx).Table("label"). Join("LEFT", "issue_label", "issue_label.label_id = label.id"). In("issue_label.issue_id", issueIDs[:limit]). @@ -171,10 +165,7 @@ func (issues IssueList) LoadMilestones(ctx context.Context) error { milestoneMaps := make(map[int64]*Milestone, len(milestoneIDs)) left := len(milestoneIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) err := db.GetEngine(ctx). In("id", milestoneIDs[:limit]). Find(&milestoneMaps) @@ -203,10 +194,7 @@ func (issues IssueList) LoadProjects(ctx context.Context) error { } for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) projects := make([]*projectWithIssueID, 0, limit) err := db.GetEngine(ctx). @@ -245,10 +233,7 @@ func (issues IssueList) LoadAssignees(ctx context.Context) error { issueIDs := issues.getIssueIDs() left := len(issueIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := db.GetEngine(ctx).Table("issue_assignees"). Join("INNER", "`user`", "`user`.id = `issue_assignees`.assignee_id"). In("`issue_assignees`.issue_id", issueIDs[:limit]).OrderBy(user_model.GetOrderByName()). @@ -306,10 +291,7 @@ func (issues IssueList) LoadPullRequests(ctx context.Context) error { pullRequestMaps := make(map[int64]*PullRequest, len(issuesIDs)) left := len(issuesIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := db.GetEngine(ctx). In("issue_id", issuesIDs[:limit]). Rows(new(PullRequest)) @@ -354,10 +336,7 @@ func (issues IssueList) LoadAttachments(ctx context.Context) (err error) { issuesIDs := issues.getIssueIDs() left := len(issuesIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := db.GetEngine(ctx). In("issue_id", issuesIDs[:limit]). Rows(new(repo_model.Attachment)) @@ -399,10 +378,7 @@ func (issues IssueList) loadComments(ctx context.Context, cond builder.Cond) (er issuesIDs := issues.getIssueIDs() left := len(issuesIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) rows, err := db.GetEngine(ctx).Table("comment"). Join("INNER", "issue", "issue.id = comment.issue_id"). In("issue.id", issuesIDs[:limit]). @@ -466,10 +442,7 @@ func (issues IssueList) loadTotalTrackedTimes(ctx context.Context) (err error) { left := len(ids) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) // select issue_id, sum(time) from tracked_time where issue_id in () group by issue_id rows, err := db.GetEngine(ctx).Table("tracked_time"). diff --git a/models/issues/issue_stats.go b/models/issues/issue_stats.go index 50409fbbd895d..adedaa3d3a047 100644 --- a/models/issues/issue_stats.go +++ b/models/issues/issue_stats.go @@ -94,10 +94,7 @@ func GetIssueStats(ctx context.Context, opts *IssuesOptions) (*IssueStats, error // ids in a temporary table and join from them. accum := &IssueStats{} for i := 0; i < len(opts.IssueIDs); { - chunk := i + MaxQueryParameters - if chunk > len(opts.IssueIDs) { - chunk = len(opts.IssueIDs) - } + chunk := min(i+MaxQueryParameters, len(opts.IssueIDs)) stats, err := getIssueStatsChunk(ctx, opts, opts.IssueIDs[i:chunk]) if err != nil { return nil, err diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index 3f76a81bb65d4..7c7ce666d6034 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -5,6 +5,7 @@ package issues_test import ( "fmt" + "slices" "sort" "sync" "testing" @@ -271,7 +272,7 @@ func TestIssue_ResolveMentions(t *testing.T) { for i, user := range resolved { ids[i] = user.ID } - sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) + slices.Sort(ids) assert.EqualValues(t, expected, ids) } @@ -293,7 +294,7 @@ func TestResourceIndex(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) var wg sync.WaitGroup - for i := 0; i < 100; i++ { + for i := range 100 { wg.Add(1) go func(i int) { testInsertIssue(t, fmt.Sprintf("issue %d", i+1), "my issue", 0) @@ -315,7 +316,7 @@ func TestCorrectIssueStats(t *testing.T) { issueAmount := issues_model.MaxQueryParameters + 10 var wg sync.WaitGroup - for i := 0; i < issueAmount; i++ { + for i := range issueAmount { wg.Add(1) go func(i int) { testInsertIssue(t, fmt.Sprintf("Issue %d", i+1), "Bugs are nasty", 0) diff --git a/models/issues/issue_update.go b/models/issues/issue_update.go index 7b3fe04aa5b10..caa93642a913f 100644 --- a/models/issues/issue_update.go +++ b/models/issues/issue_update.go @@ -306,7 +306,7 @@ func UpdateIssueAttachments(ctx context.Context, issueID int64, uuids []string) 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 = issueID if err := repo_model.UpdateAttachment(ctx, attachments[i]); err != nil { return fmt.Errorf("update attachment [id: %d]: %w", attachments[i].ID, err) diff --git a/models/issues/issue_xref.go b/models/issues/issue_xref.go index e2e35859df149..e95cf34a06f6d 100644 --- a/models/issues/issue_xref.go +++ b/models/issues/issue_xref.go @@ -6,6 +6,7 @@ package issues import ( "context" "fmt" + "slices" "code.gitea.io/gitea/models/db" access_model "code.gitea.io/gitea/models/perm/access" @@ -91,7 +92,7 @@ func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossRefe for i, x := range xreflist { if x.Issue.ID == c.IssueID && x.Action == c.RefAction { found = true - xreflist = append(xreflist[:i], xreflist[i+1:]...) + xreflist = slices.Delete(xreflist, i, i+1) break } } diff --git a/models/issues/review_list.go b/models/issues/review_list.go index 928f24fb2dcd7..bbb8c489fa133 100644 --- a/models/issues/review_list.go +++ b/models/issues/review_list.go @@ -22,7 +22,7 @@ type ReviewList []*Review // LoadReviewers loads reviewers func (reviews ReviewList) LoadReviewers(ctx context.Context) error { reviewerIDs := make([]int64, len(reviews)) - for i := 0; i < len(reviews); i++ { + for i := range reviews { reviewerIDs[i] = reviews[i].ReviewerID } reviewers, err := user_model.GetPossibleUserByIDs(ctx, reviewerIDs) diff --git a/models/issues/tracked_time.go b/models/issues/tracked_time.go index ea404d36cd162..2afbe272ed410 100644 --- a/models/issues/tracked_time.go +++ b/models/issues/tracked_time.go @@ -350,10 +350,7 @@ func GetIssueTotalTrackedTime(ctx context.Context, opts *IssuesOptions, isClosed // we get the statistics in smaller chunks and get accumulates var accum int64 for i := 0; i < len(opts.IssueIDs); { - chunk := i + MaxQueryParameters - if chunk > len(opts.IssueIDs) { - chunk = len(opts.IssueIDs) - } + chunk := min(i+MaxQueryParameters, len(opts.IssueIDs)) time, err := getIssueTotalTrackedTimeChunk(ctx, opts, isClosed, opts.IssueIDs[i:chunk]) if err != nil { return 0, err diff --git a/models/migrations/base/db.go b/models/migrations/base/db.go index eb1c44a79e6f5..001c4a73eac87 100644 --- a/models/migrations/base/db.go +++ b/models/migrations/base/db.go @@ -518,7 +518,7 @@ func ModifyColumn(x *xorm.Engine, tableName string, col *schemas.Column) error { func removeAllWithRetry(dir string) error { var err error - for i := 0; i < 20; i++ { + for range 20 { err = os.RemoveAll(dir) if err == nil { break diff --git a/models/migrations/v1_11/v111.go b/models/migrations/v1_11/v111.go index ff108479a9d4b..1c8527b2aab3f 100644 --- a/models/migrations/v1_11/v111.go +++ b/models/migrations/v1_11/v111.go @@ -5,6 +5,7 @@ package v1_11 //nolint import ( "fmt" + "slices" "xorm.io/xorm" ) @@ -344,10 +345,8 @@ func AddBranchProtectionCanPushAndEnableWhitelist(x *xorm.Engine) error { } return AccessModeWrite <= perm.UnitsMode[UnitTypeCode], nil } - for _, id := range protectedBranch.ApprovalsWhitelistUserIDs { - if id == reviewer.ID { - return true, nil - } + if slices.Contains(protectedBranch.ApprovalsWhitelistUserIDs, reviewer.ID) { + return true, nil } // isUserInTeams diff --git a/models/migrations/v1_11/v112.go b/models/migrations/v1_11/v112.go index 0857663119535..8d685054b741e 100644 --- a/models/migrations/v1_11/v112.go +++ b/models/migrations/v1_11/v112.go @@ -28,7 +28,7 @@ func RemoveAttachmentMissedRepo(x *xorm.Engine) error { return err } - for i := 0; i < len(attachments); i++ { + for i := range attachments { uuid := attachments[i].UUID if err = util.RemoveAll(filepath.Join(setting.Attachment.Storage.Path, uuid[0:1], uuid[1:2], uuid)); err != nil { fmt.Printf("Error: %v", err) //nolint:forbidigo diff --git a/models/migrations/v1_11/v115.go b/models/migrations/v1_11/v115.go index 8c631cfd0bbf3..c44c6d88e4d96 100644 --- a/models/migrations/v1_11/v115.go +++ b/models/migrations/v1_11/v115.go @@ -146,7 +146,7 @@ func copyOldAvatarToNewLocation(userID int64, oldAvatar string) (string, error) return "", fmt.Errorf("io.ReadAll: %w", err) } - newAvatar := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", userID, md5.Sum(data))))) + newAvatar := fmt.Sprintf("%x", md5.Sum(fmt.Appendf(nil, "%d-%x", userID, md5.Sum(data)))) if newAvatar == oldAvatar { return newAvatar, nil } diff --git a/models/migrations/v1_12/v128.go b/models/migrations/v1_12/v128.go index 44d44a26c549f..396a376de0645 100644 --- a/models/migrations/v1_12/v128.go +++ b/models/migrations/v1_12/v128.go @@ -7,6 +7,7 @@ import ( "fmt" "math" "path/filepath" + "slices" "strings" "time" @@ -102,7 +103,7 @@ func FixMergeBase(x *xorm.Engine) error { continue } - refs := append([]string{}, parents[1:]...) + refs := slices.Clone(parents[1:]) refs = append(refs, gitRefName) cmd := git.NewCommand(git.DefaultContext, "merge-base").AddDashesAndList(refs...) diff --git a/models/migrations/v1_12/v134.go b/models/migrations/v1_12/v134.go index 3d1c82f09e164..198420212bfb2 100644 --- a/models/migrations/v1_12/v134.go +++ b/models/migrations/v1_12/v134.go @@ -7,6 +7,7 @@ import ( "fmt" "math" "path/filepath" + "slices" "strings" "time" @@ -90,7 +91,7 @@ func RefixMergeBase(x *xorm.Engine) error { } // we should recalculate - refs := append([]string{}, parents[1:]...) + refs := slices.Clone(parents[1:]) refs = append(refs, gitRefName) cmd := git.NewCommand(git.DefaultContext, "merge-base").AddDashesAndList(refs...) diff --git a/models/migrations/v1_20/v259.go b/models/migrations/v1_20/v259.go index 5b8ced4ad7b41..0fdeb45957866 100644 --- a/models/migrations/v1_20/v259.go +++ b/models/migrations/v1_20/v259.go @@ -329,7 +329,7 @@ func ConvertScopedAccessTokens(x *xorm.Engine) error { for _, token := range tokens { var scopes []string allNewScopesMap := make(map[AccessTokenScope]bool) - for _, oldScope := range strings.Split(token.Scope, ",") { + for oldScope := range strings.SplitSeq(token.Scope, ",") { if newScopes, exists := accessTokenScopeMap[OldAccessTokenScope(oldScope)]; exists { for _, newScope := range newScopes { allNewScopesMap[newScope] = true diff --git a/models/organization/org_worktime.go b/models/organization/org_worktime.go index 7b57182a8a748..9a0b84353483f 100644 --- a/models/organization/org_worktime.go +++ b/models/organization/org_worktime.go @@ -69,7 +69,7 @@ func GetWorktimeByMilestones(org *Organization, unitFrom, unixTo int64) (results // Show only the first RepoName, for nicer output. prevRepoName := "" - for i := 0; i < len(results); i++ { + for i := range results { res := &results[i] res.MilestoneDeadline = 0 // clear the deadline because we do not really need it if prevRepoName == res.RepoName { diff --git a/models/perm/access/repo_permission.go b/models/perm/access/repo_permission.go index 5e7ecb31eabbd..a191f10cd89b5 100644 --- a/models/perm/access/repo_permission.go +++ b/models/perm/access/repo_permission.go @@ -444,7 +444,7 @@ func getUsersWithAccessMode(ctx context.Context, repo *repo_model.Repository, mo users := make([]*user_model.User, 0, len(accesses)+1) if len(accesses) > 0 { userIDs := make([]int64, len(accesses)) - for i := 0; i < len(accesses); i++ { + for i := range accesses { userIDs[i] = accesses[i].UserID } diff --git a/models/project/column_test.go b/models/project/column_test.go index 66db23a3e429c..148fe4b6db9a9 100644 --- a/models/project/column_test.go +++ b/models/project/column_test.go @@ -110,7 +110,7 @@ func Test_NewColumn(t *testing.T) { assert.NoError(t, err) assert.Len(t, columns, 3) - for i := 0; i < maxProjectColumns-3; i++ { + for i := range maxProjectColumns - 3 { err := NewColumn(db.DefaultContext, &Column{ Title: fmt.Sprintf("column-%d", i+4), ProjectID: project1.ID, diff --git a/models/pull/review_state.go b/models/pull/review_state.go index e46a22a49d66a..137af00eab2d0 100644 --- a/models/pull/review_state.go +++ b/models/pull/review_state.go @@ -6,6 +6,7 @@ package pull import ( "context" "fmt" + "maps" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/log" @@ -100,9 +101,7 @@ func mergeFiles(oldFiles, newFiles map[string]ViewedState) map[string]ViewedStat return oldFiles } - for file, viewed := range newFiles { - oldFiles[file] = viewed - } + maps.Copy(oldFiles, newFiles) return oldFiles } diff --git a/models/repo/repo_list.go b/models/repo/repo_list.go index 9bed2e919723b..b9b12c33b0604 100644 --- a/models/repo/repo_list.go +++ b/models/repo/repo_list.go @@ -454,7 +454,7 @@ func SearchRepositoryCondition(opts *SearchRepoOptions) builder.Cond { if opts.Keyword != "" { // separate keyword subQueryCond := builder.NewCond() - for _, v := range strings.Split(opts.Keyword, ",") { + for v := range strings.SplitSeq(opts.Keyword, ",") { if opts.TopicOnly { subQueryCond = subQueryCond.Or(builder.Eq{"topic.name": strings.ToLower(v)}) } else { @@ -469,7 +469,7 @@ func SearchRepositoryCondition(opts *SearchRepoOptions) builder.Cond { keywordCond := builder.In("id", subQuery) if !opts.TopicOnly { likes := builder.NewCond() - for _, v := range strings.Split(opts.Keyword, ",") { + for v := range strings.SplitSeq(opts.Keyword, ",") { likes = likes.Or(builder.Like{"lower_name", strings.ToLower(v)}) // If the string looks like "org/repo", match against that pattern too diff --git a/models/repo/repo_unit.go b/models/repo/repo_unit.go index cb52c2c9e2058..fb0d46e004599 100644 --- a/models/repo/repo_unit.go +++ b/models/repo/repo_unit.go @@ -185,10 +185,8 @@ func (cfg *ActionsConfig) IsWorkflowDisabled(file string) bool { } func (cfg *ActionsConfig) DisableWorkflow(file string) { - for _, workflow := range cfg.DisabledWorkflows { - if file == workflow { - return - } + if slices.Contains(cfg.DisabledWorkflows, file) { + return } cfg.DisabledWorkflows = append(cfg.DisabledWorkflows, file) diff --git a/models/repo/upload.go b/models/repo/upload.go index 18834f6b83fcc..c32627a64a72c 100644 --- a/models/repo/upload.go +++ b/models/repo/upload.go @@ -128,7 +128,7 @@ func DeleteUploads(ctx context.Context, uploads ...*Upload) (err error) { defer committer.Close() ids := make([]int64, len(uploads)) - for i := 0; i < len(uploads); i++ { + for i := range uploads { ids[i] = uploads[i].ID } if err = db.DeleteByIDs[Upload](ctx, ids...); err != nil { diff --git a/models/unit/unit.go b/models/unit/unit.go index c816fc6c68861..ef11c006c320c 100644 --- a/models/unit/unit.go +++ b/models/unit/unit.go @@ -6,6 +6,7 @@ package unit import ( "errors" "fmt" + "slices" "strings" "sync/atomic" @@ -144,7 +145,7 @@ func validateDefaultRepoUnits(defaultUnits, settingDefaultUnits []Type) []Type { for _, disabledUnit := range DisabledRepoUnitsGet() { for i, unit := range units { if unit == disabledUnit { - units = append(units[:i], units[i+1:]...) + units = slices.Delete(units, i, i+1) } } } @@ -200,22 +201,12 @@ func LoadUnitConfig() error { // UnitGlobalDisabled checks if unit type is global disabled func (u Type) UnitGlobalDisabled() bool { - for _, ud := range DisabledRepoUnitsGet() { - if u == ud { - return true - } - } - return false + return slices.Contains(DisabledRepoUnitsGet(), u) } // CanBeDefault checks if the unit type can be a default repo unit func (u *Type) CanBeDefault() bool { - for _, nadU := range NotAllowedDefaultRepoUnits { - if *u == nadU { - return false - } - } - return true + return !slices.Contains(NotAllowedDefaultRepoUnits, *u) } // Unit is a section of one repository diff --git a/models/unittest/consistency.go b/models/unittest/consistency.go index 71839001be08d..ddd98b72c9fa1 100644 --- a/models/unittest/consistency.go +++ b/models/unittest/consistency.go @@ -35,7 +35,7 @@ func CheckConsistencyFor(t assert.TestingT, beansToCheck ...any) { assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface())) sliceValue = ptrToSliceValue.Elem() - for i := 0; i < sliceValue.Len(); i++ { + for i := range sliceValue.Len() { entity := sliceValue.Index(i).Interface() checkForConsistency(t, entity) } diff --git a/models/user/avatar.go b/models/user/avatar.go index 2a41b9912928b..91b41e4dfb115 100644 --- a/models/user/avatar.go +++ b/models/user/avatar.go @@ -104,7 +104,7 @@ func (u *User) IsUploadAvatarChanged(data []byte) bool { if !u.UseCustomAvatar || len(u.Avatar) == 0 { return true } - avatarID := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", u.ID, md5.Sum(data))))) + avatarID := fmt.Sprintf("%x", md5.Sum(fmt.Appendf(nil, "%d-%x", u.ID, md5.Sum(data)))) return u.Avatar != avatarID } diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index d72d873de2ca7..81fe0a471e838 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -4,6 +4,7 @@ package user_test import ( + "slices" "testing" "code.gitea.io/gitea/models/db" @@ -100,12 +101,7 @@ func TestListEmails(t *testing.T) { assert.Greater(t, count, int64(5)) contains := func(match func(s *user_model.SearchEmailResult) bool) bool { - for _, v := range emails { - if match(v) { - return true - } - } - return false + return slices.ContainsFunc(emails, match) } assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 18 })) diff --git a/models/user/user_list.go b/models/user/user_list.go index c66d59f0d9245..ab6211e484448 100644 --- a/models/user/user_list.go +++ b/models/user/user_list.go @@ -13,10 +13,7 @@ func GetUsersMapByIDs(ctx context.Context, userIDs []int64) (map[int64]*User, er userMaps := make(map[int64]*User, len(userIDs)) left := len(userIDs) for left > 0 { - limit := db.DefaultMaxInSize - if left < limit { - limit = left - } + limit := min(left, db.DefaultMaxInSize) err := db.GetEngine(ctx). In("id", userIDs[:limit]). Find(&userMaps) diff --git a/models/user/user_test.go b/models/user/user_test.go index 1132c02f287c7..9f7cf9f89afd3 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -173,9 +173,9 @@ func TestHashPasswordDeterministic(t *testing.T) { b := make([]byte, 16) u := &user_model.User{} algos := hash.RecommendedHashAlgorithms - for j := 0; j < len(algos); j++ { + for j := range algos { u.PasswdHashAlgo = algos[j] - for i := 0; i < 50; i++ { + for range 50 { // generate a random password rand.Read(b) pass := string(b) diff --git a/models/webhook/webhook.go b/models/webhook/webhook.go index 97ad373027739..b234d9ffee519 100644 --- a/models/webhook/webhook.go +++ b/models/webhook/webhook.go @@ -240,7 +240,7 @@ func CreateWebhooks(ctx context.Context, ws []*Webhook) error { if len(ws) == 0 { return nil } - for i := 0; i < len(ws); i++ { + for i := range ws { ws[i].Type = strings.TrimSpace(ws[i].Type) } return db.Insert(ctx, ws) diff --git a/modules/actions/workflows.go b/modules/actions/workflows.go index 0d2b0dd9194d9..46efbdb620c4c 100644 --- a/modules/actions/workflows.go +++ b/modules/actions/workflows.go @@ -6,6 +6,7 @@ package actions import ( "bytes" "io" + "slices" "strings" "code.gitea.io/gitea/modules/git" @@ -556,11 +557,8 @@ func matchPullRequestReviewEvent(prPayload *api.PullRequestPayload, evt *jobpars matched := false for _, val := range vals { - for _, action := range actions { - if glob.MustCompile(val, '/').Match(action) { - matched = true - break - } + if slices.ContainsFunc(actions, glob.MustCompile(val, '/').Match) { + matched = true } if matched { break @@ -605,11 +603,8 @@ func matchPullRequestReviewCommentEvent(prPayload *api.PullRequestPayload, evt * matched := false for _, val := range vals { - for _, action := range actions { - if glob.MustCompile(val, '/').Match(action) { - matched = true - break - } + if slices.ContainsFunc(actions, glob.MustCompile(val, '/').Match) { + matched = true } if matched { break diff --git a/modules/auth/password/password.go b/modules/auth/password/password.go index c66b62937fd07..a1e101dd621cb 100644 --- a/modules/auth/password/password.go +++ b/modules/auth/password/password.go @@ -101,7 +101,7 @@ func Generate(n int) (string, error) { buffer := make([]byte, n) maxInt := big.NewInt(int64(len(validChars))) for { - for j := 0; j < n; j++ { + for j := range n { rnd, err := rand.Int(rand.Reader, maxInt) if err != nil { return "", err diff --git a/modules/auth/password/password_test.go b/modules/auth/password/password_test.go index 6c35dc86bd8b5..0fea593c85952 100644 --- a/modules/auth/password/password_test.go +++ b/modules/auth/password/password_test.go @@ -50,7 +50,7 @@ func TestComplexity_Generate(t *testing.T) { test := func(t *testing.T, modes []string) { testComplextity(modes) - for i := 0; i < maxCount; i++ { + for range maxCount { pwd, err := Generate(pwdLen) assert.NoError(t, err) assert.Len(t, pwd, pwdLen) diff --git a/modules/auth/password/pwn/pwn.go b/modules/auth/password/pwn/pwn.go index f77ce9f40b20d..99a6ca6ceacfb 100644 --- a/modules/auth/password/pwn/pwn.go +++ b/modules/auth/password/pwn/pwn.go @@ -101,7 +101,7 @@ func (c *Client) CheckPassword(pw string, padding bool) (int, error) { } defer resp.Body.Close() - for _, pair := range strings.Split(string(body), "\n") { + for pair := range strings.SplitSeq(string(body), "\n") { parts := strings.Split(pair, ":") if len(parts) != 2 { continue diff --git a/modules/avatar/identicon/block.go b/modules/avatar/identicon/block.go index cb1803a231acb..fc8ce902128bb 100644 --- a/modules/avatar/identicon/block.go +++ b/modules/avatar/identicon/block.go @@ -24,8 +24,8 @@ func drawBlock(img *image.Paletted, x, y, size, angle int, points []int) { rotate(points, m, m, angle) } - for i := 0; i < size; i++ { - for j := 0; j < size; j++ { + for i := range size { + for j := range size { if pointInPolygon(i, j, points) { img.SetColorIndex(x+i, y+j, 1) } diff --git a/modules/avatar/identicon/identicon.go b/modules/avatar/identicon/identicon.go index 63926d5f19086..23884318048a9 100644 --- a/modules/avatar/identicon/identicon.go +++ b/modules/avatar/identicon/identicon.go @@ -132,8 +132,8 @@ func drawBlocks(p *image.Paletted, size int, c, b1, b2 blockFunc, b1Angle, b2Ang b2(p, 0+padding, blockSize+padding, blockSize, b2Angle) // then we make it left-right mirror, so we didn't draw 3/6/9 before - for x := 0; x < size/2; x++ { - for y := 0; y < size; y++ { + for x := range size / 2 { + for y := range size { p.SetColorIndex(size-x, y, p.ColorIndexAt(x, y)) } } diff --git a/modules/cache/cache.go b/modules/cache/cache.go index f7828e3cae2df..4bd4f1d1ac7cd 100644 --- a/modules/cache/cache.go +++ b/modules/cache/cache.go @@ -22,7 +22,7 @@ func Init() error { if err != nil { return err } - for i := 0; i < 10; i++ { + for range 10 { if err = c.Ping(); err == nil { break } diff --git a/modules/charset/charset.go b/modules/charset/charset.go index 1855446a98480..597ce5120c611 100644 --- a/modules/charset/charset.go +++ b/modules/charset/charset.go @@ -164,7 +164,7 @@ func DetectEncoding(content []byte) (string, error) { } times := 1024 / len(content) detectContent = make([]byte, 0, times*len(content)) - for i := 0; i < times; i++ { + for range times { detectContent = append(detectContent, content...) } } else { diff --git a/modules/charset/charset_test.go b/modules/charset/charset_test.go index 19b1303365758..0e2c3e23eb10c 100644 --- a/modules/charset/charset_test.go +++ b/modules/charset/charset_test.go @@ -242,7 +242,7 @@ func stringMustEndWith(t *testing.T, expected, value string) { func TestToUTF8WithFallbackReader(t *testing.T) { resetDefaultCharsetsOrder() - for testLen := 0; testLen < 2048; testLen++ { + for testLen := range 2048 { pattern := " test { () }\n" input := "" for len(input) < testLen { diff --git a/modules/eventsource/messenger.go b/modules/eventsource/messenger.go index 6df26716be661..91004d7270ea7 100644 --- a/modules/eventsource/messenger.go +++ b/modules/eventsource/messenger.go @@ -3,6 +3,8 @@ package eventsource +import "slices" + import "sync" // Messenger is a per uid message store @@ -36,7 +38,7 @@ func (m *Messenger) Unregister(channel <-chan *Event) bool { defer m.mutex.Unlock() for i, toRemove := range m.channels { if channel == toRemove { - m.channels = append(m.channels[:i], m.channels[i+1:]...) + m.channels = slices.Delete(m.channels, i, i+1) close(toRemove) break } diff --git a/modules/git/commit_info_nogogit.go b/modules/git/commit_info_nogogit.go index ef2df0b133ade..a14c2cadff51b 100644 --- a/modules/git/commit_info_nogogit.go +++ b/modules/git/commit_info_nogogit.go @@ -9,6 +9,7 @@ import ( "context" "fmt" "io" + "maps" "path" "sort" @@ -40,9 +41,7 @@ func (tes Entries) GetCommitsInfo(ctx context.Context, commit *Commit, treePath return nil, nil, err } - for pth, found := range commits { - revs[pth] = found - } + maps.Copy(revs, commits) } } else { sort.Strings(entryPaths) diff --git a/modules/git/diff_test.go b/modules/git/diff_test.go index 0f865c52a8c84..f1a4624b697e1 100644 --- a/modules/git/diff_test.go +++ b/modules/git/diff_test.go @@ -154,7 +154,7 @@ func TestCutDiffAroundLine(t *testing.T) { } func BenchmarkCutDiffAroundLine(b *testing.B) { - for n := 0; n < b.N; n++ { + for b.Loop() { CutDiffAroundLine(strings.NewReader(exampleDiff), 3, true, 3) } } diff --git a/modules/git/foreachref/format.go b/modules/git/foreachref/format.go index 97e8ee47247b9..d9573a55d628c 100644 --- a/modules/git/foreachref/format.go +++ b/modules/git/foreachref/format.go @@ -76,7 +76,7 @@ func (f Format) Parser(r io.Reader) *Parser { // would turn into "%0a%00". func (f Format) hexEscaped(delim []byte) string { escaped := "" - for i := 0; i < len(delim); i++ { + for i := range delim { escaped += "%" + hex.EncodeToString([]byte{delim[i]}) } return escaped diff --git a/modules/git/hook.go b/modules/git/hook.go index 46f93ce13ec09..d61c972c9d75c 100644 --- a/modules/git/hook.go +++ b/modules/git/hook.go @@ -9,6 +9,7 @@ import ( "os" "path" "path/filepath" + "slices" "strings" "code.gitea.io/gitea/modules/log" @@ -27,12 +28,7 @@ var ErrNotValidHook = errors.New("not a valid Git hook") // IsValidHookName returns true if given name is a valid Git hook. func IsValidHookName(name string) bool { - for _, hn := range hookNames { - if hn == name { - return true - } - } - return false + return slices.Contains(hookNames, name) } // Hook represents a Git hook. diff --git a/modules/git/last_commit_cache.go b/modules/git/last_commit_cache.go index cf9c10d7b468e..cff2556083d74 100644 --- a/modules/git/last_commit_cache.go +++ b/modules/git/last_commit_cache.go @@ -13,7 +13,7 @@ import ( ) func getCacheKey(repoPath, commitID, entryPath string) string { - hashBytes := sha256.Sum256([]byte(fmt.Sprintf("%s:%s:%s", repoPath, commitID, entryPath))) + hashBytes := sha256.Sum256(fmt.Appendf(nil, "%s:%s:%s", repoPath, commitID, entryPath)) return fmt.Sprintf("last_commit:%x", hashBytes) } diff --git a/modules/git/log_name_status.go b/modules/git/log_name_status.go index 1fd58abfcdc0c..35b4a879bb487 100644 --- a/modules/git/log_name_status.go +++ b/modules/git/log_name_status.go @@ -10,6 +10,7 @@ import ( "errors" "io" "path" + "slices" "sort" "strings" @@ -319,7 +320,7 @@ func WalkGitLog(ctx context.Context, repo *Repository, head *Commit, treepath st // remove duplicates for i := len(paths) - 1; i > 0; i-- { if paths[i] == paths[i-1] { - paths = append(paths[:i-1], paths[i:]...) + paths = slices.Delete(paths, i-1, i) } } } @@ -343,10 +344,7 @@ func WalkGitLog(ctx context.Context, repo *Repository, head *Commit, treepath st results := make([]string, len(paths)) remaining := len(paths) - nextRestart := (len(paths) * 3) / 4 - if nextRestart > 70 { - nextRestart = 70 - } + nextRestart := min((len(paths)*3)/4, 70) lastEmptyParent := head.ID.String() commitSinceLastEmptyParent := uint64(0) commitSinceNextRestart := uint64(0) diff --git a/modules/git/repo.go b/modules/git/repo.go index 0993a4ac37d08..d074cd5ee8f55 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -42,9 +42,9 @@ func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, erro return commits, nil } - parts := bytes.Split(logs, []byte{'\n'}) + parts := bytes.SplitSeq(logs, []byte{'\n'}) - for _, commitID := range parts { + for commitID := range parts { commit, err := repo.GetCommit(string(commitID)) if err != nil { return nil, err diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go index 90eb783fe8761..8f41bb81e897a 100644 --- a/modules/git/repo_attribute.go +++ b/modules/git/repo_attribute.go @@ -77,7 +77,7 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[ name2attribute2info := make(map[string]map[string]string) - for i := 0; i < (len(fields) / 3); i++ { + for i := range len(fields) / 3 { filename := string(fields[3*i]) attribute := string(fields[3*i+1]) info := string(fields[3*i+2]) diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index 02d8e163e4f25..ab4dc139dfb9c 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -532,11 +532,11 @@ func (repo *Repository) GetCommitBranchStart(env []string, branch, endCommitID s return "", runErr } - parts := bytes.Split(bytes.TrimSpace(stdout), []byte{'\n'}) + parts := bytes.SplitSeq(bytes.TrimSpace(stdout), []byte{'\n'}) // check the commits one by one until we find a commit contained by another branch // and we think this commit is the divergence point - for _, commitID := range parts { + for commitID := range parts { branches, err := repo.getBranches(env, string(commitID), 2) if err != nil { return "", err diff --git a/modules/git/repo_index.go b/modules/git/repo_index.go index f45b6e61919f6..163510ba9bca7 100644 --- a/modules/git/repo_index.go +++ b/modules/git/repo_index.go @@ -95,7 +95,7 @@ func (repo *Repository) LsFiles(filenames ...string) ([]string, error) { return nil, err } filelist := make([]string, 0, len(filenames)) - for _, line := range bytes.Split(res, []byte{'\000'}) { + for line := range bytes.SplitSeq(res, []byte{'\000'}) { filelist = append(filelist, string(line)) } diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 2026a4c9f5c1a..981c7b57b5cce 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -45,8 +45,8 @@ func (repo *Repository) GetTagNameBySHA(sha string) (string, error) { return "", err } - tagRefs := strings.Split(stdout, "\n") - for _, tagRef := range tagRefs { + tagRefs := strings.SplitSeq(stdout, "\n") + for tagRef := range tagRefs { if len(strings.TrimSpace(tagRef)) > 0 { fields := strings.Fields(tagRef) if strings.HasPrefix(fields[0], sha) && strings.HasPrefix(fields[1], TagPrefix) { @@ -68,7 +68,7 @@ func (repo *Repository) GetTagID(name string) (string, error) { return "", err } // Make sure exact match is used: "v1" != "release/v1" - for _, line := range strings.Split(stdout, "\n") { + for line := range strings.SplitSeq(stdout, "\n") { fields := strings.Fields(line) if len(fields) == 2 && fields[1] == "refs/tags/"+name { return fields[0], nil diff --git a/modules/git/tree.go b/modules/git/tree.go index 5a644f6c87aa1..e05bdede450fe 100644 --- a/modules/git/tree.go +++ b/modules/git/tree.go @@ -56,7 +56,7 @@ func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error return nil, err } filelist := make([]string, 0, len(filenames)) - for _, line := range bytes.Split(res, []byte{'\000'}) { + for line := range bytes.SplitSeq(res, []byte{'\000'}) { filelist = append(filelist, string(line)) } diff --git a/modules/git/tree_entry.go b/modules/git/tree_entry.go index 95131214872e6..77fb588ecd909 100644 --- a/modules/git/tree_entry.go +++ b/modules/git/tree_entry.go @@ -75,7 +75,7 @@ func (te *TreeEntry) FollowLinks() (*TreeEntry, error) { return nil, ErrBadLink{te.Name(), "not a symlink"} } entry := te - for i := 0; i < 999; i++ { + for range 999 { if entry.IsLink() { next, err := entry.FollowLink() if err != nil { @@ -156,7 +156,7 @@ func (ctes customSortableEntries) Swap(i, j int) { func (ctes customSortableEntries) Less(i, j int) bool { t1, t2 := ctes.Entries[i], ctes.Entries[j] var k int - for k = 0; k < len(sorter)-1; k++ { + for k = range len(sorter) - 1 { s := sorter[k] switch { case s(t1, t2, ctes.Comparer): diff --git a/modules/git/tree_test.go b/modules/git/tree_test.go index 5fee64b038755..5ee3a5197db23 100644 --- a/modules/git/tree_test.go +++ b/modules/git/tree_test.go @@ -19,7 +19,7 @@ func TestSubTree_Issue29101(t *testing.T) { assert.NoError(t, err) // old code could produce a different error if called multiple times - for i := 0; i < 10; i++ { + for range 10 { _, err = commit.SubTree("file1.txt") assert.Error(t, err) assert.True(t, IsErrNotExist(err)) diff --git a/modules/git/url/url.go b/modules/git/url/url.go index 1c5e8377a6c77..c59ef1cbea10e 100644 --- a/modules/git/url/url.go +++ b/modules/git/url/url.go @@ -62,7 +62,7 @@ func ParseGitURL(remote string) (*GitURL, error) { squareBrackets := false lastIndex := -1 FOR: - for i := 0; i < len(remote); i++ { + for i := range len(remote) { switch remote[i] { case '@': url.User = stdurl.User(remote[:i]) diff --git a/modules/globallock/globallock_test.go b/modules/globallock/globallock_test.go index 0143fc6833293..8d55d9f699803 100644 --- a/modules/globallock/globallock_test.go +++ b/modules/globallock/globallock_test.go @@ -70,7 +70,7 @@ func testLockAndDo(t *testing.T) { count := 0 wg := sync.WaitGroup{} wg.Add(concurrency) - for i := 0; i < concurrency; i++ { + for range concurrency { go func() { defer wg.Done() err := LockAndDo(ctx, "test", func(ctx context.Context) error { diff --git a/modules/graceful/net_unix.go b/modules/graceful/net_unix.go index 796e00507cce2..590a449e20941 100644 --- a/modules/graceful/net_unix.go +++ b/modules/graceful/net_unix.go @@ -11,6 +11,7 @@ import ( "fmt" "net" "os" + "slices" "strconv" "strings" "sync" @@ -179,9 +180,9 @@ func GetListenerTCP(network string, address *net.TCPAddr) (*net.TCPListener, err // look for a provided listener for i, l := range providedListeners { if isSameAddr(l.Addr(), address) { - providedListeners = append(providedListeners[:i], providedListeners[i+1:]...) + providedListeners = slices.Delete(providedListeners, i, i+1) needsUnlink := providedListenersToUnlink[i] - providedListenersToUnlink = append(providedListenersToUnlink[:i], providedListenersToUnlink[i+1:]...) + providedListenersToUnlink = slices.Delete(providedListenersToUnlink, i, i+1) activeListeners = append(activeListeners, l) activeListenersToUnlink = append(activeListenersToUnlink, needsUnlink) @@ -213,9 +214,9 @@ func GetListenerUnix(network string, address *net.UnixAddr) (*net.UnixListener, // look for a provided listener for i, l := range providedListeners { if isSameAddr(l.Addr(), address) { - providedListeners = append(providedListeners[:i], providedListeners[i+1:]...) + providedListeners = slices.Delete(providedListeners, i, i+1) needsUnlink := providedListenersToUnlink[i] - providedListenersToUnlink = append(providedListenersToUnlink[:i], providedListenersToUnlink[i+1:]...) + providedListenersToUnlink = slices.Delete(providedListenersToUnlink, i, i+1) activeListenersToUnlink = append(activeListenersToUnlink, needsUnlink) activeListeners = append(activeListeners, l) diff --git a/modules/hostmatcher/hostmatcher.go b/modules/hostmatcher/hostmatcher.go index 1069310316ad5..15c6371422281 100644 --- a/modules/hostmatcher/hostmatcher.go +++ b/modules/hostmatcher/hostmatcher.go @@ -6,6 +6,7 @@ package hostmatcher import ( "net" "path/filepath" + "slices" "strings" ) @@ -38,7 +39,7 @@ func isBuiltin(s string) bool { // ParseHostMatchList parses the host list HostMatchList func ParseHostMatchList(settingKeyHint, hostList string) *HostMatchList { hl := &HostMatchList{SettingKeyHint: settingKeyHint, SettingValue: hostList} - for _, s := range strings.Split(hostList, ",") { + for s := range strings.SplitSeq(hostList, ",") { s = strings.ToLower(strings.TrimSpace(s)) if s == "" { continue @@ -61,7 +62,7 @@ func ParseSimpleMatchList(settingKeyHint, matchList string) *HostMatchList { SettingKeyHint: settingKeyHint, SettingValue: matchList, } - for _, s := range strings.Split(matchList, ",") { + for s := range strings.SplitSeq(matchList, ",") { s = strings.ToLower(strings.TrimSpace(s)) if s == "" { continue @@ -98,10 +99,8 @@ func (hl *HostMatchList) checkPattern(host string) bool { } func (hl *HostMatchList) checkIP(ip net.IP) bool { - for _, pattern := range hl.patterns { - if pattern == "*" { - return true - } + if slices.Contains(hl.patterns, "*") { + return true } for _, builtin := range hl.builtins { switch builtin { diff --git a/modules/httpcache/httpcache.go b/modules/httpcache/httpcache.go index 2c9af9440552b..0a6c4719a33e9 100644 --- a/modules/httpcache/httpcache.go +++ b/modules/httpcache/httpcache.go @@ -58,7 +58,7 @@ func HandleGenericETagCache(req *http.Request, w http.ResponseWriter, etag strin func checkIfNoneMatchIsValid(req *http.Request, etag string) bool { ifNoneMatch := req.Header.Get("If-None-Match") if len(ifNoneMatch) > 0 { - for _, item := range strings.Split(ifNoneMatch, ",") { + for item := range strings.SplitSeq(ifNoneMatch, ",") { item = strings.TrimPrefix(strings.TrimSpace(item), "W/") // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag#directives if item == etag { return true diff --git a/modules/indexer/code/bleve/token/path/path.go b/modules/indexer/code/bleve/token/path/path.go index 107e0da1090b3..d7c9678c22b3b 100644 --- a/modules/indexer/code/bleve/token/path/path.go +++ b/modules/indexer/code/bleve/token/path/path.go @@ -51,7 +51,7 @@ func generatePathTokens(input analysis.TokenStream, reversed bool) analysis.Toke slices.Reverse(input) } - for i := 0; i < len(input); i++ { + for i := range input { var sb strings.Builder sb.WriteString(string(input[0].Term)) diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index df9783288b032..6f1538349fead 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -129,8 +129,8 @@ func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revisio changes.Updates = append(changes.Updates, updates...) return nil } - lines := strings.Split(stdout, "\n") - for _, line := range lines { + lines := strings.SplitSeq(stdout, "\n") + for line := range lines { line = strings.TrimSpace(line) if len(line) == 0 { continue diff --git a/modules/indexer/code/search.go b/modules/indexer/code/search.go index 74c957dde65e4..a3ff87b9a1adc 100644 --- a/modules/indexer/code/search.go +++ b/modules/indexer/code/search.go @@ -77,7 +77,7 @@ func HighlightSearchResultCode(filename, language string, lineNums []int, code s // The lineNums outputted by highlight.Code might not match the original lineNums, because "highlight" removes the last `\n` lines := make([]*ResultLine, min(len(highlightedLines), len(lineNums))) - for i := 0; i < len(lines); i++ { + for i := range lines { lines[i] = &ResultLine{ Num: lineNums[i], FormattedContent: template.HTML(highlightedLines[i]), diff --git a/modules/indexer/internal/elasticsearch/util.go b/modules/indexer/internal/elasticsearch/util.go index 9e034bd553095..cb72164b83fc4 100644 --- a/modules/indexer/internal/elasticsearch/util.go +++ b/modules/indexer/internal/elasticsearch/util.go @@ -58,7 +58,7 @@ func (i *Indexer) initClient() (*elastic.Client, error) { } func (i *Indexer) checkOldIndexes(ctx context.Context) { - for v := 0; v < i.version; v++ { + for v := range i.version { indexName := versionedIndexName(i.indexName, v) exists, err := i.Client.IndexExists(indexName).Do(ctx) if err == nil && exists { diff --git a/modules/indexer/internal/meilisearch/util.go b/modules/indexer/internal/meilisearch/util.go index e6d8fefadeb8c..0b3ccd9321754 100644 --- a/modules/indexer/internal/meilisearch/util.go +++ b/modules/indexer/internal/meilisearch/util.go @@ -28,7 +28,7 @@ func versionedIndexName(indexName string, version int) string { } func (i *Indexer) checkOldIndexes() { - for v := 0; v < i.version; v++ { + for v := range i.version { indexName := versionedIndexName(i.indexName, v) _, err := i.Client.GetIndex(indexName) if err == nil { diff --git a/modules/indexer/issues/internal/tests/tests.go b/modules/indexer/issues/internal/tests/tests.go index 0483853dfd19e..6f39bd32416c0 100644 --- a/modules/indexer/issues/internal/tests/tests.go +++ b/modules/indexer/issues/internal/tests/tests.go @@ -738,7 +738,7 @@ func countIndexerData(data map[int64]*internal.IndexerData, f func(v *internal.I // Some engines like Elasticsearch index data asynchronously, so we need to wait for a while. func waitData(indexer internal.Indexer, total int64) error { var actual int64 - for i := 0; i < 100; i++ { + for range 100 { result, err := indexer.Search(context.Background(), &internal.SearchOptions{ Paginator: &db.ListOptions{ PageSize: 0, diff --git a/modules/issue/template/template.go b/modules/issue/template/template.go index a2b9d6b33e361..c93fed9fd08fc 100644 --- a/modules/issue/template/template.go +++ b/modules/issue/template/template.go @@ -7,6 +7,7 @@ import ( "fmt" "net/url" "regexp" + "slices" "strconv" "strings" @@ -446,12 +447,7 @@ func (o *valuedOption) IsChecked() bool { case api.IssueFormFieldTypeDropdown: checks := strings.Split(o.field.Get(fmt.Sprintf("form-field-%s", o.field.ID)), ",") idx := strconv.Itoa(o.index) - for _, v := range checks { - if v == idx { - return true - } - } - return false + return slices.Contains(checks, idx) case api.IssueFormFieldTypeCheckboxes: return o.field.Get(fmt.Sprintf("form-field-%s-%d", o.field.ID, o.index)) == "on" } diff --git a/modules/label/parser.go b/modules/label/parser.go index 511bac823ff8d..2a10152062649 100644 --- a/modules/label/parser.go +++ b/modules/label/parser.go @@ -72,7 +72,7 @@ func parseYamlFormat(fileName string, data []byte) ([]*Label, error) { func parseLegacyFormat(fileName string, data []byte) ([]*Label, error) { lines := strings.Split(string(data), "\n") list := make([]*Label, 0, len(lines)) - for i := 0; i < len(lines); i++ { + for i := range lines { line := strings.TrimSpace(lines[i]) if len(line) == 0 { continue @@ -108,7 +108,7 @@ func LoadTemplateDescription(fileName string) (string, error) { return "", err } - for i := 0; i < len(list); i++ { + for i := range list { if i > 0 { buf.WriteString(", ") } diff --git a/modules/log/event_format.go b/modules/log/event_format.go index 8fda0a498071e..cae29f24689e5 100644 --- a/modules/log/event_format.go +++ b/modules/log/event_format.go @@ -200,7 +200,7 @@ func EventFormatTextMessage(mode *WriterMode, event *Event, msgFormat string, ms } } if hasColorValue { - msg = []byte(fmt.Sprintf(msgFormat, msgArgs...)) + msg = fmt.Appendf(nil, msgFormat, msgArgs...) } } // try to re-use the pre-formatted simple text message @@ -231,8 +231,8 @@ func EventFormatTextMessage(mode *WriterMode, event *Event, msgFormat string, ms buf = append(buf, msg...) if event.Stacktrace != "" && mode.StacktraceLevel <= event.Level { - lines := bytes.Split([]byte(event.Stacktrace), []byte("\n")) - for _, line := range lines { + lines := bytes.SplitSeq([]byte(event.Stacktrace), []byte("\n")) + for line := range lines { buf = append(buf, "\n\t"...) buf = append(buf, line...) } diff --git a/modules/log/event_writer_base.go b/modules/log/event_writer_base.go index c327c48ca20ba..3e9fb638329a8 100644 --- a/modules/log/event_writer_base.go +++ b/modules/log/event_writer_base.go @@ -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 = b.OutputWriteCloser.Write(fmt.Append(nil, msg)) } if err != nil { FallbackErrorf("unable to write log message of %q (%v): %v", b.Name, err, event.Msg) diff --git a/modules/log/flags.go b/modules/log/flags.go index 8064c91745094..f409261150e55 100644 --- a/modules/log/flags.go +++ b/modules/log/flags.go @@ -123,7 +123,7 @@ func FlagsFromString(from string, def ...uint32) Flags { return Flags{defined: true, flags: def[0]} } flags := uint32(0) - for _, flag := range strings.Split(strings.ToLower(from), ",") { + for flag := range strings.SplitSeq(strings.ToLower(from), ",") { flags |= flagFromString[strings.TrimSpace(flag)] } return Flags{defined: true, flags: flags} diff --git a/modules/log/level_test.go b/modules/log/level_test.go index cd18a807d80b7..0e59af6cb70fe 100644 --- a/modules/log/level_test.go +++ b/modules/log/level_test.go @@ -32,11 +32,11 @@ func TestLevelMarshalUnmarshalJSON(t *testing.T) { assert.NoError(t, err) assert.Equal(t, INFO, testLevel.Level) - err = json.Unmarshal([]byte(fmt.Sprintf(`{"level":%d}`, 2)), &testLevel) + err = json.Unmarshal(fmt.Appendf(nil, `{"level":%d}`, 2), &testLevel) assert.NoError(t, err) assert.Equal(t, INFO, testLevel.Level) - err = json.Unmarshal([]byte(fmt.Sprintf(`{"level":%d}`, 10012)), &testLevel) + err = json.Unmarshal(fmt.Appendf(nil, `{"level":%d}`, 10012), &testLevel) assert.NoError(t, err) assert.Equal(t, INFO, testLevel.Level) @@ -51,5 +51,5 @@ func TestLevelMarshalUnmarshalJSON(t *testing.T) { } func makeTestLevelBytes(level string) []byte { - return []byte(fmt.Sprintf(`{"level":"%s"}`, level)) + return fmt.Appendf(nil, `{"level":"%s"}`, level) } diff --git a/modules/markup/html.go b/modules/markup/html.go index 3aaf669c63267..8529ef216d7ff 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "regexp" + "slices" "strings" "sync" @@ -116,13 +117,7 @@ func CustomLinkURLSchemes(schemes []string) { if !validScheme.MatchString(s) { continue } - without := false - for _, sna := range xurls.SchemesNoAuthority { - if s == sna { - without = true - break - } - } + without := slices.Contains(xurls.SchemesNoAuthority, s) if without { s += ":" } else { diff --git a/modules/markup/html_commit.go b/modules/markup/html_commit.go index aa1b7d034a594..2b0ef9f212e36 100644 --- a/modules/markup/html_commit.go +++ b/modules/markup/html_commit.go @@ -63,7 +63,7 @@ func anyHashPatternExtract(s string) (ret anyHashPatternResult, ok bool) { // if url ends in '.', it's very likely that it is not part of the actual url but used to finish a sentence. ret.PosEnd-- ret.FullURL = ret.FullURL[:len(ret.FullURL)-1] - for i := 0; i < len(m); i++ { + for i := range m { m[i] = min(m[i], ret.PosEnd) } } diff --git a/modules/markup/html_link.go b/modules/markup/html_link.go index 0e7a988d3680e..079d81e745e69 100644 --- a/modules/markup/html_link.go +++ b/modules/markup/html_link.go @@ -31,8 +31,8 @@ func shortLinkProcessor(ctx *RenderContext, node *html.Node) { // It makes page handling terrible, but we prefer GitHub syntax // And fall back to MediaWiki only when it is obvious from the look // Of text and link contents - sl := strings.Split(content, "|") - for _, v := range sl { + sl := strings.SplitSeq(content, "|") + for v := range sl { if equalPos := strings.IndexByte(v, '='); equalPos == -1 { // There is no equal in this argument; this is a mandatory arg if props["name"] == "" { diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go index b5fffccdb989a..b652cf7751ca0 100644 --- a/modules/markup/markdown/markdown.go +++ b/modules/markup/markdown/markdown.go @@ -191,10 +191,7 @@ func render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error } buf, _ = ExtractMetadataBytes(buf, rc) - metaLength := bufWithMetadataLength - len(buf) - if metaLength < 0 { - metaLength = 0 - } + metaLength := max(bufWithMetadataLength-len(buf), 0) rc.metaLength = metaLength pc.Set(renderConfigKey, rc) diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go index 7a09be8665827..366d733bb7c07 100644 --- a/modules/markup/markdown/markdown_test.go +++ b/modules/markup/markdown/markdown_test.go @@ -252,7 +252,7 @@ This PR has been generated by [Renovate Bot](https://github.com/renovatebot/reno return username == "r-lyeh" }, }) - for i := 0; i < len(sameCases); i++ { + for i := range sameCases { line, err := markdown.RenderString(markup.NewTestRenderContext(localMetas), sameCases[i]) assert.NoError(t, err) assert.Equal(t, testAnswers[i], string(line)) diff --git a/modules/markup/markdown/math/block_renderer.go b/modules/markup/markdown/math/block_renderer.go index 412e4d0dee6c2..427ed842ec307 100644 --- a/modules/markup/markdown/math/block_renderer.go +++ b/modules/markup/markdown/math/block_renderer.go @@ -42,7 +42,7 @@ func (r *BlockRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { func (r *BlockRenderer) writeLines(w util.BufWriter, source []byte, n gast.Node) { l := n.Lines().Len() - for i := 0; i < l; i++ { + for i := range l { line := n.Lines().At(i) _, _ = w.Write(util.EscapeHTML(line.Value(source))) } diff --git a/modules/markup/markdown/meta_test.go b/modules/markup/markdown/meta_test.go index 278c33f1d2f07..abbc062ce2bda 100644 --- a/modules/markup/markdown/meta_test.go +++ b/modules/markup/markdown/meta_test.go @@ -60,7 +60,7 @@ func TestExtractMetadata(t *testing.T) { func TestExtractMetadataBytes(t *testing.T) { t.Run("ValidFrontAndBody", func(t *testing.T) { var meta IssueTemplate - body, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s\n%s", sepTest, frontTest, sepTest, bodyTest)), &meta) + body, err := ExtractMetadataBytes(fmt.Appendf(nil, "%s\n%s\n%s\n%s", sepTest, frontTest, sepTest, bodyTest), &meta) assert.NoError(t, err) assert.Equal(t, bodyTest, string(body)) assert.Equal(t, metaTest, meta) @@ -69,19 +69,19 @@ func TestExtractMetadataBytes(t *testing.T) { t.Run("NoFirstSeparator", func(t *testing.T) { var meta IssueTemplate - _, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", frontTest, sepTest, bodyTest)), &meta) + _, err := ExtractMetadataBytes(fmt.Appendf(nil, "%s\n%s\n%s", frontTest, sepTest, bodyTest), &meta) assert.Error(t, err) }) t.Run("NoLastSeparator", func(t *testing.T) { var meta IssueTemplate - _, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, bodyTest)), &meta) + _, err := ExtractMetadataBytes(fmt.Appendf(nil, "%s\n%s\n%s", sepTest, frontTest, bodyTest), &meta) assert.Error(t, err) }) t.Run("NoBody", func(t *testing.T) { var meta IssueTemplate - body, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, sepTest)), &meta) + body, err := ExtractMetadataBytes(fmt.Appendf(nil, "%s\n%s\n%s", sepTest, frontTest, sepTest), &meta) assert.NoError(t, err) assert.Equal(t, "", string(body)) assert.Equal(t, metaTest, meta) diff --git a/modules/markup/markdown/toc.go b/modules/markup/markdown/toc.go index ea1af83a3ed1a..86e6c5be2696c 100644 --- a/modules/markup/markdown/toc.go +++ b/modules/markup/markdown/toc.go @@ -50,7 +50,7 @@ func createTOCNode(toc []Header, lang string, detailsAttrs map[string]string) as } li := ast.NewListItem(currentLevel * 2) a := ast.NewLink() - a.Destination = []byte(fmt.Sprintf("#%s", url.QueryEscape(header.ID))) + a.Destination = fmt.Appendf(nil, "#%s", url.QueryEscape(header.ID)) a.AppendChild(a, ast.NewString([]byte(header.Text))) li.AppendChild(li, a) ul.AppendChild(ul, li) diff --git a/modules/markup/markdown/transform_heading.go b/modules/markup/markdown/transform_heading.go index 5f8a12794dac8..cac3cd6617da5 100644 --- a/modules/markup/markdown/transform_heading.go +++ b/modules/markup/markdown/transform_heading.go @@ -16,7 +16,7 @@ import ( func (g *ASTTransformer) transformHeading(_ *markup.RenderContext, v *ast.Heading, reader text.Reader, tocList *[]Header) { for _, attr := range v.Attributes() { if _, ok := attr.Value.([]byte); !ok { - v.SetAttribute(attr.Name, []byte(fmt.Sprintf("%v", attr.Value))) + v.SetAttribute(attr.Name, fmt.Appendf(nil, "%v", attr.Value)) } } txt := v.Text(reader.Source()) //nolint:staticcheck diff --git a/modules/packages/npm/creator.go b/modules/packages/npm/creator.go index 8ba4dbfba710c..11b5123c27880 100644 --- a/modules/packages/npm/creator.go +++ b/modules/packages/npm/creator.go @@ -58,7 +58,7 @@ type PackageMetadata struct { Time map[string]time.Time `json:"time,omitempty"` Homepage string `json:"homepage,omitempty"` Keywords []string `json:"keywords,omitempty"` - Repository Repository `json:"repository,omitempty"` + Repository Repository `json:"repository"` Author User `json:"author"` ReadmeFilename string `json:"readmeFilename,omitempty"` Users map[string]bool `json:"users,omitempty"` @@ -75,7 +75,7 @@ type PackageMetadataVersion struct { Author User `json:"author"` Homepage string `json:"homepage,omitempty"` License string `json:"license,omitempty"` - Repository Repository `json:"repository,omitempty"` + Repository Repository `json:"repository"` Keywords []string `json:"keywords,omitempty"` Dependencies map[string]string `json:"dependencies,omitempty"` BundleDependencies []string `json:"bundleDependencies,omitempty"` diff --git a/modules/packages/npm/metadata.go b/modules/packages/npm/metadata.go index d1d026338780c..362d0470d55e0 100644 --- a/modules/packages/npm/metadata.go +++ b/modules/packages/npm/metadata.go @@ -23,5 +23,5 @@ type Metadata struct { OptionalDependencies map[string]string `json:"optional_dependencies,omitempty"` Bin map[string]string `json:"bin,omitempty"` Readme string `json:"readme,omitempty"` - Repository Repository `json:"repository,omitempty"` + Repository Repository `json:"repository"` } diff --git a/modules/packages/nuget/symbol_extractor.go b/modules/packages/nuget/symbol_extractor.go index 81bf0371a0b1a..ba10e736a95aa 100644 --- a/modules/packages/nuget/symbol_extractor.go +++ b/modules/packages/nuget/symbol_extractor.go @@ -150,7 +150,7 @@ func ParseDebugHeaderID(r io.ReadSeeker) (string, error) { } } - for i := 0; i < int(streamCount); i++ { + for range int(streamCount) { var offset uint32 if err := binary.Read(r, binary.LittleEndian, &offset); err != nil { return "", err diff --git a/modules/packages/rubygems/marshal.go b/modules/packages/rubygems/marshal.go index 4e6a5fc5f8baf..d0993e3f34620 100644 --- a/modules/packages/rubygems/marshal.go +++ b/modules/packages/rubygems/marshal.go @@ -175,7 +175,7 @@ func (e *MarshalEncoder) marshalIntInternal(i int64) error { length = -length } - for c := 0; c < length; c++ { + for c := range length { if err := e.w.WriteByte(byte(i >> uint(8*c) & 0xff)); err != nil { return err } @@ -250,7 +250,7 @@ func (e *MarshalEncoder) marshalArray(arr reflect.Value) error { return err } - for i := 0; i < length; i++ { + for i := range length { if err := e.marshal(arr.Index(i).Interface()); err != nil { return err } diff --git a/modules/packages/swift/metadata.go b/modules/packages/swift/metadata.go index 24c4262ab7248..85beb57607a26 100644 --- a/modules/packages/swift/metadata.go +++ b/modules/packages/swift/metadata.go @@ -47,7 +47,7 @@ type Metadata struct { Keywords []string `json:"keywords,omitempty"` RepositoryURL string `json:"repository_url,omitempty"` License string `json:"license,omitempty"` - Author Person `json:"author,omitempty"` + Author Person `json:"author"` Manifests map[string]*Manifest `json:"manifests,omitempty"` } diff --git a/modules/paginator/paginator.go b/modules/paginator/paginator.go index 8258d194c263f..9f9b7c87ec338 100644 --- a/modules/paginator/paginator.go +++ b/modules/paginator/paginator.go @@ -189,7 +189,7 @@ func (p *Paginator) Pages() []*Page { } // Check previous pages. - for i := 0; i < previousNum; i++ { + for i := range previousNum { pages[offsetIdx+i] = &Page{i + offsetVal, false} } diff --git a/modules/public/public.go b/modules/public/public.go index abc6b46158027..edaf6d58f9602 100644 --- a/modules/public/public.go +++ b/modules/public/public.go @@ -44,7 +44,7 @@ func FileHandlerFunc() http.HandlerFunc { func parseAcceptEncoding(val string) container.Set[string] { parts := strings.Split(val, ";") types := make(container.Set[string]) - for _, v := range strings.Split(parts[0], ",") { + for v := range strings.SplitSeq(parts[0], ",") { types.Add(strings.TrimSpace(v)) } return types diff --git a/modules/queue/base_levelqueue_common.go b/modules/queue/base_levelqueue_common.go index 78d3b85a8a258..d37093b84dca1 100644 --- a/modules/queue/base_levelqueue_common.go +++ b/modules/queue/base_levelqueue_common.go @@ -83,7 +83,7 @@ func prepareLevelDB(cfg *BaseConfig) (conn string, db *leveldb.DB, err error) { } conn = cfg.ConnStr } - for i := 0; i < 10; i++ { + for range 10 { if db, err = nosql.GetManager().GetLevelDB(conn); err == nil { break } diff --git a/modules/queue/base_redis.go b/modules/queue/base_redis.go index a1e234943d2f8..bea0fd7a985d4 100644 --- a/modules/queue/base_redis.go +++ b/modules/queue/base_redis.go @@ -29,7 +29,7 @@ func newBaseRedisGeneric(cfg *BaseConfig, unique bool) (baseQueue, error) { client := nosql.GetManager().GetRedisClient(cfg.ConnStr) var err error - for i := 0; i < 10; i++ { + for range 10 { err = client.Ping(graceful.GetManager().ShutdownContext()).Err() if err == nil { break diff --git a/modules/queue/base_test.go b/modules/queue/base_test.go index 73abf49091037..5c993f3818112 100644 --- a/modules/queue/base_test.go +++ b/modules/queue/base_test.go @@ -86,8 +86,8 @@ func testQueueBasic(t *testing.T, newFn func(cfg *BaseConfig) (baseQueue, error) assert.Nil(t, it) // test blocking push if queue is full - for i := 0; i < cfg.Length; i++ { - err = q.PushItem(ctx, []byte(fmt.Sprintf("item-%d", i))) + for i := range cfg.Length { + err = q.PushItem(ctx, fmt.Appendf(nil, "item-%d", i)) assert.NoError(t, err) } ctxTimed, cancel = context.WithTimeout(ctx, 10*time.Millisecond) diff --git a/modules/queue/manager.go b/modules/queue/manager.go index 079e2bee7a7b9..ae6c51872dd47 100644 --- a/modules/queue/manager.go +++ b/modules/queue/manager.go @@ -6,6 +6,7 @@ package queue import ( "context" "errors" + "maps" "sync" "time" @@ -70,9 +71,7 @@ func (m *Manager) ManagedQueues() map[int64]ManagedWorkerPoolQueue { defer m.mu.Unlock() queues := make(map[int64]ManagedWorkerPoolQueue, len(m.Queues)) - for k, v := range m.Queues { - queues[k] = v - } + maps.Copy(queues, m.Queues) return queues } diff --git a/modules/queue/workerqueue_test.go b/modules/queue/workerqueue_test.go index 0ca2be1d21add..6cf4ac390d980 100644 --- a/modules/queue/workerqueue_test.go +++ b/modules/queue/workerqueue_test.go @@ -53,7 +53,7 @@ func TestWorkerPoolQueueUnhandled(t *testing.T) { q, _ := newWorkerPoolQueueForTest("test-workpoolqueue", queueSetting, handler, false) stop := runWorkerPoolQueue(q) - for i := 0; i < queueSetting.Length; i++ { + for i := range queueSetting.Length { testRecorder.Record("push:%v", i) assert.NoError(t, q.Push(i)) } @@ -61,7 +61,7 @@ func TestWorkerPoolQueueUnhandled(t *testing.T) { stop() ok := true - for i := 0; i < queueSetting.Length; i++ { + for i := range queueSetting.Length { if i%2 == 0 { ok = ok && assert.EqualValues(t, 2, m[i], "test %s: item %d", t.Name(), i) } else { @@ -77,17 +77,17 @@ func TestWorkerPoolQueueUnhandled(t *testing.T) { runCount := 2 // we can run these tests even hundreds times to see its stability t.Run("1/1", func(t *testing.T) { - for i := 0; i < runCount; i++ { + for range runCount { test(t, setting.QueueSettings{BatchLength: 1, MaxWorkers: 1}) } }) t.Run("3/1", func(t *testing.T) { - for i := 0; i < runCount; i++ { + for range runCount { test(t, setting.QueueSettings{BatchLength: 3, MaxWorkers: 1}) } }) t.Run("4/5", func(t *testing.T) { - for i := 0; i < runCount; i++ { + for range runCount { test(t, setting.QueueSettings{BatchLength: 4, MaxWorkers: 5}) } }) @@ -96,17 +96,17 @@ func TestWorkerPoolQueueUnhandled(t *testing.T) { func TestWorkerPoolQueuePersistence(t *testing.T) { runCount := 2 // we can run these tests even hundreds times to see its stability t.Run("1/1", func(t *testing.T) { - for i := 0; i < runCount; i++ { + for range runCount { testWorkerPoolQueuePersistence(t, setting.QueueSettings{BatchLength: 1, MaxWorkers: 1, Length: 100}) } }) t.Run("3/1", func(t *testing.T) { - for i := 0; i < runCount; i++ { + for range runCount { testWorkerPoolQueuePersistence(t, setting.QueueSettings{BatchLength: 3, MaxWorkers: 1, Length: 100}) } }) t.Run("4/5", func(t *testing.T) { - for i := 0; i < runCount; i++ { + for range runCount { testWorkerPoolQueuePersistence(t, setting.QueueSettings{BatchLength: 4, MaxWorkers: 5, Length: 100}) } }) @@ -141,7 +141,7 @@ func testWorkerPoolQueuePersistence(t *testing.T, queueSetting setting.QueueSett q, _ := newWorkerPoolQueueForTest("pr_patch_checker_test", queueSetting, testHandler, true) stop := runWorkerPoolQueue(q) - for i := 0; i < testCount; i++ { + for i := range testCount { _ = q.Push("task-" + strconv.Itoa(i)) } close(startWhenAllReady) @@ -186,7 +186,7 @@ func TestWorkerPoolQueueActiveWorkers(t *testing.T) { q, _ := newWorkerPoolQueueForTest("test-workpoolqueue", setting.QueueSettings{Type: "channel", BatchLength: 1, MaxWorkers: 1, Length: 100}, handler, false) stop := runWorkerPoolQueue(q) - for i := 0; i < 5; i++ { + for i := range 5 { assert.NoError(t, q.Push(i)) } @@ -202,7 +202,7 @@ func TestWorkerPoolQueueActiveWorkers(t *testing.T) { q, _ = newWorkerPoolQueueForTest("test-workpoolqueue", setting.QueueSettings{Type: "channel", BatchLength: 1, MaxWorkers: 3, Length: 100}, handler, false) stop = runWorkerPoolQueue(q) - for i := 0; i < 15; i++ { + for i := range 15 { assert.NoError(t, q.Push(i)) } @@ -235,7 +235,7 @@ func TestWorkerPoolQueueShutdown(t *testing.T) { qs := setting.QueueSettings{Type: "level", Datadir: t.TempDir() + "/queue", BatchLength: 3, MaxWorkers: 4, Length: 20} q, _ := newWorkerPoolQueueForTest("test-workpoolqueue", qs, handler, false) stop := runWorkerPoolQueue(q) - for i := 0; i < qs.Length; i++ { + for i := range qs.Length { assert.NoError(t, q.Push(i)) } <-handlerCalled @@ -260,7 +260,7 @@ func TestWorkerPoolQueueWorkerIdleReset(t *testing.T) { handledCount.Add(int32(len(items))) // make each work have different duration, and check the active worker number periodically var activeNums []int - for i := 0; i < 5-items[0]%2; i++ { + for range 5 - items[0]%2 { time.Sleep(workerIdleDuration * 2) activeNums = append(activeNums, q.GetWorkerActiveNumber()) } @@ -274,7 +274,7 @@ func TestWorkerPoolQueueWorkerIdleReset(t *testing.T) { } q, _ = newWorkerPoolQueueForTest("test-workpoolqueue", setting.QueueSettings{Type: "channel", BatchLength: 1, MaxWorkers: 2, Length: 100}, handler, false) stop := runWorkerPoolQueue(q) - for i := 0; i < 100; i++ { + for i := range 100 { assert.NoError(t, q.Push(i)) } time.Sleep(500 * time.Millisecond) diff --git a/modules/repository/init.go b/modules/repository/init.go index 24602ae090108..7b8475772337a 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -152,7 +152,7 @@ func InitializeLabels(ctx context.Context, id int64, labelTemplate string, isOrg } labels := make([]*issues_model.Label, len(list)) - for i := 0; i < len(list); i++ { + for i := range list { labels[i] = &issues_model.Label{ Name: list[i].Name, Exclusive: list[i].Exclusive, diff --git a/modules/reqctx/datastore.go b/modules/reqctx/datastore.go index 94232450f33ca..445df06123016 100644 --- a/modules/reqctx/datastore.go +++ b/modules/reqctx/datastore.go @@ -6,6 +6,7 @@ package reqctx import ( "context" "io" + "maps" "sync" "code.gitea.io/gitea/modules/process" @@ -22,9 +23,7 @@ func (ds ContextData) GetData() ContextData { } func (ds ContextData) MergeFrom(other ContextData) ContextData { - for k, v := range other { - ds[k] = v - } + maps.Copy(ds, other) return ds } diff --git a/modules/setting/config_env.go b/modules/setting/config_env.go index 5d94a9641f782..58063dd67ee96 100644 --- a/modules/setting/config_env.go +++ b/modules/setting/config_env.go @@ -63,7 +63,7 @@ func decodeEnvSectionKey(encoded string) (ok bool, section, key string) { } toDecode := encoded[unescapeIdx[0]+3 : unescapeIdx[1]-1] decodedBytes := make([]byte, len(toDecode)/2) - for i := 0; i < len(toDecode)/2; i++ { + for i := range len(toDecode) / 2 { // Can ignore error here as we know these should be hexadecimal from the regexp byteInt, _ := strconv.ParseInt(toDecode[2*i:2*i+2], 16, 0) decodedBytes[i] = byte(byteInt) diff --git a/modules/setting/cron.go b/modules/setting/cron.go index 7c4cc44288597..e5b033283a03e 100644 --- a/modules/setting/cron.go +++ b/modules/setting/cron.go @@ -18,7 +18,7 @@ func getCronSettings(rootCfg ConfigProvider, name string, config any) (any, erro typ := reflect.TypeOf(config).Elem() val := reflect.ValueOf(config).Elem() - for i := 0; i < typ.NumField(); i++ { + for i := range typ.NumField() { field := val.Field(i) tpField := typ.Field(i) if tpField.Type.Kind() == reflect.Struct && tpField.Anonymous { diff --git a/modules/setting/indexer.go b/modules/setting/indexer.go index e34baae012b32..ace7eec70eb77 100644 --- a/modules/setting/indexer.go +++ b/modules/setting/indexer.go @@ -96,7 +96,7 @@ func loadIndexerFrom(rootCfg ConfigProvider) { // IndexerGlobFromString parses a comma separated list of patterns and returns a glob.Glob slice suited for repo indexing func IndexerGlobFromString(globstr string) []*GlobMatcher { extarr := make([]*GlobMatcher, 0, 10) - for _, expr := range strings.Split(strings.ToLower(globstr), ",") { + for expr := range strings.SplitSeq(strings.ToLower(globstr), ",") { expr = strings.TrimSpace(expr) if expr != "" { if g, err := GlobMatcherCompile(expr, '.', '/'); err != nil { diff --git a/modules/setting/log.go b/modules/setting/log.go index 50c57799945e5..454bce35076f7 100644 --- a/modules/setting/log.go +++ b/modules/setting/log.go @@ -228,8 +228,8 @@ func initLoggerByName(manager *log.LoggerManager, rootCfg ConfigProvider, logger } var eventWriters []log.EventWriter - modes := strings.Split(modeVal, ",") - for _, modeName := range modes { + modes := strings.SplitSeq(modeVal, ",") + for modeName := range modes { modeName = strings.TrimSpace(modeName) if modeName == "" { continue diff --git a/modules/setting/mirror.go b/modules/setting/mirror.go index 3aa530a1f4847..300711789db36 100644 --- a/modules/setting/mirror.go +++ b/modules/setting/mirror.go @@ -48,11 +48,7 @@ func loadMirrorFrom(rootCfg ConfigProvider) { Mirror.MinInterval = 1 * time.Minute } if Mirror.DefaultInterval < Mirror.MinInterval { - if time.Hour*8 < Mirror.MinInterval { - Mirror.DefaultInterval = Mirror.MinInterval - } else { - Mirror.DefaultInterval = time.Hour * 8 - } + Mirror.DefaultInterval = max(time.Hour*8, Mirror.MinInterval) log.Warn("Mirror.DefaultInterval is less than Mirror.MinInterval, set to %s", Mirror.DefaultInterval.String()) } } diff --git a/modules/setting/repository.go b/modules/setting/repository.go index c5619d0f04858..4417e71744d77 100644 --- a/modules/setting/repository.go +++ b/modules/setting/repository.go @@ -7,6 +7,7 @@ import ( "os/exec" "path" "path/filepath" + "slices" "strings" "code.gitea.io/gitea/modules/log" @@ -337,7 +338,7 @@ func loadRepositoryFrom(rootCfg ConfigProvider) { // remove it from the defaults for i, charset := range defaultDetectedCharsetsOrder { if charset == canonicalCharset { - defaultDetectedCharsetsOrder = append(defaultDetectedCharsetsOrder[:i], defaultDetectedCharsetsOrder[i+1:]...) + defaultDetectedCharsetsOrder = slices.Delete(defaultDetectedCharsetsOrder, i, i+1) break } } diff --git a/modules/setting/storage.go b/modules/setting/storage.go index d3d1fb9f30b20..97986d3153221 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "path/filepath" + "slices" "strings" ) @@ -30,12 +31,7 @@ var storageTypes = []StorageType{ // IsValidStorageType returns true if the given storage type is valid func IsValidStorageType(storageType StorageType) bool { - for _, t := range storageTypes { - if t == storageType { - return true - } - } - return false + return slices.Contains(storageTypes, storageType) } // MinioStorageConfig represents the configuration for a minio storage diff --git a/modules/structs/issue.go b/modules/structs/issue.go index 3682191be5751..c4d8be117d2f0 100644 --- a/modules/structs/issue.go +++ b/modules/structs/issue.go @@ -203,7 +203,7 @@ func (l *IssueTemplateStringSlice) UnmarshalYAML(value *yaml.Node) error { if err != nil { return err } - for _, v := range strings.Split(str, ",") { + for v := range strings.SplitSeq(str, ",") { if v = strings.TrimSpace(v); v == "" { continue } diff --git a/modules/structs/repo.go b/modules/structs/repo.go index fb784bd8b37f8..0e285f0745ebe 100644 --- a/modules/structs/repo.go +++ b/modules/structs/repo.go @@ -111,7 +111,7 @@ type Repository struct { // enum: sha1,sha256 ObjectFormatName string `json:"object_format_name"` // swagger:strfmt date-time - MirrorUpdated time.Time `json:"mirror_updated,omitempty"` + MirrorUpdated time.Time `json:"mirror_updated"` RepoTransfer *RepoTransfer `json:"repo_transfer"` Topics []string `json:"topics"` Licenses []string `json:"licenses"` diff --git a/modules/structs/repo_actions.go b/modules/structs/repo_actions.go index 203491ac02610..d981a000ade27 100644 --- a/modules/structs/repo_actions.go +++ b/modules/structs/repo_actions.go @@ -57,7 +57,7 @@ type ActionWorkflow struct { HTMLURL string `json:"html_url"` BadgeURL string `json:"badge_url"` // swagger:strfmt date-time - DeletedAt time.Time `json:"deleted_at,omitempty"` + DeletedAt time.Time `json:"deleted_at"` } // ActionWorkflowResponse returns a ActionWorkflow diff --git a/modules/structs/user.go b/modules/structs/user.go index 5ed677f239fb5..7338e45739734 100644 --- a/modules/structs/user.go +++ b/modules/structs/user.go @@ -35,9 +35,9 @@ type User struct { // Is the user an administrator IsAdmin bool `json:"is_admin"` // swagger:strfmt date-time - LastLogin time.Time `json:"last_login,omitempty"` + LastLogin time.Time `json:"last_login"` // swagger:strfmt date-time - Created time.Time `json:"created,omitempty"` + Created time.Time `json:"created"` // Is user restricted Restricted bool `json:"restricted"` // Is user active diff --git a/modules/structs/user_gpgkey.go b/modules/structs/user_gpgkey.go index ff9b0aea1d616..deae70de33729 100644 --- a/modules/structs/user_gpgkey.go +++ b/modules/structs/user_gpgkey.go @@ -21,9 +21,9 @@ type GPGKey struct { CanCertify bool `json:"can_certify"` Verified bool `json:"verified"` // swagger:strfmt date-time - Created time.Time `json:"created_at,omitempty"` + Created time.Time `json:"created_at"` // swagger:strfmt date-time - Expires time.Time `json:"expires_at,omitempty"` + Expires time.Time `json:"expires_at"` } // GPGKeyEmail an email attached to a GPGKey diff --git a/modules/structs/user_key.go b/modules/structs/user_key.go index 08eed59a89c88..b92552b200288 100644 --- a/modules/structs/user_key.go +++ b/modules/structs/user_key.go @@ -15,7 +15,7 @@ type PublicKey struct { Title string `json:"title,omitempty"` Fingerprint string `json:"fingerprint,omitempty"` // swagger:strfmt date-time - Created time.Time `json:"created_at,omitempty"` + Created time.Time `json:"created_at"` Owner *User `json:"user,omitempty"` ReadOnly bool `json:"read_only,omitempty"` KeyType string `json:"key_type,omitempty"` diff --git a/modules/templates/htmlrenderer.go b/modules/templates/htmlrenderer.go index 529284f7e8e19..f51936354e6a1 100644 --- a/modules/templates/htmlrenderer.go +++ b/modules/templates/htmlrenderer.go @@ -251,7 +251,7 @@ func extractErrorLine(code []byte, lineNum, posNum int, target string) string { b := bufio.NewReader(bytes.NewReader(code)) var line []byte var err error - for i := 0; i < lineNum; i++ { + for i := range lineNum { if line, err = b.ReadBytes('\n'); err != nil { if i == lineNum-1 && errors.Is(err, io.EOF) { err = nil diff --git a/modules/templates/scopedtmpl/scopedtmpl.go b/modules/templates/scopedtmpl/scopedtmpl.go index 2722ba97a28ac..0d84f8598b858 100644 --- a/modules/templates/scopedtmpl/scopedtmpl.go +++ b/modules/templates/scopedtmpl/scopedtmpl.go @@ -7,6 +7,7 @@ import ( "fmt" "html/template" "io" + "maps" "reflect" "sync" texttemplate "text/template" @@ -40,9 +41,7 @@ func (t *ScopedTemplate) Funcs(funcMap template.FuncMap) { panic("cannot add new functions to frozen template set") } t.all.Funcs(funcMap) - for k, v := range funcMap { - t.parseFuncs[k] = v - } + maps.Copy(t.parseFuncs, funcMap) } func (t *ScopedTemplate) New(name string) *template.Template { @@ -159,9 +158,7 @@ func newScopedTemplateSet(all *template.Template, name string) (*scopedTemplateS textTmplPtr.muFuncs.Lock() ts.execFuncs = map[string]reflect.Value{} - for k, v := range textTmplPtr.execFuncs { - ts.execFuncs[k] = v - } + maps.Copy(ts.execFuncs, textTmplPtr.execFuncs) textTmplPtr.muFuncs.Unlock() var collectTemplates func(nodes []parse.Node) @@ -220,9 +217,7 @@ func (ts *scopedTemplateSet) newExecutor(funcMap map[string]any) TemplateExecuto tmpl := texttemplate.New("") tmplPtr := ptr[textTemplate](tmpl) tmplPtr.execFuncs = map[string]reflect.Value{} - for k, v := range ts.execFuncs { - tmplPtr.execFuncs[k] = v - } + maps.Copy(tmplPtr.execFuncs, ts.execFuncs) if funcMap != nil { tmpl.Funcs(funcMap) } diff --git a/modules/templates/util_dict.go b/modules/templates/util_dict.go index 8d6376b522e56..14160b646807b 100644 --- a/modules/templates/util_dict.go +++ b/modules/templates/util_dict.go @@ -75,7 +75,7 @@ func dumpVarMarshalable(v any, dumped container.Set[uintptr]) (ret any, ok bool) return e.Interface(), true case reflect.Struct: m := map[string]any{} - for i := 0; i < e.NumField(); i++ { + for i := range e.NumField() { k := e.Type().Field(i).Name if !e.Type().Field(i).IsExported() { continue @@ -92,7 +92,7 @@ func dumpVarMarshalable(v any, dumped container.Set[uintptr]) (ret any, ok bool) return m, true case reflect.Array, reflect.Slice: var m []any - for i := 0; i < e.Len(); i++ { + for i := range e.Len() { v, _ := dumpVarMarshalable(e.Index(i).Interface(), dumped) m = append(m, v) } diff --git a/modules/templates/util_slice.go b/modules/templates/util_slice.go index a3318cc11a435..ed3e9450434fe 100644 --- a/modules/templates/util_slice.go +++ b/modules/templates/util_slice.go @@ -22,7 +22,7 @@ func (su *SliceUtils) Contains(s, v any) bool { if sv.Kind() != reflect.Slice && sv.Kind() != reflect.Array { panic(fmt.Sprintf("invalid type, expected slice or array, but got: %T", s)) } - for i := 0; i < sv.Len(); i++ { + for i := range sv.Len() { it := sv.Index(i) if !it.CanInterface() { continue diff --git a/modules/testlogger/testlogger.go b/modules/testlogger/testlogger.go index 8e970aa2bed99..60e281d403c1c 100644 --- a/modules/testlogger/testlogger.go +++ b/modules/testlogger/testlogger.go @@ -92,7 +92,7 @@ func (w *testLoggerWriterCloser) Reset() { // Printf takes a format and args and prints the string to os.Stdout func Printf(format string, args ...any) { if !log.CanColorStdout { - for i := 0; i < len(args); i++ { + for i := range args { if c, ok := args[i].(*log.ColoredValue); ok { args[i] = c.Value() } diff --git a/modules/translation/i18n/format.go b/modules/translation/i18n/format.go index e5e221831f5ec..c104401236827 100644 --- a/modules/translation/i18n/format.go +++ b/modules/translation/i18n/format.go @@ -26,7 +26,7 @@ func Format(format string, args ...any) (msg string, err error) { // 1. Tr(lang, key, [slice-items]) as Sprintf(msg, items...) // 2. Tr(lang, key, args...) as Sprintf(msg, args...) if len(args) == 1 { - for i := 0; i < val.Len(); i++ { + for i := range val.Len() { fmtArgs = append(fmtArgs, val.Index(i).Interface()) } } else { diff --git a/modules/util/remove.go b/modules/util/remove.go index d1e38faf5f1fb..3db0b5a796993 100644 --- a/modules/util/remove.go +++ b/modules/util/remove.go @@ -15,7 +15,7 @@ const windowsSharingViolationError syscall.Errno = 32 // Remove removes the named file or (empty) directory with at most 5 attempts. func Remove(name string) error { var err error - for i := 0; i < 5; i++ { + for range 5 { err = os.Remove(name) if err == nil { break @@ -44,7 +44,7 @@ func Remove(name string) error { // RemoveAll removes the named file or (empty) directory with at most 5 attempts. func RemoveAll(name string) error { var err error - for i := 0; i < 5; i++ { + for range 5 { err = os.RemoveAll(name) if err == nil { break @@ -73,7 +73,7 @@ func RemoveAll(name string) error { // Rename renames (moves) oldpath to newpath with at most 5 attempts. func Rename(oldpath, newpath string) error { var err error - for i := 0; i < 5; i++ { + for i := range 5 { err = os.Rename(oldpath, newpath) if err == nil { break diff --git a/modules/util/rotatingfilewriter/writer_test.go b/modules/util/rotatingfilewriter/writer_test.go index 88392797b375a..f6ea1d50ae742 100644 --- a/modules/util/rotatingfilewriter/writer_test.go +++ b/modules/util/rotatingfilewriter/writer_test.go @@ -23,7 +23,7 @@ func TestCompressOldFile(t *testing.T) { ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0o660) assert.NoError(t, err) - for i := 0; i < 999; i++ { + for range 999 { f.WriteString("This is a test file\n") ng.WriteString("This is a test file\n") } diff --git a/modules/util/string.go b/modules/util/string.go index 19cf75b8b35eb..a8b7e183030ae 100644 --- a/modules/util/string.go +++ b/modules/util/string.go @@ -80,7 +80,7 @@ func ToSnakeCase(input string) string { needSep = false } } - for i := 0; i < len(res); i++ { + for i := range res { if isSnakeCaseUpper(res[i]) { res[i] += 'a' - 'A' } @@ -103,7 +103,7 @@ func UnsafeStringToBytes(s string) []byte { func SplitTrimSpace(input, sep string) []string { input = strings.TrimSpace(input) var stringList []string - for _, s := range strings.Split(input, sep) { + for s := range strings.SplitSeq(input, sep) { if s = strings.TrimSpace(s); s != "" { stringList = append(stringList, s) } diff --git a/modules/validation/helpers.go b/modules/validation/helpers.go index 9f6cf5201a289..ba383ba195db1 100644 --- a/modules/validation/helpers.go +++ b/modules/validation/helpers.go @@ -7,6 +7,7 @@ import ( "net" "net/url" "regexp" + "slices" "strings" "sync" @@ -55,12 +56,7 @@ func IsValidSiteURL(uri string) bool { return false } - for _, scheme := range setting.Service.ValidSiteURLSchemes { - if scheme == u.Scheme { - return true - } - } - return false + return slices.Contains(setting.Service.ValidSiteURLSchemes, u.Scheme) } // IsEmailDomainListed checks whether the domain of an email address diff --git a/modules/web/handler.go b/modules/web/handler.go index 42a649714d9df..f2414d52fa65f 100644 --- a/modules/web/handler.go +++ b/modules/web/handler.go @@ -78,7 +78,7 @@ func prepareHandleArgsIn(resp http.ResponseWriter, req *http.Request, fn reflect isPreCheck := req == nil argsIn := make([]reflect.Value, fn.Type().NumIn()) - for i := 0; i < fn.Type().NumIn(); i++ { + for i := range fn.Type().NumIn() { argTyp := fn.Type().In(i) switch argTyp { case respWriterType: diff --git a/modules/web/middleware/binding.go b/modules/web/middleware/binding.go index 03e188f5098b4..8343e0d615170 100644 --- a/modules/web/middleware/binding.go +++ b/modules/web/middleware/binding.go @@ -34,7 +34,7 @@ func AssignForm(form any, data map[string]any) { val = val.Elem() } - for i := 0; i < typ.NumField(); i++ { + for i := range typ.NumField() { field := typ.Field(i) fieldName := field.Tag.Get("form") @@ -50,7 +50,7 @@ func AssignForm(form any, data map[string]any) { } func getRuleBody(field reflect.StructField, prefix string) string { - for _, rule := range strings.Split(field.Tag.Get("binding"), ";") { + for rule := range strings.SplitSeq(field.Tag.Get("binding"), ";") { if strings.HasPrefix(rule, prefix) { return rule[len(prefix) : len(rule)-1] } diff --git a/modules/web/router.go b/modules/web/router.go index da06b955b13af..a5564c9a48160 100644 --- a/modules/web/router.go +++ b/modules/web/router.go @@ -125,8 +125,8 @@ func (r *Router) Methods(methods, pattern string, h ...any) { middlewares, handlerFunc := wrapMiddlewareAndHandler(r.curMiddlewares, h) fullPattern := r.getPattern(pattern) if strings.Contains(methods, ",") { - methods := strings.Split(methods, ",") - for _, method := range methods { + methods := strings.SplitSeq(methods, ",") + for method := range methods { r.chiRouter.With(middlewares...).Method(strings.TrimSpace(method), fullPattern, handlerFunc) } } else { @@ -202,7 +202,7 @@ func (r *Router) normalizeRequestPath(resp http.ResponseWriter, req *http.Reques // if the path doesn't have repeated slashes, then no need to execute it if removeRepeatedSlashes { buf := &strings.Builder{} - for i := 0; i < len(normalizedPath); i++ { + for i := range len(normalizedPath) { if i == 0 || normalizedPath[i-1] != '/' || normalizedPath[i] != '/' { buf.WriteByte(normalizedPath[i]) } diff --git a/modules/web/router_path.go b/modules/web/router_path.go index b59948581a94e..35ad74a8d0a80 100644 --- a/modules/web/router_path.go +++ b/modules/web/router_path.go @@ -100,7 +100,7 @@ func isValidMethod(name string) bool { func newRouterPathMatcher(methods, pattern string, h ...any) *routerPathMatcher { middlewares, handlerFunc := wrapMiddlewareAndHandler(nil, h) p := &routerPathMatcher{methods: make(container.Set[string]), middlewares: middlewares, handlerFunc: handlerFunc} - for _, method := range strings.Split(methods, ",") { + for method := range strings.SplitSeq(methods, ",") { method = strings.TrimSpace(method) if !isValidMethod(method) { panic(fmt.Sprintf("invalid HTTP method: %s", method)) diff --git a/routers/api/actions/artifactsv4.go b/routers/api/actions/artifactsv4.go index 665156d936c57..2756147928a74 100644 --- a/routers/api/actions/artifactsv4.go +++ b/routers/api/actions/artifactsv4.go @@ -162,8 +162,8 @@ func (r artifactV4Routes) buildSignature(endp, expires, artifactName string, tas mac.Write([]byte(endp)) mac.Write([]byte(expires)) mac.Write([]byte(artifactName)) - mac.Write([]byte(fmt.Sprint(taskID))) - mac.Write([]byte(fmt.Sprint(artifactID))) + mac.Write(fmt.Append(nil, taskID)) + mac.Write(fmt.Append(nil, artifactID)) return mac.Sum(nil) } diff --git a/routers/api/packages/cargo/cargo.go b/routers/api/packages/cargo/cargo.go index 42ef13476c1d1..bae33496b82ec 100644 --- a/routers/api/packages/cargo/cargo.go +++ b/routers/api/packages/cargo/cargo.go @@ -95,10 +95,7 @@ type SearchResultMeta struct { // https://doc.rust-lang.org/cargo/reference/registries.html#search func SearchPackages(ctx *context.Context) { - page := ctx.FormInt("page") - if page < 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) perPage := ctx.FormInt("per_page") paginator := db.ListOptions{ Page: page, diff --git a/routers/api/packages/composer/composer.go b/routers/api/packages/composer/composer.go index c6c14e5cf4fb0..37138055794cb 100644 --- a/routers/api/packages/composer/composer.go +++ b/routers/api/packages/composer/composer.go @@ -53,10 +53,7 @@ func ServiceIndex(ctx *context.Context) { // SearchPackages searches packages, only "q" is supported // https://packagist.org/apidoc#search-packages func SearchPackages(ctx *context.Context) { - page := ctx.FormInt("page") - if page < 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) perPage := ctx.FormInt("per_page") paginator := db.ListOptions{ Page: page, diff --git a/routers/api/v1/repo/action.go b/routers/api/v1/repo/action.go index 6b4ce37fcf4a2..72460133263cb 100644 --- a/routers/api/v1/repo/action.go +++ b/routers/api/v1/repo/action.go @@ -1098,8 +1098,8 @@ func DeleteArtifact(ctx *context.APIContext) { func buildSignature(endp string, expires, artifactID int64) []byte { mac := hmac.New(sha256.New, setting.GetGeneralTokenSigningSecret()) mac.Write([]byte(endp)) - mac.Write([]byte(fmt.Sprint(expires))) - mac.Write([]byte(fmt.Sprint(artifactID))) + mac.Write(fmt.Append(nil, expires)) + mac.Write(fmt.Append(nil, artifactID)) return mac.Sum(nil) } diff --git a/routers/api/v1/repo/compare.go b/routers/api/v1/repo/compare.go index 6d427c8073422..06445e60ba643 100644 --- a/routers/api/v1/repo/compare.go +++ b/routers/api/v1/repo/compare.go @@ -74,7 +74,7 @@ func CompareDiff(ctx *context.APIContext) { apiCommits := make([]*api.Commit, 0, len(compareResult.compareInfo.Commits)) userCache := make(map[string]*user_model.User) - for i := 0; i < len(compareResult.compareInfo.Commits); i++ { + for i := range compareResult.compareInfo.Commits { apiCommit, err := convert.ToCommit(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, compareResult.compareInfo.Commits[i], userCache, convert.ToCommitOptions{ Stat: true, diff --git a/routers/api/v1/repo/issue_dependency.go b/routers/api/v1/repo/issue_dependency.go index 2048c76ea0ef5..1b58beb7b6e92 100644 --- a/routers/api/v1/repo/issue_dependency.go +++ b/routers/api/v1/repo/issue_dependency.go @@ -77,10 +77,7 @@ func GetIssueDependencies(ctx *context.APIContext) { return } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) limit := ctx.FormInt("limit") if limit == 0 { limit = setting.API.DefaultPagingNum @@ -328,10 +325,7 @@ func GetIssueBlocks(ctx *context.APIContext) { return } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) limit := ctx.FormInt("limit") if limit <= 1 { limit = setting.API.DefaultPagingNum diff --git a/routers/api/v1/repo/wiki.go b/routers/api/v1/repo/wiki.go index 8d73383f76573..c3f5e83cc6560 100644 --- a/routers/api/v1/repo/wiki.go +++ b/routers/api/v1/repo/wiki.go @@ -298,10 +298,7 @@ func ListWikiPages(ctx *context.APIContext) { return } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) limit := ctx.FormInt("limit") if limit <= 1 { limit = setting.API.DefaultPagingNum @@ -434,10 +431,7 @@ func ListPageRevisions(ctx *context.APIContext) { // get commit count - wiki revisions commitsCount, _ := wikiRepo.FileCommitsCount("master", pageFilename) - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) // get Commit Count commitsHistory, err := wikiRepo.CommitsByFileAndRange( diff --git a/routers/common/db.go b/routers/common/db.go index 61b331760c429..935a8cd4a32af 100644 --- a/routers/common/db.go +++ b/routers/common/db.go @@ -21,7 +21,7 @@ import ( // InitDBEngine In case of problems connecting to DB, retry connection. Eg, PGSQL in Docker Container on Synology func InitDBEngine(ctx context.Context) (err error) { log.Info("Beginning ORM engine initialization.") - for i := 0; i < setting.Database.DBConnectRetries; i++ { + for i := range setting.Database.DBConnectRetries { select { case <-ctx.Done(): return fmt.Errorf("Aborted due to shutdown:\nin retry ORM engine initialization") diff --git a/routers/install/install.go b/routers/install/install.go index 8544717f657dd..5f52e4ab735dd 100644 --- a/routers/install/install.go +++ b/routers/install/install.go @@ -11,6 +11,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strconv" "strings" "time" @@ -100,11 +101,8 @@ func Install(ctx *context.Context) { curDBType := setting.Database.Type.String() var isCurDBTypeSupported bool - for _, dbType := range setting.SupportedDatabaseTypes { - if dbType == curDBType { - isCurDBTypeSupported = true - break - } + if slices.Contains(setting.SupportedDatabaseTypes, curDBType) { + isCurDBTypeSupported = true } if !isCurDBTypeSupported { curDBType = "mysql" diff --git a/routers/web/admin/auths.go b/routers/web/admin/auths.go index 2b3bf1f77d774..7c7de5e3f6c9d 100644 --- a/routers/web/admin/auths.go +++ b/routers/web/admin/auths.go @@ -181,7 +181,7 @@ func parseOAuth2Config(form forms.AuthenticationForm) *oauth2.Source { customURLMapping = nil } var scopes []string - for _, s := range strings.Split(form.Oauth2Scopes, ",") { + for s := range strings.SplitSeq(form.Oauth2Scopes, ",") { s = strings.TrimSpace(s) if s != "" { scopes = append(scopes, s) diff --git a/routers/web/admin/config.go b/routers/web/admin/config.go index 520f14e89fa2e..5387d2b26fe26 100644 --- a/routers/web/admin/config.go +++ b/routers/web/admin/config.go @@ -61,7 +61,7 @@ func TestCache(ctx *context.Context) { func shadowPasswordKV(cfgItem, splitter string) string { fields := strings.Split(cfgItem, splitter) - for i := 0; i < len(fields); i++ { + for i := range fields { if strings.HasPrefix(fields[i], "password=") { fields[i] = "password=******" break diff --git a/routers/web/admin/diagnosis.go b/routers/web/admin/diagnosis.go index d040dbe0ba364..4bbd636f70a26 100644 --- a/routers/web/admin/diagnosis.go +++ b/routers/web/admin/diagnosis.go @@ -16,10 +16,7 @@ import ( ) func MonitorDiagnosis(ctx *context.Context) { - seconds := ctx.FormInt64("seconds") - if seconds <= 1 { - seconds = 1 - } + seconds := max(ctx.FormInt64("seconds"), 1) if seconds > 300 { seconds = 300 } diff --git a/routers/web/admin/notice.go b/routers/web/admin/notice.go index 21a8ab0d17642..e9d6abbe92eb1 100644 --- a/routers/web/admin/notice.go +++ b/routers/web/admin/notice.go @@ -26,10 +26,7 @@ func Notices(ctx *context.Context) { ctx.Data["PageIsAdminNotices"] = true total := system_model.CountNotices(ctx) - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) notices, err := system_model.Notices(ctx, page, setting.UI.Admin.NoticePagingNum) if err != nil { diff --git a/routers/web/admin/packages.go b/routers/web/admin/packages.go index 5122342259584..1904bfee11eda 100644 --- a/routers/web/admin/packages.go +++ b/routers/web/admin/packages.go @@ -24,10 +24,7 @@ const ( // Packages shows all packages func Packages(ctx *context.Context) { - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) query := ctx.FormTrim("q") packageType := ctx.FormTrim("type") sort := ctx.FormTrim("sort") diff --git a/routers/web/auth/openid.go b/routers/web/auth/openid.go index c3415cccac6d5..3043f75c8caf1 100644 --- a/routers/web/auth/openid.go +++ b/routers/web/auth/openid.go @@ -349,10 +349,7 @@ func RegisterOpenIDPost(ctx *context.Context) { context.VerifyCaptcha(ctx, tplSignUpOID, form) } - length := setting.MinPasswordLength - if length < 256 { - length = 256 - } + length := max(setting.MinPasswordLength, 256) password, err := util.CryptoRandomString(int64(length)) if err != nil { ctx.RenderWithErr(err.Error(), tplSignUpOID, form) diff --git a/routers/web/devtest/mock_actions.go b/routers/web/devtest/mock_actions.go index 3ce75dfad2d76..9043b0a212049 100644 --- a/routers/web/devtest/mock_actions.go +++ b/routers/web/devtest/mock_actions.go @@ -35,7 +35,7 @@ func generateMockStepsLog(logCur actions.LogCursor) (stepsLog []*actions.ViewSte if logCur.Step == 1 && logCur.Cursor == 0 { mockCount = 30 // for the first batch, return as many as possible to test the auto-expand and auto-scroll } - for i := 0; i < mockCount; i++ { + for range mockCount { logStr := mockedLogs[int(cur)%len(mockedLogs)] cur++ logStr = strings.ReplaceAll(logStr, "{step}", fmt.Sprintf("%d", logCur.Step)) diff --git a/routers/web/explore/code.go b/routers/web/explore/code.go index ae5ff3db761bd..fe318cfe73bbf 100644 --- a/routers/web/explore/code.go +++ b/routers/web/explore/code.go @@ -5,6 +5,7 @@ package explore import ( "net/http" + "slices" "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" @@ -94,11 +95,8 @@ func Code(ctx *context.Context) { loadRepoIDs := make([]int64, 0, len(searchResults)) for _, result := range searchResults { var find bool - for _, id := range loadRepoIDs { - if id == result.RepoID { - find = true - break - } + if slices.Contains(loadRepoIDs, result.RepoID) { + find = true } if !find { loadRepoIDs = append(loadRepoIDs, result.RepoID) diff --git a/routers/web/org/members.go b/routers/web/org/members.go index 7d88d6b1adee8..c508fa5e6ce93 100644 --- a/routers/web/org/members.go +++ b/routers/web/org/members.go @@ -28,10 +28,7 @@ func Members(ctx *context.Context) { ctx.Data["Title"] = org.FullName ctx.Data["PageIsOrgMembers"] = true - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) opts := &organization.FindOrgMembersOpts{ Doer: ctx.Doer, diff --git a/routers/web/org/projects.go b/routers/web/org/projects.go index 985fd2ca45d4d..85a1d08385dbc 100644 --- a/routers/web/org/projects.go +++ b/routers/web/org/projects.go @@ -50,10 +50,7 @@ func Projects(ctx *context.Context) { isShowClosed := strings.ToLower(ctx.FormTrim("state")) == "closed" keyword := ctx.FormTrim("q") - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) var projectType project_model.Type if ctx.ContextUser.IsOrganization() { diff --git a/routers/web/repo/actions/actions.go b/routers/web/repo/actions/actions.go index d07d195713f88..2d42eb0770c7b 100644 --- a/routers/web/repo/actions/actions.go +++ b/routers/web/repo/actions/actions.go @@ -370,10 +370,8 @@ func workflowDispatchConfig(w *model.Workflow) *WorkflowDispatch { if !decodeNode(w.RawOn, &val) { return nil } - for _, v := range val { - if v == "workflow_dispatch" { - return &WorkflowDispatch{} - } + if slices.Contains(val, "workflow_dispatch") { + return &WorkflowDispatch{} } case yaml.MappingNode: var val map[string]yaml.Node diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index 5d963eff66930..d02f0b7ca718e 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -45,10 +45,7 @@ func Branches(ctx *context.Context) { ctx.Data["PageIsViewCode"] = true ctx.Data["PageIsBranches"] = true - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) pageSize := setting.Git.BranchesRangeSize kw := ctx.FormString("q") diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go index 9c12ef9297813..dce78c1eae03e 100644 --- a/routers/web/repo/commit.go +++ b/routers/web/repo/commit.go @@ -66,10 +66,7 @@ func Commits(ctx *context.Context) { commitsCount := ctx.Repo.CommitsCount - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) pageSize := ctx.FormInt("limit") if pageSize <= 0 { @@ -230,10 +227,7 @@ func FileHistory(ctx *context.Context) { return } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) commits, err := ctx.Repo.GitRepo.CommitsByFileAndRange( git.CommitsByFileAndRangeOptions{ @@ -329,7 +323,7 @@ func Diff(ctx *context.Context) { } parents := make([]string, commit.ParentCount()) - for i := 0; i < commit.ParentCount(); i++ { + for i := range commit.ParentCount() { sha, err := commit.ParentID(i) if err != nil { ctx.NotFound(err) diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index 71bce759a9252..8210ddcd3cf81 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -956,7 +956,7 @@ func getExcerptLines(commit *git.Commit, filePath string, idxLeft, idxRight, chu defer reader.Close() scanner := bufio.NewScanner(reader) var diffLines []*gitdiff.DiffLine - for line := 0; line < idxRight+chunkSize; line++ { + for line := range idxRight + chunkSize { if ok := scanner.Scan(); !ok { break } diff --git a/routers/web/repo/editor.go b/routers/web/repo/editor.go index 3107d7b849c8d..8d0dc97d7b96f 100644 --- a/routers/web/repo/editor.go +++ b/routers/web/repo/editor.go @@ -803,7 +803,7 @@ func cleanUploadFileName(name string) string { // Rebase the filename name = util.PathJoinRel(name) // Git disallows any filenames to have a .git directory in them. - for _, part := range strings.Split(name, "/") { + for part := range strings.SplitSeq(name, "/") { if strings.ToLower(part) == ".git" { return "" } diff --git a/routers/web/repo/fork.go b/routers/web/repo/fork.go index 36e64bfee31ae..40061865a554e 100644 --- a/routers/web/repo/fork.go +++ b/routers/web/repo/fork.go @@ -7,6 +7,7 @@ import ( "errors" "net/http" "net/url" + "slices" "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" @@ -72,7 +73,7 @@ func getForkRepository(ctx *context.Context) *repo_model.Repository { } else { for i, org := range orgs { if org.ID == traverseParentRepo.OwnerID { - orgs = append(orgs[:i], orgs[i+1:]...) + orgs = slices.Delete(orgs, i, i+1) break } } diff --git a/routers/web/repo/githttp.go b/routers/web/repo/githttp.go index 5b7b0188dc13b..ded441077caab 100644 --- a/routers/web/repo/githttp.go +++ b/routers/web/repo/githttp.go @@ -13,6 +13,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "strconv" "strings" "sync" @@ -369,12 +370,7 @@ func containsParentDirectorySeparator(v string) bool { if !strings.Contains(v, "..") { return false } - for _, ent := range strings.FieldsFunc(v, isSlashRune) { - if ent == ".." { - return true - } - } - return false + return slices.Contains(strings.FieldsFunc(v, isSlashRune), "..") } func isSlashRune(r rune) bool { return r == '/' || r == '\\' } diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index dbbe29a3c3f4f..a11e213ced43d 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -211,7 +211,7 @@ func getActionIssues(ctx *context.Context) issues_model.IssueList { return nil } issueIDs := make([]int64, 0, 10) - for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") { + for stringIssueID := range strings.SplitSeq(commaSeparatedIssueIDs, ",") { issueID, err := strconv.ParseInt(stringIssueID, 10, 64) if err != nil { ctx.ServerError("ParseInt", err) @@ -572,7 +572,7 @@ func GetIssueAttachments(ctx *context.Context) { return } attachments := make([]*api.Attachment, len(issue.Attachments)) - for i := 0; i < len(issue.Attachments); i++ { + for i := range issue.Attachments { attachments[i] = convert.ToAttachment(ctx.Repo.Repository, issue.Attachments[i]) } ctx.JSON(http.StatusOK, attachments) @@ -588,7 +588,7 @@ func updateAttachments(ctx *context.Context, item any, files []string) error { default: return fmt.Errorf("unknown Type: %T", content) } - for i := 0; i < len(attachments); i++ { + for i := range attachments { if util.SliceContainsString(files, attachments[i].UUID) { continue } diff --git a/routers/web/repo/issue_comment.go b/routers/web/repo/issue_comment.go index bc84950701726..eafc23181c151 100644 --- a/routers/web/repo/issue_comment.go +++ b/routers/web/repo/issue_comment.go @@ -461,7 +461,7 @@ func GetCommentAttachments(ctx *context.Context) { ctx.ServerError("LoadAttachments", err) return } - for i := 0; i < len(comment.Attachments); i++ { + for i := range comment.Attachments { attachments = append(attachments, convert.ToAttachment(ctx.Repo.Repository, comment.Attachments[i])) } ctx.JSON(http.StatusOK, attachments) diff --git a/routers/web/repo/issue_list.go b/routers/web/repo/issue_list.go index a65ae77795584..5b010953a3779 100644 --- a/routers/web/repo/issue_list.go +++ b/routers/web/repo/issue_list.go @@ -589,10 +589,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption opt ctx.Data["TotalTrackedTime"] = totalTrackedTime } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) var total int switch { diff --git a/routers/web/repo/issue_new.go b/routers/web/repo/issue_new.go index 9f52396414f8b..09e9f34fc8959 100644 --- a/routers/web/repo/issue_new.go +++ b/routers/web/repo/issue_new.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "html/template" + "maps" "net/http" "slices" "sort" @@ -136,9 +137,7 @@ func NewIssue(ctx *context.Context) { ret := issue_service.ParseTemplatesFromDefaultBranch(ctx.Repo.Repository, ctx.Repo.GitRepo) templateLoaded, errs := setTemplateIfExists(ctx, issueTemplateKey, IssueTemplateCandidates, pageMetaData) - for k, v := range errs { - ret.TemplateErrors[k] = v - } + maps.Copy(ret.TemplateErrors, errs) if ctx.Written() { return } diff --git a/routers/web/repo/issue_view.go b/routers/web/repo/issue_view.go index 37e1b2793106e..a8317cb30d520 100644 --- a/routers/web/repo/issue_view.go +++ b/routers/web/repo/issue_view.go @@ -8,6 +8,7 @@ import ( "math/big" "net/http" "net/url" + "slices" "sort" activities_model "code.gitea.io/gitea/models/activities" @@ -194,7 +195,7 @@ func filterXRefComments(ctx *context.Context, issue *issues_model.Issue) error { return err } if !perm.CanReadIssuesOrPulls(c.RefIsPull) { - issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...) + issue.Comments = slices.Delete(issue.Comments, i, i+1) continue } } @@ -232,7 +233,7 @@ func combineLabelComments(issue *issues_model.Issue) { addedAndRemoved := false for i, label := range prev.AddedLabels { if cur.Label.ID == label.ID { - prev.AddedLabels = append(prev.AddedLabels[:i], prev.AddedLabels[i+1:]...) + prev.AddedLabels = slices.Delete(prev.AddedLabels, i, i+1) addedAndRemoved = true break } @@ -246,7 +247,7 @@ func combineLabelComments(issue *issues_model.Issue) { removedAndAdded := false for i, label := range prev.RemovedLabels { if cur.Label.ID == label.ID { - prev.RemovedLabels = append(prev.RemovedLabels[:i], prev.RemovedLabels[i+1:]...) + prev.RemovedLabels = slices.Delete(prev.RemovedLabels, i, i+1) removedAndAdded = true break } @@ -257,7 +258,7 @@ func combineLabelComments(issue *issues_model.Issue) { } prev.CreatedUnix = cur.CreatedUnix // remove the current comment since it has been combined to prev comment - issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...) + issue.Comments = slices.Delete(issue.Comments, i, i+1) i-- } else { // if prev is not a label comment, start a new group if cur.Content != "1" { diff --git a/routers/web/repo/milestone.go b/routers/web/repo/milestone.go index f1d0a857eaa70..30c5b3ca7275c 100644 --- a/routers/web/repo/milestone.go +++ b/routers/web/repo/milestone.go @@ -38,10 +38,7 @@ func Milestones(ctx *context.Context) { isShowClosed := ctx.FormString("state") == "closed" sortType := ctx.FormString("sort") keyword := ctx.FormTrim("q") - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) miles, total, err := db.FindAndCount[issues_model.Milestone](ctx, issues_model.FindMilestoneOptions{ ListOptions: db.ListOptions{ diff --git a/routers/web/repo/packages.go b/routers/web/repo/packages.go index 65a340a799700..d09a57c03fee8 100644 --- a/routers/web/repo/packages.go +++ b/routers/web/repo/packages.go @@ -21,10 +21,7 @@ const ( // Packages displays a list of all packages in the repository func Packages(ctx *context.Context) { - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) query := ctx.FormTrim("q") packageType := ctx.FormTrim("type") diff --git a/routers/web/repo/projects.go b/routers/web/repo/projects.go index 5b81a5e4d1b6e..3da9ca50b93ae 100644 --- a/routers/web/repo/projects.go +++ b/routers/web/repo/projects.go @@ -61,10 +61,7 @@ func Projects(ctx *context.Context) { isShowClosed := strings.ToLower(ctx.FormTrim("state")) == "closed" keyword := ctx.FormTrim("q") repo := ctx.Repo.Repository - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) ctx.Data["OpenCount"] = repo.NumOpenProjects ctx.Data["ClosedCount"] = repo.NumClosedProjects diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 73baf683ed577..dff33c2c43ea8 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -89,7 +89,7 @@ func checkContextUser(ctx *context.Context, uid int64) *user_model.User { if !ctx.Doer.IsAdmin { orgsAvailable := []*organization.Organization{} - for i := 0; i < len(orgs); i++ { + for i := range orgs { if orgs[i].CanCreateRepo() { orgsAvailable = append(orgsAvailable, orgs[i]) } diff --git a/routers/web/repo/setting/lfs.go b/routers/web/repo/setting/lfs.go index 655291d25c3a4..d8e941fc58b23 100644 --- a/routers/web/repo/setting/lfs.go +++ b/routers/web/repo/setting/lfs.go @@ -44,10 +44,7 @@ func LFSFiles(ctx *context.Context) { ctx.NotFound(nil) return } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) total, err := git_model.CountLFSMetaObjects(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("LFSFiles", err) @@ -76,10 +73,7 @@ func LFSLocks(ctx *context.Context) { } ctx.Data["LFSFilesLink"] = ctx.Repo.RepoLink + "/settings/lfs" - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) total, err := git_model.CountLFSLockByRepoID(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("LFSLocks", err) @@ -328,7 +322,7 @@ func LFSFileGet(ctx *context.Context) { ctx.Data["FileContent"] = gotemplate.HTML(output.String()) output.Reset() - for i := 0; i < len(lines); i++ { + for i := range lines { output.WriteString(fmt.Sprintf(`%d`, i+1, i+1)) } ctx.Data["LineNums"] = gotemplate.HTML(output.String()) diff --git a/routers/web/repo/wiki.go b/routers/web/repo/wiki.go index 98c84b6993154..f65bc142f581c 100644 --- a/routers/web/repo/wiki.go +++ b/routers/web/repo/wiki.go @@ -418,10 +418,7 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) ctx.Data["CommitCount"] = commitsCount // get page - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) // get Commit Count commitsHistory, err := wikiRepo.CommitsByFileAndRange( diff --git a/routers/web/shared/actions/runners.go b/routers/web/shared/actions/runners.go index 444bd960db58d..1e264fa995882 100644 --- a/routers/web/shared/actions/runners.go +++ b/routers/web/shared/actions/runners.go @@ -109,10 +109,7 @@ func Runners(ctx *context.Context) { return } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) opts := actions_model.FindRunnerOptions{ ListOptions: db.ListOptions{ @@ -180,10 +177,7 @@ func RunnersEdit(ctx *context.Context) { return } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) runnerID := ctx.PathParamInt64("runnerid") ownerID := rCtx.OwnerID diff --git a/routers/web/user/code.go b/routers/web/user/code.go index 665ce1a6a6fc1..2e49c03410e64 100644 --- a/routers/web/user/code.go +++ b/routers/web/user/code.go @@ -5,6 +5,7 @@ package user import ( "net/http" + "slices" "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" @@ -90,11 +91,8 @@ func CodeSearch(ctx *context.Context) { loadRepoIDs := make([]int64, 0, len(searchResults)) for _, result := range searchResults { var find bool - for _, id := range loadRepoIDs { - if id == result.RepoID { - find = true - break - } + if slices.Contains(loadRepoIDs, result.RepoID) { + find = true } if !find { loadRepoIDs = append(loadRepoIDs, result.RepoID) diff --git a/routers/web/user/home.go b/routers/web/user/home.go index dc78950cf2ecb..8339c7cf0c0f7 100644 --- a/routers/web/user/home.go +++ b/routers/web/user/home.go @@ -197,7 +197,7 @@ func Milestones(ctx *context.Context) { reposQuery = reposQuery[1 : len(reposQuery)-1] // for each ID (delimiter ",") add to int to repoIDs - for _, rID := range strings.Split(reposQuery, ",") { + for rID := range strings.SplitSeq(reposQuery, ",") { // Ensure nonempty string entries if rID != "" && rID != "0" { rIDint64, err := strconv.ParseInt(rID, 10, 64) @@ -258,7 +258,7 @@ func Milestones(ctx *context.Context) { } if milestones[i].Repo == nil { log.Warn("Cannot find milestone %d 's repository %d", milestones[i].ID, milestones[i].RepoID) - milestones = append(milestones[:i], milestones[i+1:]...) + milestones = slices.Delete(milestones, i, i+1) continue } @@ -520,10 +520,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) { opts.IsClosed = optional.Some(isShowClosed) // Make sure page number is at least 1. Will be posted to ctx.Data. - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) opts.Paginator = &db.ListOptions{ Page: page, PageSize: setting.UI.IssuePagingNum, diff --git a/routers/web/user/notification.go b/routers/web/user/notification.go index 1c91ff6364324..bc4ee11401cdf 100644 --- a/routers/web/user/notification.go +++ b/routers/web/user/notification.go @@ -230,10 +230,7 @@ func NotificationPurgePost(ctx *context.Context) { // NotificationSubscriptions returns the list of subscribed issues func NotificationSubscriptions(ctx *context.Context) { - page := ctx.FormInt("page") - if page < 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) sortType := ctx.FormString("sort") ctx.Data["SortType"] = sortType @@ -365,10 +362,7 @@ func NotificationSubscriptions(ctx *context.Context) { // NotificationWatching returns the list of watching repos func NotificationWatching(ctx *context.Context) { - page := ctx.FormInt("page") - if page < 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) keyword := ctx.FormTrim("q") ctx.Data["Keyword"] = keyword diff --git a/routers/web/user/package.go b/routers/web/user/package.go index c01bc96e2bfe6..00a8cc89835cc 100644 --- a/routers/web/user/package.go +++ b/routers/web/user/package.go @@ -43,10 +43,7 @@ const ( // ListPackages displays a list of all packages of the context user func ListPackages(ctx *context.Context) { shared_user.PrepareContextForProfileBigAvatar(ctx) - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) query := ctx.FormTrim("q") packageType := ctx.FormTrim("type") @@ -324,10 +321,7 @@ func ListPackageVersions(ctx *context.Context) { return } - page := ctx.FormInt("page") - if page <= 1 { - page = 1 - } + page := max(ctx.FormInt("page"), 1) pagination := &db.ListOptions{ PageSize: setting.UI.PackagesPagingNum, Page: page, diff --git a/services/actions/job_emitter.go b/services/actions/job_emitter.go index 1f859fcf70506..3d1fceca3148d 100644 --- a/services/actions/job_emitter.go +++ b/services/actions/job_emitter.go @@ -107,7 +107,7 @@ func newJobStatusResolver(jobs actions_model.ActionJobList) *jobStatusResolver { func (r *jobStatusResolver) Resolve() map[int64]actions_model.Status { ret := map[int64]actions_model.Status{} - for i := 0; i < len(r.statuses); i++ { + for range len(r.statuses) { updated := r.resolve() if len(updated) == 0 { return ret diff --git a/services/actions/rerun.go b/services/actions/rerun.go index 60f66509058f5..478720cddc045 100644 --- a/services/actions/rerun.go +++ b/services/actions/rerun.go @@ -4,6 +4,8 @@ package actions import ( + "slices" + actions_model "code.gitea.io/gitea/models/actions" "code.gitea.io/gitea/modules/container" ) @@ -20,13 +22,10 @@ func GetAllRerunJobs(job *actions_model.ActionRunJob, allJobs []*actions_model.A if rerunJobsIDSet.Contains(j.JobID) { continue } - for _, need := range j.Needs { - if rerunJobsIDSet.Contains(need) { - found = true - rerunJobs = append(rerunJobs, j) - rerunJobsIDSet.Add(j.JobID) - break - } + if slices.ContainsFunc(j.Needs, rerunJobsIDSet.Contains) { + found = true + rerunJobs = append(rerunJobs, j) + rerunJobsIDSet.Add(j.JobID) } } if !found { diff --git a/services/auth/source/oauth2/urlmapping.go b/services/auth/source/oauth2/urlmapping.go index d0442d58a8b49..b9f445caa7038 100644 --- a/services/auth/source/oauth2/urlmapping.go +++ b/services/auth/source/oauth2/urlmapping.go @@ -14,11 +14,11 @@ type CustomURLMapping struct { // CustomURLSettings describes the urls values and availability to use when customizing OAuth2 provider URLs type CustomURLSettings struct { - AuthURL Attribute `json:",omitempty"` - TokenURL Attribute `json:",omitempty"` - ProfileURL Attribute `json:",omitempty"` - EmailURL Attribute `json:",omitempty"` - Tenant Attribute `json:",omitempty"` + AuthURL Attribute + TokenURL Attribute + ProfileURL Attribute + EmailURL Attribute + Tenant Attribute } // Attribute describes the availability, and required status for a custom url configuration diff --git a/services/context/api.go b/services/context/api.go index c163de036c719..9f31cad00b67d 100644 --- a/services/context/api.go +++ b/services/context/api.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "net/url" + "slices" "strings" "code.gitea.io/gitea/models/unit" @@ -375,11 +376,5 @@ func (ctx *APIContext) IsUserRepoAdmin() bool { // IsUserRepoWriter returns true if current user has "write" privilege in current repo func (ctx *APIContext) IsUserRepoWriter(unitTypes []unit.Type) bool { - for _, unitType := range unitTypes { - if ctx.Repo.CanWrite(unitType) { - return true - } - } - - return false + return slices.ContainsFunc(unitTypes, ctx.Repo.CanWrite) } diff --git a/services/context/permission.go b/services/context/permission.go index 7055f798da3f0..c0a5a98724729 100644 --- a/services/context/permission.go +++ b/services/context/permission.go @@ -5,6 +5,7 @@ package context import ( "net/http" + "slices" auth_model "code.gitea.io/gitea/models/auth" repo_model "code.gitea.io/gitea/models/repo" @@ -34,10 +35,8 @@ func CanWriteToBranch() func(ctx *Context) { // RequireUnitWriter returns a middleware for requiring repository write to one of the unit permission func RequireUnitWriter(unitTypes ...unit.Type) func(ctx *Context) { return func(ctx *Context) { - for _, unitType := range unitTypes { - if ctx.Repo.CanWrite(unitType) { - return - } + if slices.ContainsFunc(unitTypes, ctx.Repo.CanWrite) { + return } ctx.NotFound(nil) } diff --git a/services/context/upload/upload.go b/services/context/upload/upload.go index da4370a43364c..c5cdf1e3f8891 100644 --- a/services/context/upload/upload.go +++ b/services/context/upload/upload.go @@ -39,7 +39,7 @@ func Verify(buf []byte, fileName, allowedTypesStr string) error { allowedTypesStr = strings.ReplaceAll(allowedTypesStr, "|", ",") // compat for old config format allowedTypes := []string{} - for _, entry := range strings.Split(allowedTypesStr, ",") { + for entry := range strings.SplitSeq(allowedTypesStr, ",") { entry = strings.ToLower(strings.TrimSpace(entry)) if entry != "" { allowedTypes = append(allowedTypes, entry) diff --git a/services/convert/git_commit.go b/services/convert/git_commit.go index e0efcddbcb0c7..a20ae1c3b48ac 100644 --- a/services/convert/git_commit.go +++ b/services/convert/git_commit.go @@ -140,7 +140,7 @@ func ToCommit(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Rep // Retrieve parent(s) of the commit apiParents := make([]*api.CommitMeta, commit.ParentCount()) - for i := 0; i < commit.ParentCount(); i++ { + for i := range commit.ParentCount() { sha, _ := commit.ParentID(i) apiParents[i] = &api.CommitMeta{ URL: repo.APIURL() + "/git/commits/" + url.PathEscape(sha.String()), diff --git a/services/doctor/mergebase.go b/services/doctor/mergebase.go index de460c419051a..938d59fd1bd06 100644 --- a/services/doctor/mergebase.go +++ b/services/doctor/mergebase.go @@ -6,6 +6,7 @@ package doctor import ( "context" "fmt" + "slices" "strings" "code.gitea.io/gitea/models/db" @@ -62,7 +63,7 @@ func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) erro return nil } - refs := append([]string{}, parents[1:]...) + refs := slices.Clone(parents[1:]) refs = append(refs, pr.GetGitRefName()) cmd := git.NewCommand(ctx, "merge-base").AddDashesAndList(refs...) pr.MergeBase, _, err = cmd.RunStdString(&git.RunOpts{Dir: repoPath}) diff --git a/services/feed/feed_test.go b/services/feed/feed_test.go index 1e4d029e18cf3..4da039e922cbb 100644 --- a/services/feed/feed_test.go +++ b/services/feed/feed_test.go @@ -147,7 +147,7 @@ func TestRepoActions(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) _ = db.TruncateBeans(db.DefaultContext, &activities_model.Action{}) - for i := 0; i < 3; i++ { + for i := range 3 { _ = db.Insert(db.DefaultContext, &activities_model.Action{ UserID: 2 + int64(i), ActUserID: 2, diff --git a/services/forms/repo_form.go b/services/forms/repo_form.go index 70019f3fa907e..6a98112e01f0c 100644 --- a/services/forms/repo_form.go +++ b/services/forms/repo_form.go @@ -6,6 +6,7 @@ package forms import ( "net/http" + "slices" "strings" issues_model "code.gitea.io/gitea/models/issues" @@ -489,13 +490,7 @@ func (i IssueLockForm) HasValidReason() bool { return true } - for _, v := range setting.Repository.Issue.LockReasons { - if v == i.Reason { - return true - } - } - - return false + return slices.Contains(setting.Repository.Issue.LockReasons, i.Reason) } // CreateProjectForm form for creating a project diff --git a/services/gitdiff/csv.go b/services/gitdiff/csv.go index 8db73c56a3744..06bf3084b1c72 100644 --- a/services/gitdiff/csv.go +++ b/services/gitdiff/csv.go @@ -134,7 +134,7 @@ func createCsvDiffSingle(reader *csv.Reader, celltype TableDiffCellType) ([]*Tab return nil, err } cells := make([]*TableDiffCell, len(row)) - for j := 0; j < len(row); j++ { + for j := range row { if celltype == TableDiffCellDel { cells[j] = &TableDiffCell{LeftCell: row[j], Type: celltype} } else { @@ -360,16 +360,16 @@ func getColumnMapping(baseCSVReader, headCSVReader *csvReader) ([]int, []int) { } // Initializes all head2base mappings to be unmappedColumn (-1) - for i := 0; i < len(head2BaseColMap); i++ { + for i := range head2BaseColMap { head2BaseColMap[i] = unmappedColumn } // Loops through the baseRow and see if there is a match in the head row - for i := 0; i < len(baseRow); i++ { + for i := range baseRow { base2HeadColMap[i] = unmappedColumn baseCell, err := getCell(baseRow, i) if err == nil { - for j := 0; j < len(headRow); j++ { + for j := range headRow { if head2BaseColMap[j] == -1 { headCell, err := getCell(headRow, j) if err == nil && baseCell == headCell { @@ -390,7 +390,7 @@ func getColumnMapping(baseCSVReader, headCSVReader *csvReader) ([]int, []int) { // tryMapColumnsByContent tries to map missing columns by the content of the first lines. func tryMapColumnsByContent(baseCSVReader *csvReader, base2HeadColMap []int, headCSVReader *csvReader, head2BaseColMap []int) { - for i := 0; i < len(base2HeadColMap); i++ { + for i := range base2HeadColMap { headStart := 0 for base2HeadColMap[i] == unmappedColumn && headStart < len(head2BaseColMap) { if head2BaseColMap[headStart] == unmappedColumn { @@ -424,7 +424,7 @@ func getCell(row []string, column int) (string, error) { // countUnmappedColumns returns the count of unmapped columns. func countUnmappedColumns(mapping []int) int { count := 0 - for i := 0; i < len(mapping); i++ { + for i := range mapping { if mapping[i] == unmappedColumn { count++ } @@ -450,7 +450,7 @@ func tryMergeLines(lines []*DiffLine) [][2]int { result := make([][2]int, len(ids)) j := 0 - for i = 0; i < len(ids); i++ { + for i = range ids { if ids[i][0] == 0 { if j > 0 && result[j-1][1] == 0 { temp := j diff --git a/services/gitdiff/gitdiff.go b/services/gitdiff/gitdiff.go index 064f05cfce9f7..13bc2e1a50066 100644 --- a/services/gitdiff/gitdiff.go +++ b/services/gitdiff/gitdiff.go @@ -501,10 +501,7 @@ func ParsePatch(ctx context.Context, maxLines, maxLineCharacters, maxFiles int, // OK let's set a reasonable buffer size. // This should be at least the size of maxLineCharacters or 4096 whichever is larger. - readerSize := maxLineCharacters - if readerSize < 4096 { - readerSize = 4096 - } + readerSize := max(maxLineCharacters, 4096) input := bufio.NewReaderSize(reader, readerSize) line, err := input.ReadString('\n') diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go index 5a0e7405b18c7..e1eefb6803b15 100644 --- a/services/gitdiff/gitdiff_test.go +++ b/services/gitdiff/gitdiff_test.go @@ -445,7 +445,7 @@ index 0000000..6bb8f39 ` diffBuilder.WriteString(diff) - for i := 0; i < 35; i++ { + for i := range 35 { diffBuilder.WriteString("+line" + strconv.Itoa(i) + "\n") } diff = diffBuilder.String() @@ -482,11 +482,11 @@ index 0000000..6bb8f39 diffBuilder.Reset() diffBuilder.WriteString(diff) - for i := 0; i < 33; i++ { + for i := range 33 { diffBuilder.WriteString("+line" + strconv.Itoa(i) + "\n") } diffBuilder.WriteString("+line33") - for i := 0; i < 512; i++ { + for range 512 { diffBuilder.WriteString("0123456789ABCDEF") } diffBuilder.WriteByte('\n') diff --git a/services/gitdiff/highlightdiff.go b/services/gitdiff/highlightdiff.go index 35d48445504ae..fdafc9aa87d79 100644 --- a/services/gitdiff/highlightdiff.go +++ b/services/gitdiff/highlightdiff.go @@ -13,7 +13,7 @@ import ( // token is a html tag or entity, eg: "", "", "<" func extractHTMLToken(s string) (before, token, after string, valid bool) { - for pos1 := 0; pos1 < len(s); pos1++ { + for pos1 := range len(s) { if s[pos1] == '<' { pos2 := strings.IndexByte(s[pos1:], '>') if pos2 == -1 { diff --git a/services/gitdiff/highlightdiff_test.go b/services/gitdiff/highlightdiff_test.go index 545a060e20491..cd64c5116349f 100644 --- a/services/gitdiff/highlightdiff_test.go +++ b/services/gitdiff/highlightdiff_test.go @@ -101,7 +101,7 @@ func TestDiffWithHighlightPlaceholderExhausted(t *testing.T) { func TestDiffWithHighlightTagMatch(t *testing.T) { totalOverflow := 0 - for i := 0; i < 100; i++ { + for i := range 100 { hcd := newHighlightCodeDiff() hcd.placeholderMaxCount = i diffs := hcd.diffWithHighlight( diff --git a/services/lfs/locks.go b/services/lfs/locks.go index 1d464f4a669ac..264001f0f984f 100644 --- a/services/lfs/locks.go +++ b/services/lfs/locks.go @@ -74,10 +74,7 @@ func GetListLockHandler(ctx *context.Context) { } ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType) - cursor := ctx.FormInt("cursor") - if cursor < 0 { - cursor = 0 - } + cursor := max(ctx.FormInt("cursor"), 0) limit := ctx.FormInt("limit") if limit > setting.LFS.LocksPagingNum && setting.LFS.LocksPagingNum > 0 { limit = setting.LFS.LocksPagingNum @@ -239,10 +236,7 @@ func VerifyLockHandler(ctx *context.Context) { ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType) - cursor := ctx.FormInt("cursor") - if cursor < 0 { - cursor = 0 - } + cursor := max(ctx.FormInt("cursor"), 0) limit := ctx.FormInt("limit") if limit > setting.LFS.LocksPagingNum && setting.LFS.LocksPagingNum > 0 { limit = setting.LFS.LocksPagingNum diff --git a/services/lfs/server.go b/services/lfs/server.go index c4866edaab233..2f42bd145ecce 100644 --- a/services/lfs/server.go +++ b/services/lfs/server.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" "io" + "maps" "net/http" "net/url" "path" @@ -479,9 +480,7 @@ func buildObjectResponse(rc *requestContext, pointer lfs_module.Pointer, downloa rep.Actions["upload"] = &lfs_module.Link{Href: rc.UploadLink(pointer), Header: header} verifyHeader := make(map[string]string) - for key, value := range header { - verifyHeader[key] = value - } + maps.Copy(verifyHeader, header) // This is only needed to workaround https://github.com/git-lfs/git-lfs/issues/3662 verifyHeader["Accept"] = lfs_module.AcceptHeader diff --git a/services/mailer/sender/message_test.go b/services/mailer/sender/message_test.go index 63d0bc349a9c6..ae153ebf05d0c 100644 --- a/services/mailer/sender/message_test.go +++ b/services/mailer/sender/message_test.go @@ -108,9 +108,9 @@ func extractMailHeaderAndContent(t *testing.T, mail string) (map[string]string, } content := strings.TrimSpace("boundary=" + parts[1]) - hParts := strings.Split(parts[0], "\n") + hParts := strings.SplitSeq(parts[0], "\n") - for _, hPart := range hParts { + for hPart := range hParts { parts := strings.SplitN(hPart, ":", 2) hk := strings.TrimSpace(parts[0]) if hk != "" { diff --git a/services/migrations/codecommit.go b/services/migrations/codecommit.go index c45f9e594375a..e0be42533f083 100644 --- a/services/migrations/codecommit.go +++ b/services/migrations/codecommit.go @@ -155,10 +155,7 @@ func (c *CodeCommitDownloader) GetPullRequests(ctx context.Context, page, perPag } startIndex := (page - 1) * perPage - endIndex := page * perPage - if endIndex > len(allPullRequestIDs) { - endIndex = len(allPullRequestIDs) - } + endIndex := min(page*perPage, len(allPullRequestIDs)) batch := allPullRequestIDs[startIndex:endIndex] prs := make([]*base.PullRequest, 0, len(batch)) diff --git a/services/migrations/dump.go b/services/migrations/dump.go index 11efc1816307d..cc624163500e0 100644 --- a/services/migrations/dump.go +++ b/services/migrations/dump.go @@ -603,7 +603,7 @@ func (g *RepositoryDumper) CreatePullRequests(ctx context.Context, prs ...*base. defer encoder.Close() count := 0 - for i := 0; i < len(prs); i++ { + for i := range prs { pr := prs[i] if err := g.handlePullRequest(ctx, pr); err != nil { log.Error("PR #%d in %s/%s failed - skipping", pr.Number, g.repoOwner, g.repoName, err) diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 79356ddf5b8a2..8fee616f4e27d 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -239,7 +239,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { assert.NoError(t, git.InitRepository(git.DefaultContext, fromRepo.RepoPath(), false, fromRepo.ObjectFormatName)) err := git.NewCommand(git.DefaultContext, "symbolic-ref").AddDynamicArguments("HEAD", git.BranchPrefix+baseRef).Run(&git.RunOpts{Dir: fromRepo.RepoPath()}) assert.NoError(t, err) - assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", fromRepo.RepoPath())), 0o644)) + assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), fmt.Appendf(nil, "# Testing Repository\n\nOriginally created in: %s", fromRepo.RepoPath()), 0o644)) assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) signature := git.Signature{ Email: "test@example.com", @@ -287,7 +287,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { })) _, _, err = git.NewCommand(git.DefaultContext, "checkout", "-b").AddDynamicArguments(forkHeadRef).RunStdString(&git.RunOpts{Dir: forkRepo.RepoPath()}) assert.NoError(t, err) - assert.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# branch2 %s", forkRepo.RepoPath())), 0o644)) + assert.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), fmt.Appendf(nil, "# branch2 %s", forkRepo.RepoPath()), 0o644)) assert.NoError(t, git.AddChanges(forkRepo.RepoPath(), true)) assert.NoError(t, git.CommitChanges(forkRepo.RepoPath(), git.CommitChangesOptions{ Committer: &signature, diff --git a/services/migrations/github.go b/services/migrations/github.go index b00d6ed27f6c1..0384a9709075a 100644 --- a/services/migrations/github.go +++ b/services/migrations/github.go @@ -89,8 +89,8 @@ func NewGithubDownloaderV3(_ context.Context, baseURL, userName, password, token } if token != "" { - tokens := strings.Split(token, ",") - for _, token := range tokens { + tokens := strings.SplitSeq(token, ",") + for token := range tokens { token = strings.TrimSpace(token) ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, @@ -142,7 +142,7 @@ func (g *GithubDownloaderV3) addClient(client *http.Client, baseURL string) { func (g *GithubDownloaderV3) waitAndPickClient(ctx context.Context) { var recentIdx int var maxRemaining int - for i := 0; i < len(g.clients); i++ { + for i := range g.clients { if g.rates[i] != nil && g.rates[i].Remaining > maxRemaining { maxRemaining = g.rates[i].Remaining recentIdx = i diff --git a/services/oauth2_provider/access_token.go b/services/oauth2_provider/access_token.go index 5cb6fb64c5e32..abc876d03969c 100644 --- a/services/oauth2_provider/access_token.go +++ b/services/oauth2_provider/access_token.go @@ -82,7 +82,7 @@ func GrantAdditionalScopes(grantScopes string) auth.AccessTokenScope { } var accessScopes []string // the scopes for access control, but not for general information - for _, scope := range strings.Split(grantScopes, " ") { + for scope := range strings.SplitSeq(grantScopes, " ") { if scope != "" && !slices.Contains(generalScopesSupported, scope) { accessScopes = append(accessScopes, scope) } diff --git a/services/org/team_test.go b/services/org/team_test.go index 3791776e46e9f..d1a9a14ef952d 100644 --- a/services/org/team_test.go +++ b/services/org/team_test.go @@ -222,7 +222,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { // Create repos. repoIDs := make([]int64, 0) - for i := 0; i < 3; i++ { + for i := range 3 { r, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user, org.AsUser(), repo_service.CreateRepoOptions{Name: fmt.Sprintf("repo-%d", i)}) assert.NoError(t, err, "CreateRepository %d", i) if r != nil { diff --git a/services/packages/arch/vercmp.go b/services/packages/arch/vercmp.go index 0d33dda0f1232..b37c05c0a8ed0 100644 --- a/services/packages/arch/vercmp.go +++ b/services/packages/arch/vercmp.go @@ -35,12 +35,8 @@ func parseEVR(evr string) (epoch, version, release string) { func compareSegments(a, b []string) int { lenA, lenB := len(a), len(b) var l int - if lenA > lenB { - l = lenB - } else { - l = lenA - } - for i := 0; i < l; i++ { + l = min(lenA, lenB) + for i := range l { if r := compare(a[i], b[i]); r != 0 { return r } diff --git a/services/packages/arch/vercmp_test.go b/services/packages/arch/vercmp_test.go index 2014a6d429d14..07456a30b628e 100644 --- a/services/packages/arch/vercmp_test.go +++ b/services/packages/arch/vercmp_test.go @@ -16,7 +16,7 @@ func TestCompareVersions(t *testing.T) { {"1", "1.0", "1.1", "1.1.1", "1.2", "2.0", "3.0.0"}, } for _, check := range checks { - for i := 0; i < len(check)-1; i++ { + for i := range len(check) - 1 { require.Equal(t, -1, compareVersions(check[i], check[i+1])) require.Equal(t, 1, compareVersions(check[i+1], check[i])) } diff --git a/services/pull/merge.go b/services/pull/merge.go index 9c909ef7958b1..7f0a6daa2743d 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -7,6 +7,7 @@ package pull import ( "context" "fmt" + "maps" "os" "path/filepath" "regexp" @@ -93,9 +94,7 @@ func getMergeMessage(ctx context.Context, baseGitRepo *git.Repository, pr *issue vars["HeadRepoOwnerName"] = pr.HeadRepo.OwnerName vars["HeadRepoName"] = pr.HeadRepo.Name } - for extraKey, extraValue := range extraVars { - vars[extraKey] = extraValue - } + maps.Copy(vars, extraVars) refs, err := pr.ResolveCrossReferences(ctx) if err == nil { closeIssueIndexes := make([]string, 0, len(refs)) diff --git a/services/repository/adopt_test.go b/services/repository/adopt_test.go index 123cedc1f257b..c3a012df2cab8 100644 --- a/services/repository/adopt_test.go +++ b/services/repository/adopt_test.go @@ -28,7 +28,7 @@ func TestCheckUnadoptedRepositories_Add(t *testing.T) { } total := 30 - for i := 0; i < total; i++ { + for range total { unadopted.add("something") } diff --git a/services/repository/commitstatus/commitstatus.go b/services/repository/commitstatus/commitstatus.go index f369a303e6ce4..1c7dd3d25e247 100644 --- a/services/repository/commitstatus/commitstatus.go +++ b/services/repository/commitstatus/commitstatus.go @@ -24,7 +24,7 @@ import ( ) func getCacheKey(repoID int64, brancheName string) string { - hashBytes := sha256.Sum256([]byte(fmt.Sprintf("%d:%s", repoID, brancheName))) + hashBytes := sha256.Sum256(fmt.Appendf(nil, "%d:%s", repoID, brancheName)) return fmt.Sprintf("commit_status:%x", hashBytes) } diff --git a/services/repository/create.go b/services/repository/create.go index 23aacd6f958d8..198ec72bbb7a3 100644 --- a/services/repository/create.go +++ b/services/repository/create.go @@ -100,8 +100,8 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, // .gitignore if len(opts.Gitignores) > 0 { var buf bytes.Buffer - names := strings.Split(opts.Gitignores, ",") - for _, name := range names { + names := strings.SplitSeq(opts.Gitignores, ",") + for name := range names { data, err = options.Gitignore(name) if err != nil { return fmt.Errorf("GetRepoInitFile[%s]: %w", name, err) diff --git a/services/repository/delete.go b/services/repository/delete.go index 3b953d3ec7f37..af09e278f02b0 100644 --- a/services/repository/delete.go +++ b/services/repository/delete.go @@ -112,7 +112,7 @@ func DeleteRepositoryDirectly(ctx context.Context, doer *user_model.User, repoID return err } releaseAttachments := make([]string, 0, len(attachments)) - for i := 0; i < len(attachments); i++ { + for i := range attachments { releaseAttachments = append(releaseAttachments, attachments[i].RelativePath()) } diff --git a/services/repository/files/file.go b/services/repository/files/file.go index 2caa1b4946937..2b7442f7c1565 100644 --- a/services/repository/files/file.go +++ b/services/repository/files/file.go @@ -134,7 +134,7 @@ func CleanUploadFileName(name string) string { // Rebase the filename name = util.PathJoinRel(name) // Git disallows any filenames to have a .git directory in them. - for _, part := range strings.Split(name, "/") { + for part := range strings.SplitSeq(name, "/") { if strings.ToLower(part) == ".git" { return "" } diff --git a/services/repository/files/temp_repo.go b/services/repository/files/temp_repo.go index cf1402397b60c..cc70085f8e4fb 100644 --- a/services/repository/files/temp_repo.go +++ b/services/repository/files/temp_repo.go @@ -127,7 +127,7 @@ func (t *TemporaryUploadRepository) LsFiles(filenames ...string) ([]string, erro } fileList := make([]string, 0, len(filenames)) - for _, line := range bytes.Split(stdOut.Bytes(), []byte{'\000'}) { + for line := range bytes.SplitSeq(stdOut.Bytes(), []byte{'\000'}) { fileList = append(fileList, string(line)) } diff --git a/services/repository/files/tree.go b/services/repository/files/tree.go index 6775186afdd8e..e94d9c1b170d4 100644 --- a/services/repository/files/tree.go +++ b/services/repository/files/tree.go @@ -88,11 +88,7 @@ func GetTreeBySHA(ctx context.Context, repo *repo_model.Repository, gitRepo *git if len(entries) > perPage { tree.Truncated = true } - if rangeStart+perPage < len(entries) { - rangeEnd = rangeStart + perPage - } else { - rangeEnd = len(entries) - } + rangeEnd = min(rangeStart+perPage, len(entries)) tree.Entries = make([]api.GitEntry, rangeEnd-rangeStart) for e := rangeStart; e < rangeEnd; e++ { i := e - rangeStart diff --git a/services/repository/files/update.go b/services/repository/files/update.go index a707ea8bb6f08..f676dfd56190f 100644 --- a/services/repository/files/update.go +++ b/services/repository/files/update.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "path" + "slices" "strings" "time" @@ -196,13 +197,7 @@ func ChangeRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use } // Find the file we want to delete in the index - inFilelist := false - for _, indexFile := range filesInIndex { - if indexFile == file.TreePath { - inFilelist = true - break - } - } + inFilelist := slices.Contains(filesInIndex, file.TreePath) if !inFilelist { return nil, ErrRepoFileDoesNotExist{ Path: file.TreePath, @@ -459,11 +454,9 @@ func CreateOrUpdateFile(ctx context.Context, t *TemporaryUploadRepository, file } // If is a new file (not updating) then the given path shouldn't exist if file.Operation == "create" { - for _, indexFile := range filesInIndex { - if indexFile == file.TreePath { - return ErrRepoFileAlreadyExists{ - Path: file.TreePath, - } + if slices.Contains(filesInIndex, file.TreePath) { + return ErrRepoFileAlreadyExists{ + Path: file.TreePath, } } } diff --git a/services/repository/gitgraph/graph_test.go b/services/repository/gitgraph/graph_test.go index 4c48b94aa20ae..81ef54741ca74 100644 --- a/services/repository/gitgraph/graph_test.go +++ b/services/repository/gitgraph/graph_test.go @@ -6,6 +6,7 @@ package gitgraph import ( "bytes" "fmt" + "slices" "strings" "testing" @@ -108,7 +109,7 @@ func TestReleaseUnusedColors(t *testing.T) { for _, testcase := range testcases { parser := &Parser{} parser.Reset() - parser.availableColors = append([]int{}, testcase.availableColors...) + parser.availableColors = slices.Clone(testcase.availableColors) parser.oldColors = append(parser.oldColors, testcase.oldColors...) parser.firstAvailable = testcase.firstAvailable parser.firstInUse = testcase.firstInUse @@ -117,13 +118,7 @@ func TestReleaseUnusedColors(t *testing.T) { if parser.firstAvailable == -1 { // All in use for _, color := range parser.availableColors { - found := false - for _, oldColor := range parser.oldColors { - if oldColor == color { - found = true - break - } - } + found := slices.Contains(parser.oldColors, color) if !found { t.Errorf("In testcase:\n%d\t%d\t%d %d =>\n%d\t%d\t%d %d: %d should be available but is not", testcase.availableColors, @@ -141,13 +136,7 @@ func TestReleaseUnusedColors(t *testing.T) { // Some in use for i := parser.firstInUse; i != parser.firstAvailable; i = (i + 1) % len(parser.availableColors) { color := parser.availableColors[i] - found := false - for _, oldColor := range parser.oldColors { - if oldColor == color { - found = true - break - } - } + found := slices.Contains(parser.oldColors, color) if !found { t.Errorf("In testcase:\n%d\t%d\t%d %d =>\n%d\t%d\t%d %d: %d should be available but is not", testcase.availableColors, @@ -163,13 +152,7 @@ func TestReleaseUnusedColors(t *testing.T) { } for i := parser.firstAvailable; i != parser.firstInUse; i = (i + 1) % len(parser.availableColors) { color := parser.availableColors[i] - found := false - for _, oldColor := range parser.oldColors { - if oldColor == color { - found = true - break - } - } + found := slices.Contains(parser.oldColors, color) if found { t.Errorf("In testcase:\n%d\t%d\t%d %d =>\n%d\t%d\t%d %d: %d should not be available but is", testcase.availableColors, diff --git a/services/repository/push.go b/services/repository/push.go index 0ea51f9c072d2..e9e640b3933f7 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -243,7 +243,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { log.Error("unable to GetCommit %s from %-v: %v", oldCommitID, repo, err) } if oldCommit != nil { - for i := 0; i < oldCommit.ParentCount(); i++ { + for i := range oldCommit.ParentCount() { commitID, _ := oldCommit.ParentID(i) if !commitID.IsZero() { oldCommitID = commitID.String() diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index e8b89f5e97b3f..60bc360b9b28d 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -116,9 +116,9 @@ func TestGitPathToWebPath(t *testing.T) { func TestUserWebGitPathConsistency(t *testing.T) { maxLen := 20 b := make([]byte, maxLen) - for i := 0; i < 1000; i++ { + for range 1000 { l := rand.Intn(maxLen) - for j := 0; j < l; j++ { + for j := range l { r := rand.Intn(0x80-0x20) + 0x20 b[j] = byte(r) } diff --git a/tests/integration/actions_job_test.go b/tests/integration/actions_job_test.go index a967adb417c0b..81c80e3274dbc 100644 --- a/tests/integration/actions_job_test.go +++ b/tests/integration/actions_job_test.go @@ -141,7 +141,7 @@ jobs: fileResp := createWorkflowFile(t, token, user2.Name, apiRepo.Name, tc.treePath, opts) // fetch and execute task - for i := 0; i < len(tc.outcomes); i++ { + for range len(tc.outcomes) { task := runner.fetchTask(t) jobName := getTaskJobNameByTaskID(t, token, user2.Name, apiRepo.Name, task.Id) outcome := tc.outcomes[jobName] @@ -325,7 +325,7 @@ jobs: opts := getWorkflowCreateFileOptions(user2, apiRepo.DefaultBranch, fmt.Sprintf("create %s", tc.treePath), tc.fileContent) createWorkflowFile(t, token, user2.Name, apiRepo.Name, tc.treePath, opts) - for i := 0; i < len(tc.outcomes); i++ { + for range len(tc.outcomes) { task := runner.fetchTask(t) jobName := getTaskJobNameByTaskID(t, token, user2.Name, apiRepo.Name, task.Id) outcome := tc.outcomes[jobName] diff --git a/tests/integration/api_helper_for_declarative_test.go b/tests/integration/api_helper_for_declarative_test.go index 96669b46f02d1..e05eb19ab14eb 100644 --- a/tests/integration/api_helper_for_declarative_test.go +++ b/tests/integration/api_helper_for_declarative_test.go @@ -259,7 +259,7 @@ func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64) var req *RequestWrapper var resp *httptest.ResponseRecorder - for i := 0; i < 6; i++ { + for range 6 { req = NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{ MergeMessageField: "doAPIMergePullRequest Merge", Do: string(repo_model.MergeStyleMerge), diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index d8394a33d96f4..97972a15711a3 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -166,7 +166,7 @@ func TestAPICreateIssueParallel(t *testing.T) { urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues", owner.Name, repoBefore.Name) var wg sync.WaitGroup - for i := 0; i < 10; i++ { + for i := range 10 { wg.Add(1) go func(parentT *testing.T, i int) { parentT.Run(fmt.Sprintf("ParallelCreateIssue_%d", i), func(t *testing.T) { @@ -267,10 +267,7 @@ func TestAPISearchIssues(t *testing.T) { defer tests.PrepareTestEnv(t)() // as this API was used in the frontend, it uses UI page size - expectedIssueCount := 20 // from the fixtures - if expectedIssueCount > setting.UI.IssuePagingNum { - expectedIssueCount = setting.UI.IssuePagingNum - } + expectedIssueCount := min(20, setting.UI.IssuePagingNum) link, _ := url.Parse("/api/v1/repos/issues/search") token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue) @@ -371,10 +368,7 @@ func TestAPISearchIssuesWithLabels(t *testing.T) { defer tests.PrepareTestEnv(t)() // as this API was used in the frontend, it uses UI page size - expectedIssueCount := 20 // from the fixtures - if expectedIssueCount > setting.UI.IssuePagingNum { - expectedIssueCount = setting.UI.IssuePagingNum - } + expectedIssueCount := min(20, setting.UI.IssuePagingNum) link, _ := url.Parse("/api/v1/repos/issues/search") token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue) diff --git a/tests/integration/api_packages_chef_test.go b/tests/integration/api_packages_chef_test.go index 6efb2708afd51..9f5418832eba4 100644 --- a/tests/integration/api_packages_chef_test.go +++ b/tests/integration/api_packages_chef_test.go @@ -181,7 +181,7 @@ nwIDAQAB var data []byte if version == "1.3" { - data = []byte(fmt.Sprintf( + data = fmt.Appendf(nil, "Method:%s\nPath:%s\nX-Ops-Content-Hash:%s\nX-Ops-Sign:version=%s\nX-Ops-Timestamp:%s\nX-Ops-UserId:%s\nX-Ops-Server-API-Version:%s", req.Method, path.Clean(req.URL.Path), @@ -190,17 +190,17 @@ nwIDAQAB req.Header.Get("X-Ops-Timestamp"), username, req.Header.Get("X-Ops-Server-Api-Version"), - )) + ) } else { sum := sha1.Sum([]byte(path.Clean(req.URL.Path))) - data = []byte(fmt.Sprintf( + data = fmt.Appendf(nil, "Method:%s\nHashed Path:%s\nX-Ops-Content-Hash:%s\nX-Ops-Timestamp:%s\nX-Ops-UserId:%s", req.Method, base64.StdEncoding.EncodeToString(sum[:]), req.Header.Get("X-Ops-Content-Hash"), req.Header.Get("X-Ops-Timestamp"), username, - )) + ) } for k := range req.Header { diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index 3905ad1b70368..727822706d2cb 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -731,7 +731,7 @@ func TestPackageContainer(t *testing.T) { url := fmt.Sprintf("%sv2/%s/parallel", setting.AppURL, user.Name) var wg sync.WaitGroup - for i := 0; i < 10; i++ { + for i := range 10 { wg.Add(1) content := []byte{byte(i)} diff --git a/tests/integration/api_packages_debian_test.go b/tests/integration/api_packages_debian_test.go index 98027d774c08f..3ae60d2aa2f6d 100644 --- a/tests/integration/api_packages_debian_test.go +++ b/tests/integration/api_packages_debian_test.go @@ -284,7 +284,7 @@ func TestPackageDebian(t *testing.T) { // because "Iterate" keeps a dangling SQL session but the callback function still uses the same session to execute statements. // The "Iterate" problem has been checked by TestContextSafety now, so here we only need to check the cleanup logic with a small number packagesCount := 2 - for i := 0; i < packagesCount; i++ { + for i := range packagesCount { uploadURL := fmt.Sprintf("%s/pool/%s/%s/upload", rootURL, "test", "main") req := NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, "1.0."+strconv.Itoa(i), "all")).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) diff --git a/tests/integration/api_packages_maven_test.go b/tests/integration/api_packages_maven_test.go index 408c8805c2412..30ef1884cd38c 100644 --- a/tests/integration/api_packages_maven_test.go +++ b/tests/integration/api_packages_maven_test.go @@ -321,7 +321,7 @@ func TestPackageMavenConcurrent(t *testing.T) { defer tests.PrintCurrentTest(t)() var wg sync.WaitGroup - for i := 0; i < 10; i++ { + for i := range 10 { wg.Add(1) go func(i int) { putFile(t, fmt.Sprintf("/%s/%s.jar", packageVersion, strconv.Itoa(i)), "test", http.StatusCreated) diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index 2bf4a81280ef5..c4375d5ecfc74 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -114,7 +114,7 @@ func BenchmarkAPICreateFileSmall(b *testing.B) { repo1 := unittest.AssertExistsAndLoadBean(b, &repo_model.Repository{ID: 1}) // public repo b.ResetTimer() - for n := 0; n < b.N; n++ { + for n := 0; b.Loop(); n++ { treePath := fmt.Sprintf("update/file%d.txt", n) _, _ = createFileInBranch(user2, repo1, treePath, repo1.DefaultBranch, treePath) } @@ -129,7 +129,7 @@ func BenchmarkAPICreateFileMedium(b *testing.B) { repo1 := unittest.AssertExistsAndLoadBean(b, &repo_model.Repository{ID: 1}) // public repo b.ResetTimer() - for n := 0; n < b.N; n++ { + for n := 0; b.Loop(); n++ { treePath := fmt.Sprintf("update/file%d.txt", n) copy(data, treePath) _, _ = createFileInBranch(user2, repo1, treePath, repo1.DefaultBranch, treePath) diff --git a/tests/integration/auth_ldap_test.go b/tests/integration/auth_ldap_test.go index c00e88b88b4f8..86b4c11013a48 100644 --- a/tests/integration/auth_ldap_test.go +++ b/tests/integration/auth_ldap_test.go @@ -408,7 +408,7 @@ func TestLDAPUserSSHKeySync(t *testing.T) { divs := htmlDoc.doc.Find("#keys-ssh .flex-item .flex-item-body:not(:last-child)") syncedKeys := make([]string, divs.Length()) - for i := 0; i < divs.Length(); i++ { + for i := range divs.Length() { syncedKeys[i] = strings.TrimSpace(divs.Eq(i).Text()) } diff --git a/tests/integration/compare_test.go b/tests/integration/compare_test.go index cbf927813e102..871bcafed17a7 100644 --- a/tests/integration/compare_test.go +++ b/tests/integration/compare_test.go @@ -152,7 +152,7 @@ func TestCompareCodeExpand(t *testing.T) { // all the links in the comparison should be to the forked repo&branch assert.NotZero(t, els.Length()) - for i := 0; i < els.Length(); i++ { + for i := range els.Length() { link := els.Eq(i).AttrOr("hx-get", "") assert.True(t, strings.HasPrefix(link, "/user2/test_blob_excerpt-fork/blob_excerpt/")) } diff --git a/tests/integration/dump_restore_test.go b/tests/integration/dump_restore_test.go index 54683becaa736..b6b4d67b59099 100644 --- a/tests/integration/dump_restore_test.go +++ b/tests/integration/dump_restore_test.go @@ -267,7 +267,7 @@ func (c *compareDump) assertEqual(filename string, kind any, fields compareField func (c *compareDump) assertEqualSlices(before, after reflect.Value, fields compareFields) any { assert.EqualValues(c.t, before.Len(), after.Len()) if before.Len() == after.Len() { - for i := 0; i < before.Len(); i++ { + for i := range before.Len() { _ = c.assertEqualValues( reflect.Indirect(before.Index(i).Elem()), reflect.Indirect(after.Index(i).Elem()), diff --git a/tests/integration/git_helper_for_declarative_test.go b/tests/integration/git_helper_for_declarative_test.go index 9f51f15149d82..f38275dbf2070 100644 --- a/tests/integration/git_helper_for_declarative_test.go +++ b/tests/integration/git_helper_for_declarative_test.go @@ -124,7 +124,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) { // forcibly set default branch to master _, _, err := git.NewCommand(git.DefaultContext, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunStdString(&git.RunOpts{Dir: dstPath}) assert.NoError(t, err) - assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644)) + assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), fmt.Appendf(nil, "# Testing Repository\n\nOriginally created in: %s", dstPath), 0o644)) assert.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@example.com", @@ -164,7 +164,7 @@ func doGitAddSomeCommits(dstPath, branch string) func(*testing.T) { return func(t *testing.T) { doGitCheckoutBranch(dstPath, branch)(t) - assert.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), []byte(fmt.Sprintf("file %s", branch)), 0o644)) + assert.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), fmt.Appendf(nil, "file %s", branch), 0o644)) assert.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@test.test", diff --git a/tests/integration/git_push_test.go b/tests/integration/git_push_test.go index e68f8bfce2d87..f28608545495b 100644 --- a/tests/integration/git_push_test.go +++ b/tests/integration/git_push_test.go @@ -27,7 +27,7 @@ func TestGitPush(t *testing.T) { func testGitPush(t *testing.T, u *url.URL) { t.Run("Push branches at once", func(t *testing.T) { runTestGitPush(t, u, func(t *testing.T, gitPath string) (pushed, deleted []string) { - for i := 0; i < 100; i++ { + for i := range 100 { branchName := fmt.Sprintf("branch-%d", i) pushed = append(pushed, branchName) doGitCreateBranch(gitPath, branchName)(t) @@ -40,7 +40,7 @@ func testGitPush(t *testing.T, u *url.URL) { t.Run("Push branches exists", func(t *testing.T) { runTestGitPush(t, u, func(t *testing.T, gitPath string) (pushed, deleted []string) { - for i := 0; i < 10; i++ { + for i := range 10 { branchName := fmt.Sprintf("branch-%d", i) if i < 5 { pushed = append(pushed, branchName) @@ -54,7 +54,7 @@ func testGitPush(t *testing.T, u *url.URL) { pushed = pushed[:0] // do some changes for the first 5 branches created above - for i := 0; i < 5; i++ { + for i := range 5 { branchName := fmt.Sprintf("branch-%d", i) pushed = append(pushed, branchName) @@ -75,7 +75,7 @@ func testGitPush(t *testing.T, u *url.URL) { t.Run("Push branches one by one", func(t *testing.T) { runTestGitPush(t, u, func(t *testing.T, gitPath string) (pushed, deleted []string) { - for i := 0; i < 100; i++ { + for i := range 100 { branchName := fmt.Sprintf("branch-%d", i) doGitCreateBranch(gitPath, branchName)(t) doGitPushTestRepository(gitPath, "origin", branchName)(t) @@ -101,14 +101,14 @@ func testGitPush(t *testing.T, u *url.URL) { doGitPushTestRepository(gitPath, "origin", "master")(t) // make sure master is the default branch instead of a branch we are going to delete pushed = append(pushed, "master") - for i := 0; i < 100; i++ { + for i := range 100 { branchName := fmt.Sprintf("branch-%d", i) pushed = append(pushed, branchName) doGitCreateBranch(gitPath, branchName)(t) } doGitPushTestRepository(gitPath, "origin", "--all")(t) - for i := 0; i < 10; i++ { + for i := range 10 { branchName := fmt.Sprintf("branch-%d", i) doGitPushTestRepository(gitPath, "origin", "--delete", branchName)(t) deleted = append(deleted, branchName) diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go index 31695fb2e18cd..defa6ae9496d4 100644 --- a/tests/integration/gpg_git_test.go +++ b/tests/integration/gpg_git_test.go @@ -273,7 +273,7 @@ func crudActionCreateFile(_ *testing.T, ctx APITestContext, user *user_model.Use Email: user.Email, }, }, - ContentBase64: base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("This is new text for %s", path))), + ContentBase64: base64.StdEncoding.EncodeToString(fmt.Appendf(nil, "This is new text for %s", path)), }, callback...) } diff --git a/tests/integration/issue_test.go b/tests/integration/issue_test.go index dc0c9b135017d..3183b42506dcf 100644 --- a/tests/integration/issue_test.go +++ b/tests/integration/issue_test.go @@ -76,14 +76,11 @@ func TestViewIssuesSortByType(t *testing.T) { htmlDoc := NewHTMLParser(t, resp.Body) issuesSelection := getIssuesSelection(t, htmlDoc) - expectedNumIssues := unittest.GetCount(t, + expectedNumIssues := min(unittest.GetCount(t, &issues_model.Issue{RepoID: repo.ID, PosterID: user.ID}, unittest.Cond("is_closed=?", false), unittest.Cond("is_pull=?", false), - ) - if expectedNumIssues > setting.UI.IssuePagingNum { - expectedNumIssues = setting.UI.IssuePagingNum - } + ), setting.UI.IssuePagingNum) assert.EqualValues(t, expectedNumIssues, issuesSelection.Length()) issuesSelection.Each(func(_ int, selection *goquery.Selection) { @@ -473,10 +470,7 @@ func TestSearchIssues(t *testing.T) { session := loginUser(t, "user2") - expectedIssueCount := 20 // from the fixtures - if expectedIssueCount > setting.UI.IssuePagingNum { - expectedIssueCount = setting.UI.IssuePagingNum - } + expectedIssueCount := min(20, setting.UI.IssuePagingNum) link, _ := url.Parse("/issues/search") req := NewRequest(t, "GET", link.String()) @@ -567,10 +561,7 @@ func TestSearchIssues(t *testing.T) { func TestSearchIssuesWithLabels(t *testing.T) { defer tests.PrepareTestEnv(t)() - expectedIssueCount := 20 // from the fixtures - if expectedIssueCount > setting.UI.IssuePagingNum { - expectedIssueCount = setting.UI.IssuePagingNum - } + expectedIssueCount := min(20, setting.UI.IssuePagingNum) session := loginUser(t, "user1") link, _ := url.Parse("/issues/search") diff --git a/tests/integration/org_test.go b/tests/integration/org_test.go index ef4ef2bb9b429..ea89a51bd58e1 100644 --- a/tests/integration/org_test.go +++ b/tests/integration/org_test.go @@ -40,7 +40,7 @@ func TestOrgRepos(t *testing.T) { sel := htmlDoc.doc.Find("a.name") assert.Len(t, repos, len(sel.Nodes)) - for i := 0; i < len(repos); i++ { + for i := range repos { assert.EqualValues(t, repos[i], strings.TrimSpace(sel.Eq(i).Text())) } } diff --git a/tests/integration/project_test.go b/tests/integration/project_test.go index 111356b1da220..c9f966f9fc89a 100644 --- a/tests/integration/project_test.go +++ b/tests/integration/project_test.go @@ -47,7 +47,7 @@ func TestMoveRepoProjectColumns(t *testing.T) { err := project_model.NewProject(db.DefaultContext, &project1) assert.NoError(t, err) - for i := 0; i < 3; i++ { + for i := range 3 { err = project_model.NewColumn(db.DefaultContext, &project_model.Column{ Title: fmt.Sprintf("column %d", i+1), ProjectID: project1.ID, diff --git a/tests/integration/release_test.go b/tests/integration/release_test.go index 1a7f9e38b5173..b6ea177466adc 100644 --- a/tests/integration/release_test.go +++ b/tests/integration/release_test.go @@ -118,7 +118,7 @@ func TestCreateReleasePaging(t *testing.T) { session := loginUser(t, "user2") // Create enough releases to have paging - for i := 0; i < 12; i++ { + for i := range 12 { version := fmt.Sprintf("v0.0.%d", i) createNewRelease(t, session, "/user2/repo1", version, version, false, false) } diff --git a/tests/integration/repo_commits_test.go b/tests/integration/repo_commits_test.go index fbe215eb859d0..eb5efb8237d88 100644 --- a/tests/integration/repo_commits_test.go +++ b/tests/integration/repo_commits_test.go @@ -186,7 +186,7 @@ func TestRepoCommitsStatusParallel(t *testing.T) { assert.NotEmpty(t, commitURL) var wg sync.WaitGroup - for i := 0; i < 10; i++ { + for i := range 10 { wg.Add(1) go func(parentT *testing.T, i int) { parentT.Run(fmt.Sprintf("ParallelCreateStatus_%d", i), func(t *testing.T) { diff --git a/tests/integration/ssh_key_test.go b/tests/integration/ssh_key_test.go index eb3a3e926aa8e..833b211d5bf7d 100644 --- a/tests/integration/ssh_key_test.go +++ b/tests/integration/ssh_key_test.go @@ -27,7 +27,7 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testin func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) { return func(t *testing.T) { - assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0o644)) + assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), fmt.Appendf(nil, "# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now()), 0o644)) assert.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@example.com", diff --git a/tools/lint-go-gopls.sh b/tools/lint-go-gopls.sh index a222ea14d7e17..c47774d47cced 100755 --- a/tools/lint-go-gopls.sh +++ b/tools/lint-go-gopls.sh @@ -11,7 +11,9 @@ IGNORE_PATTERNS=( # current absolute path, indicating a error was found. This is necessary # because the tool does not set non-zero exit code when errors are found. # ref: https://github.com/golang/go/issues/67078 -ERROR_LINES=$("$GO" run "$GOPLS_PACKAGE" check "$@" 2>/dev/null | grep -E "^$PWD" | grep -vFf <(printf '%s\n' "${IGNORE_PATTERNS[@]}")); +ERROR_LINES="$("$GO" run "$GOPLS_PACKAGE" check "$@" 2>/dev/null | grep -E "^$PWD" | grep -vFf <(printf '%s\n' "${IGNORE_PATTERNS[@]}"))"; +ERROR_LINES="${ERROR_LINES}$("$GO" run "$GOPLS_MODERNIZE_PACKAGE" -fix ./...)" + NUM_ERRORS=$(echo -n "$ERROR_LINES" | wc -l) if [ "$NUM_ERRORS" -eq "0" ]; then From a15d4fd26f3ef00f9f99d37902b167c45f4dad3d Mon Sep 17 00:00:00 2001 From: silverwind Date: Thu, 27 Feb 2025 16:35:34 +0100 Subject: [PATCH 2/4] revert fmt changes --- Makefile | 4 +--- tools/lint-go-gopls.sh | 1 - 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/Makefile b/Makefile index f1aa695767fdd..3f896f716a768 100644 --- a/Makefile +++ b/Makefile @@ -37,7 +37,6 @@ GO_LICENSES_PACKAGE ?= github.com/google/go-licenses@v1 GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@v1 ACTIONLINT_PACKAGE ?= github.com/rhysd/actionlint/cmd/actionlint@v1 GOPLS_PACKAGE ?= golang.org/x/tools/gopls@v0.18.1 -GOPLS_MODERNIZE_PACKAGE ?= golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@v0.18.1 DOCKER_IMAGE ?= gitea/gitea DOCKER_TAG ?= latest @@ -248,7 +247,6 @@ fmt: ## format the Go code -e 's/{{[ ]\{1,\}/{{/g' -e '/^[ ]\{1,\}}}/! s/[ ]\{1,\}}}/}}/g' \ -e 's/([ ]\{1,\}/(/g' -e '/^[ ]\{1,\})/! s/[ ]\{1,\})/)/g' \ $(TEMPLATES) - @$(GO) run $(GOPLS_MODERNIZE_PACKAGE) -fix ./... .PHONY: fmt-check fmt-check: fmt @@ -376,7 +374,7 @@ lint-go-vet: ## lint go files with vet .PHONY: lint-go-gopls lint-go-gopls: ## lint go files with gopls @echo "Running gopls..." - @GO=$(GO) GOPLS_PACKAGE=$(GOPLS_PACKAGE) GOPLS_MODERNIZE_PACKAGE=$(GOPLS_MODERNIZE_PACKAGE) tools/lint-go-gopls.sh $(GO_SOURCES_NO_BINDATA) + @GO=$(GO) GOPLS_PACKAGE=$(GOPLS_PACKAGE) tools/lint-go-gopls.sh $(GO_SOURCES_NO_BINDATA) .PHONY: lint-editorconfig lint-editorconfig: diff --git a/tools/lint-go-gopls.sh b/tools/lint-go-gopls.sh index c47774d47cced..dae6843dc8924 100755 --- a/tools/lint-go-gopls.sh +++ b/tools/lint-go-gopls.sh @@ -12,7 +12,6 @@ IGNORE_PATTERNS=( # because the tool does not set non-zero exit code when errors are found. # ref: https://github.com/golang/go/issues/67078 ERROR_LINES="$("$GO" run "$GOPLS_PACKAGE" check "$@" 2>/dev/null | grep -E "^$PWD" | grep -vFf <(printf '%s\n' "${IGNORE_PATTERNS[@]}"))"; -ERROR_LINES="${ERROR_LINES}$("$GO" run "$GOPLS_MODERNIZE_PACKAGE" -fix ./...)" NUM_ERRORS=$(echo -n "$ERROR_LINES" | wc -l) From 421e47ca22b1250c5c865ecdf079599d4a1ea05e Mon Sep 17 00:00:00 2001 From: silverwind Date: Thu, 27 Feb 2025 16:36:12 +0100 Subject: [PATCH 3/4] revert Makefile --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 3f896f716a768..0acc8a1858d0d 100644 --- a/Makefile +++ b/Makefile @@ -36,7 +36,7 @@ XGO_PACKAGE ?= src.techknowlogick.com/xgo@latest GO_LICENSES_PACKAGE ?= github.com/google/go-licenses@v1 GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@v1 ACTIONLINT_PACKAGE ?= github.com/rhysd/actionlint/cmd/actionlint@v1 -GOPLS_PACKAGE ?= golang.org/x/tools/gopls@v0.18.1 +GOPLS_PACKAGE ?= golang.org/x/tools/gopls@v0.17.1 DOCKER_IMAGE ?= gitea/gitea DOCKER_TAG ?= latest @@ -372,7 +372,7 @@ lint-go-vet: ## lint go files with vet @$(GO) vet -vettool=gitea-vet ./... .PHONY: lint-go-gopls -lint-go-gopls: ## lint go files with gopls +lint-go-gopls: ## lint go files with gopls check @echo "Running gopls..." @GO=$(GO) GOPLS_PACKAGE=$(GOPLS_PACKAGE) tools/lint-go-gopls.sh $(GO_SOURCES_NO_BINDATA) From f611eb3dce2257104855d897f99d6038db032543 Mon Sep 17 00:00:00 2001 From: silverwind Date: Thu, 27 Feb 2025 16:36:47 +0100 Subject: [PATCH 4/4] revert Makefile --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 0acc8a1858d0d..e38fb801c318a 100644 --- a/Makefile +++ b/Makefile @@ -372,8 +372,8 @@ lint-go-vet: ## lint go files with vet @$(GO) vet -vettool=gitea-vet ./... .PHONY: lint-go-gopls -lint-go-gopls: ## lint go files with gopls check - @echo "Running gopls..." +lint-go-gopls: ## lint go files with gopls + @echo "Running gopls check..." @GO=$(GO) GOPLS_PACKAGE=$(GOPLS_PACKAGE) tools/lint-go-gopls.sh $(GO_SOURCES_NO_BINDATA) .PHONY: lint-editorconfig