From fd8907175f03da7be918035b4c4c93c3410bb768 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Sat, 20 Mar 2021 09:39:40 +0800 Subject: [PATCH 1/2] refactor: update format --- cmd/admin.go | 7 +- cmd/admin_auth_ldap_test.go | 16 +-- cmd/cert.go | 2 +- cmd/doctor.go | 2 - cmd/dump.go | 6 +- cmd/dump_repo.go | 2 +- cmd/embedded.go | 13 +- cmd/manager.go | 3 +- cmd/restore_repo.go | 2 +- cmd/serv.go | 2 +- cmd/web.go | 3 +- cmd/web_letsencrypt.go | 3 +- contrib/fixtures/fixture_generation.go | 2 +- contrib/pr/checkout.go | 35 +++--- integrations/api_admin_org_test.go | 6 +- integrations/api_branch_test.go | 1 - integrations/api_comment_test.go | 6 +- integrations/api_gpg_keys_test.go | 36 +++--- integrations/api_issue_label_test.go | 18 ++- integrations/api_issue_reaction_test.go | 20 ++-- integrations/api_issue_subscription_test.go | 1 - integrations/api_issue_test.go | 3 +- integrations/api_issue_tracked_time_test.go | 10 +- integrations/api_notification_test.go | 6 +- integrations/api_org_test.go | 8 +- integrations/api_pull_review_test.go | 33 +++--- integrations/api_repo_edit_test.go | 6 +- integrations/api_repo_lfs_locks_test.go | 14 +-- integrations/api_repo_test.go | 111 +++++++++++------- integrations/api_repo_topic_test.go | 1 - integrations/api_team_test.go | 1 - integrations/api_user_orgs_test.go | 2 +- integrations/attachment_test.go | 8 +- integrations/benchmarks_test.go | 8 +- integrations/cmd_keys_test.go | 7 +- integrations/editor_test.go | 1 - integrations/eventsource_test.go | 2 +- .../git_helper_for_declarative_test.go | 11 +- integrations/git_test.go | 21 ++-- integrations/gpg_git_test.go | 4 +- integrations/integration_test.go | 2 +- integrations/issue_test.go | 22 ++-- integrations/links_test.go | 10 +- integrations/migration-test/migration_test.go | 1 - integrations/nonascii_branches_test.go | 1 - integrations/privateactivity_test.go | 6 +- integrations/pull_merge_test.go | 8 +- integrations/pull_update_test.go | 12 +- integrations/repo_activity_test.go | 1 - integrations/repo_commits_test.go | 4 +- integrations/repofiles_update_test.go | 2 +- integrations/setting_test.go | 1 - integrations/ssh_key_test.go | 4 +- integrations/testlogger.go | 2 +- integrations/timetracking_test.go | 5 +- integrations/user_test.go | 10 +- main.go | 2 +- models/consistency.go | 1 - modules/auth/ldap/ldap.go | 4 +- modules/auth/oauth2/oauth2.go | 3 +- modules/auth/openid/discovery_cache_test.go | 4 +- modules/auth/openid/openid.go | 6 +- modules/auth/pam/pam.go | 1 - modules/auth/sso/basic.go | 3 +- modules/auth/sso/oauth2.go | 3 +- modules/auth/sso/reverseproxy.go | 3 +- modules/auth/sso/session.go | 3 +- modules/avatar/avatar_test.go | 1 + modules/base/tool.go | 10 +- modules/cache/cache.go | 4 +- modules/cache/cache_test.go | 1 + modules/charset/charset_test.go | 102 ++++++++++------ modules/context/api.go | 25 ++-- modules/context/api_test.go | 2 +- modules/context/captcha.go | 6 +- modules/context/context.go | 18 +-- modules/context/csrf.go | 4 +- modules/context/pagination.go | 6 +- modules/context/private.go | 4 +- modules/context/repo.go | 5 +- modules/context/response.go | 4 +- modules/context/secret.go | 4 +- modules/convert/git_commit.go | 1 - modules/convert/notification.go | 6 +- modules/convert/pull_test.go | 4 +- modules/convert/repository.go | 2 +- modules/convert/status.go | 1 - modules/convert/user_test.go | 1 - modules/cron/cron.go | 1 - modules/cron/tasks.go | 10 +- modules/doctor/misc.go | 1 - modules/doctor/paths.go | 2 +- modules/emoji/emoji.go | 3 - modules/eventsource/event.go | 2 +- modules/forms/repo_form_test.go | 2 - modules/git/batch_reader.go | 1 - modules/git/command_test.go | 2 - modules/git/commit.go | 2 +- modules/git/commit_info_gogit.go | 2 +- modules/git/commit_info_nogogit.go | 2 +- modules/git/commit_info_test.go | 6 +- modules/git/hook.go | 8 +- modules/git/last_commit_cache_gogit.go | 1 - modules/git/parse_nogogit_test.go | 1 - modules/git/repo.go | 4 +- modules/git/repo_attribute.go | 2 +- modules/git/repo_commit.go | 5 +- modules/git/repo_compare.go | 2 +- modules/git/repo_language_stats.go | 6 +- modules/git/repo_object.go | 1 - modules/git/repo_tag.go | 2 +- modules/git/repo_tree.go | 2 +- modules/git/submodule_test.go | 2 +- modules/git/tag.go | 6 +- modules/git/tree_blob_gogit.go | 2 +- modules/git/tree_entry_mode.go | 10 +- modules/git/utils.go | 2 +- modules/gitgraph/graph.go | 2 +- modules/gitgraph/graph_test.go | 2 - modules/gitgraph/parser.go | 1 - modules/graceful/manager.go | 1 + modules/highlight/highlight.go | 6 +- modules/httplib/httplib.go | 12 +- modules/indexer/code/bleve.go | 12 +- modules/indexer/code/elastic_search.go | 10 +- modules/indexer/code/git.go | 2 +- modules/indexer/code/indexer.go | 4 +- modules/indexer/code/indexer_test.go | 78 ++++++------ modules/indexer/code/wrapped.go | 5 +- modules/indexer/issues/bleve.go | 6 +- modules/indexer/issues/bleve_test.go | 62 +++++----- modules/indexer/issues/db.go | 5 +- modules/indexer/issues/elastic_search.go | 8 +- modules/indexer/issues/indexer_test.go | 1 - modules/indexer/stats/db.go | 3 +- modules/lfs/locks.go | 8 +- modules/lfs/server.go | 3 +- modules/log/colors.go | 11 +- modules/log/conn_test.go | 3 +- modules/log/file.go | 7 +- modules/log/file_test.go | 15 ++- modules/log/log_test.go | 1 - modules/log/logger.go | 1 - modules/log/multichannel.go | 2 +- modules/log/stack.go | 4 +- modules/log/writer.go | 4 +- modules/log/writer_test.go | 1 - modules/markup/common/footnote.go | 9 +- modules/markup/common/html.go | 14 +-- modules/markup/common/linkify.go | 16 +-- modules/markup/csv/csv.go | 4 +- modules/markup/csv/csv_test.go | 2 +- modules/markup/html.go | 9 +- modules/markup/html_internal_test.go | 8 +- modules/markup/html_test.go | 16 +-- modules/markup/markdown/goldmark.go | 4 +- modules/markup/markdown/markdown.go | 21 ++-- modules/markup/markdown/markdown_test.go | 9 +- modules/markup/markup.go | 2 +- modules/markup/mdstripper/mdstripper.go | 9 +- modules/markup/mdstripper/mdstripper_test.go | 3 +- modules/markup/orgmode/orgmode.go | 5 +- modules/markup/orgmode/orgmode_test.go | 8 +- modules/markup/sanitizer.go | 3 +- modules/metrics/collector.go | 1 - modules/migrations/base/null_downloader.go | 7 +- modules/migrations/base/retry_downloader.go | 4 +- modules/migrations/dump.go | 12 +- modules/migrations/error.go | 6 +- modules/migrations/git.go | 4 +- modules/migrations/gitea_downloader.go | 21 ++-- modules/migrations/gitea_uploader.go | 42 ++++--- modules/migrations/github.go | 36 +++--- modules/migrations/github_test.go | 20 ++-- modules/migrations/gitlab.go | 45 ++++--- modules/migrations/gitlab_test.go | 7 +- modules/migrations/gogs.go | 19 ++- modules/migrations/gogs_test.go | 6 +- modules/migrations/migrate.go | 12 +- modules/migrations/restore.go | 20 ++-- modules/nosql/redis.go | 1 - modules/notification/action/action.go | 8 +- modules/notification/base/notifier.go | 6 +- modules/notification/base/null.go | 13 +- modules/notification/indexer/indexer.go | 6 +- modules/notification/mail/mail.go | 4 +- modules/notification/notification.go | 10 +- modules/notification/ui/ui.go | 20 ++-- modules/notification/webhook/webhook.go | 11 +- modules/options/dynamic.go | 10 +- modules/options/static.go | 14 +-- modules/private/mail.go | 2 +- modules/private/manager.go | 1 - modules/private/serv.go | 1 - modules/process/manager_test.go | 2 - modules/public/public.go | 2 +- modules/public/public_test.go | 2 +- modules/public/static.go | 2 +- modules/queue/manager.go | 3 - modules/queue/queue.go | 5 +- modules/queue/queue_disk_channel_test.go | 1 - modules/queue/queue_wrapped.go | 2 +- modules/queue/workerpool.go | 3 +- modules/references/references.go | 7 +- modules/references/references_test.go | 1 - modules/repofiles/action.go | 1 - modules/repofiles/temp_repo.go | 6 +- modules/repository/generate.go | 4 +- modules/repository/hooks.go | 10 +- modules/repository/init.go | 6 +- modules/repository/repo.go | 4 +- modules/repository/update.go | 2 +- modules/secret/secret.go | 4 +- modules/session/db.go | 1 - modules/setting/attachment.go | 34 +++--- modules/setting/cache.go | 50 ++++---- modules/setting/cors.go | 28 ++--- modules/setting/cron_test.go | 2 - modules/setting/database.go | 2 +- modules/setting/git.go | 104 ++++++++-------- modules/setting/indexer.go | 78 ++++++------ modules/setting/indexer_test.go | 1 - modules/setting/lfs.go | 4 +- modules/setting/log.go | 14 ++- modules/setting/mailer.go | 6 +- modules/setting/markup.go | 2 +- modules/setting/migrations.go | 24 ++-- modules/setting/session.go | 52 ++++---- modules/setting/setting.go | 26 ++-- modules/setting/webhook.go | 38 +++--- modules/ssh/ssh.go | 7 +- modules/ssh/ssh_graceful.go | 1 - modules/storage/local.go | 4 +- modules/storage/minio.go | 4 +- modules/structs/hook.go | 6 +- modules/structs/repo.go | 18 ++- modules/task/task.go | 2 +- modules/templates/base.go | 2 +- modules/templates/dynamic.go | 2 - modules/templates/helper.go | 20 ++-- modules/templates/static.go | 6 +- modules/test/context_tests.go | 9 +- modules/timeutil/language.go | 12 +- modules/upload/upload.go | 8 +- modules/util/compare.go | 2 +- modules/util/paginate_test.go | 2 +- modules/util/path.go | 2 +- modules/util/sanitize_test.go | 2 +- modules/util/shellquote.go | 8 +- modules/util/util_test.go | 1 - modules/validation/binding.go | 11 +- modules/web/middleware/cookie.go | 2 +- modules/web/middleware/flash.go | 6 +- modules/web/middleware/locale.go | 2 +- modules/web/route.go | 32 ++--- routers/admin/admin.go | 2 +- routers/admin/admin_test.go | 2 +- routers/admin/emails.go | 5 +- routers/admin/users_test.go | 3 - routers/api/v1/admin/org.go | 2 +- routers/api/v1/admin/user.go | 2 +- routers/api/v1/api.go | 12 +- routers/api/v1/misc/markdown_test.go | 10 +- routers/api/v1/notify/repo.go | 2 +- routers/api/v1/org/hook.go | 4 +- routers/api/v1/org/org.go | 3 +- routers/api/v1/org/team.go | 5 +- routers/api/v1/repo/branch.go | 6 - routers/api/v1/repo/fork.go | 2 +- routers/api/v1/repo/issue.go | 2 +- routers/api/v1/repo/issue_reaction.go | 4 +- routers/api/v1/repo/issue_subscription.go | 4 +- routers/api/v1/repo/issue_tracked_time.go | 4 +- routers/api/v1/repo/migrate.go | 4 +- routers/api/v1/repo/milestone.go | 2 +- routers/api/v1/repo/pull.go | 1 - routers/api/v1/repo/pull_review.go | 1 - routers/api/v1/repo/release_attachment.go | 2 +- routers/api/v1/repo/repo.go | 6 +- routers/api/v1/repo/repo_test.go | 4 +- routers/api/v1/repo/status.go | 8 +- routers/api/v1/user/gpg_key.go | 10 +- routers/api/v1/user/watch.go | 1 - routers/home.go | 8 +- routers/install.go | 10 +- routers/org/home.go | 2 +- routers/org/members.go | 2 +- routers/org/teams.go | 8 +- routers/private/internal.go | 6 +- routers/private/manager_unix.go | 1 - routers/repo/attachment.go | 10 +- routers/repo/blame.go | 8 +- routers/repo/branch.go | 2 +- routers/repo/compare.go | 10 +- routers/repo/editor.go | 2 +- routers/repo/editor_test.go | 2 +- routers/repo/http.go | 5 +- routers/repo/issue.go | 11 +- routers/repo/issue_lock.go | 1 - routers/repo/issue_test.go | 4 +- routers/repo/lfs.go | 4 +- routers/repo/migrate.go | 2 +- routers/repo/projects.go | 8 +- routers/repo/pull.go | 23 ++-- routers/repo/settings_test.go | 5 - routers/repo/topic.go | 4 +- routers/repo/view.go | 6 +- routers/repo/wiki.go | 6 +- routers/repo/wiki_test.go | 6 +- routers/routes/base.go | 8 +- routers/routes/install.go | 4 +- routers/routes/web.go | 11 +- routers/user/auth.go | 8 +- routers/user/auth_openid.go | 4 +- routers/user/home.go | 15 ++- routers/user/oauth.go | 2 +- routers/user/profile.go | 3 +- routers/user/setting/account_test.go | 6 +- routers/user/setting/keys.go | 2 - services/archiver/archiver.go | 14 ++- services/gitdiff/gitdiff.go | 16 +-- services/gitdiff/gitdiff_test.go | 9 +- services/issue/assignee.go | 2 +- services/issue/issue.go | 4 +- services/issue/label_test.go | 4 +- services/mailer/mail.go | 1 - services/mailer/mail_issue.go | 1 - services/mailer/mail_test.go | 51 +++++--- services/mailer/mailer.go | 10 +- services/pull/commit_status.go | 2 +- services/pull/merge.go | 4 +- services/pull/review.go | 3 +- services/pull/temp_repo.go | 2 +- services/pull/update.go | 2 +- services/repository/push.go | 2 +- services/webhook/deliver.go | 4 +- services/webhook/deliver_test.go | 2 +- services/webhook/dingtalk.go | 9 +- services/webhook/discord.go | 4 +- services/webhook/feishu.go | 7 +- services/webhook/general.go | 4 +- services/webhook/matrix.go | 6 +- services/webhook/msteams.go | 4 +- services/webhook/slack.go | 6 +- services/webhook/telegram.go | 5 +- services/webhook/webhook.go | 62 +++++----- tools/fuzz.go | 2 +- 347 files changed, 1399 insertions(+), 1540 deletions(-) diff --git a/cmd/admin.go b/cmd/admin.go index 3ddf8eddf9e6c..b3dbe2c665873 100644 --- a/cmd/admin.go +++ b/cmd/admin.go @@ -404,7 +404,7 @@ func runCreateUser(c *cli.Context) error { } // always default to true - var changePassword = true + changePassword := true // If this is the first user being created. // Take it as the admin and don't force a password update. @@ -453,7 +453,6 @@ func runListUsers(c *cli.Context) error { } users, err := models.GetAllUsers() - if err != nil { return err } @@ -477,7 +476,6 @@ func runListUsers(c *cli.Context) error { w.Flush() return nil - } func runDeleteUser(c *cli.Context) error { @@ -668,7 +666,7 @@ func runUpdateOauth(c *cli.Context) error { } // update custom URL mapping - var customURLMapping = &oauth2.CustomURLMapping{} + customURLMapping := &oauth2.CustomURLMapping{} if oAuth2Config.CustomURLMapping != nil { customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL @@ -704,7 +702,6 @@ func runListAuth(c *cli.Context) error { } loginSources, err := models.LoginSources() - if err != nil { return err } diff --git a/cmd/admin_auth_ldap_test.go b/cmd/admin_auth_ldap_test.go index 87f4f789ab0ab..1bae07b7c37ae 100644 --- a/cmd/admin_auth_ldap_test.go +++ b/cmd/admin_auth_ldap_test.go @@ -16,12 +16,12 @@ import ( func TestAddLdapBindDn(t *testing.T) { // Mock cli functions to do not exit on error - var osExiter = cli.OsExiter + osExiter := cli.OsExiter defer func() { cli.OsExiter = osExiter }() cli.OsExiter = func(code int) {} // Test cases - var cases = []struct { + cases := []struct { args []string loginSource *models.LoginSource errMsg string @@ -244,12 +244,12 @@ func TestAddLdapBindDn(t *testing.T) { func TestAddLdapSimpleAuth(t *testing.T) { // Mock cli functions to do not exit on error - var osExiter = cli.OsExiter + osExiter := cli.OsExiter defer func() { cli.OsExiter = osExiter }() cli.OsExiter = func(code int) {} // Test cases - var cases = []struct { + cases := []struct { args []string loginSource *models.LoginSource errMsg string @@ -477,12 +477,12 @@ func TestAddLdapSimpleAuth(t *testing.T) { func TestUpdateLdapBindDn(t *testing.T) { // Mock cli functions to do not exit on error - var osExiter = cli.OsExiter + osExiter := cli.OsExiter defer func() { cli.OsExiter = osExiter }() cli.OsExiter = func(code int) {} // Test cases - var cases = []struct { + cases := []struct { args []string id int64 existingLoginSource *models.LoginSource @@ -958,12 +958,12 @@ func TestUpdateLdapBindDn(t *testing.T) { func TestUpdateLdapSimpleAuth(t *testing.T) { // Mock cli functions to do not exit on error - var osExiter = cli.OsExiter + osExiter := cli.OsExiter defer func() { cli.OsExiter = osExiter }() cli.OsExiter = func(code int) {} // Test cases - var cases = []struct { + cases := []struct { args []string id int64 existingLoginSource *models.LoginSource diff --git a/cmd/cert.go b/cmd/cert.go index b62319f80854a..162c4171bfb29 100644 --- a/cmd/cert.go +++ b/cmd/cert.go @@ -180,7 +180,7 @@ func runCert(c *cli.Context) error { } log.Println("Written cert.pem") - keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { log.Fatalf("Failed to open key.pem for writing: %v", err) } diff --git a/cmd/doctor.go b/cmd/doctor.go index 0152aebe39959..0ff4627a2c8b9 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -120,11 +120,9 @@ func runRecreateTable(ctx *cli.Context) error { } return recreateTables(x) }) - } func runDoctor(ctx *cli.Context) error { - // Silence the default loggers log.DelNamedLogger("console") log.DelNamedLogger(log.DEFAULT) diff --git a/cmd/dump.go b/cmd/dump.go index 43997c8da8c57..3c6d7c12a2b9b 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -26,7 +26,7 @@ import ( "github.com/urfave/cli" ) -func addFile(w archiver.Writer, filePath string, absPath string, verbose bool) error { +func addFile(w archiver.Writer, filePath, absPath string, verbose bool) error { if verbose { log.Info("Adding file %s\n", filePath) } @@ -49,7 +49,7 @@ func addFile(w archiver.Writer, filePath string, absPath string, verbose bool) e }) } -func isSubdir(upper string, lower string) (bool, error) { +func isSubdir(upper, lower string) (bool, error) { if relPath, err := filepath.Rel(upper, lower); err != nil { return false, err } else if relPath == "." || !strings.HasPrefix(relPath, ".") { @@ -353,7 +353,7 @@ func runDump(ctx *cli.Context) error { fatal("Failed to save %s: %v", fileName, err) } - if err := os.Chmod(fileName, 0600); err != nil { + if err := os.Chmod(fileName, 0o600); err != nil { log.Info("Can't change file access permissions mask to 0600: %v", err) } } diff --git a/cmd/dump_repo.go b/cmd/dump_repo.go index cea640b53438d..5c1632cee5db7 100644 --- a/cmd/dump_repo.go +++ b/cmd/dump_repo.go @@ -104,7 +104,7 @@ func runDumpRepository(ctx *cli.Context) error { } serviceType = convert.ToGitServiceType(serviceStr) - var opts = base.MigrateOptions{ + opts := base.MigrateOptions{ GitServiceType: serviceType, CloneAddr: cloneAddr, AuthUsername: ctx.String("auth_username"), diff --git a/cmd/embedded.go b/cmd/embedded.go index 363b85c066eaa..337cb85f4025d 100644 --- a/cmd/embedded.go +++ b/cmd/embedded.go @@ -107,7 +107,6 @@ type asset struct { } func initEmbeddedExtractor(c *cli.Context) error { - // Silence the console logger log.DelNamedLogger("console") log.DelNamedLogger(log.DEFAULT) @@ -258,7 +257,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error { return fmt.Errorf("%s: %v", dir, err) } - perms := os.ModePerm & 0666 + perms := os.ModePerm & 0o666 fi, err := os.Lstat(dest) if err != nil { @@ -294,7 +293,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error { } func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset { - var results = make([]asset, 0, 64) + results := make([]asset, 0, 64) for _, name := range sec.Names() { if isdir, err := sec.IsDir(name); !isdir && err == nil { if sec.Path == "public" && @@ -305,9 +304,11 @@ func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset { matchName := sec.Path + "/" + name for _, g := range globs { if g.Match(matchName) { - results = append(results, asset{Section: sec, - Name: name, - Path: sec.Path + "/" + name}) + results = append(results, asset{ + Section: sec, + Name: name, + Path: sec.Path + "/" + name, + }) break } } diff --git a/cmd/manager.go b/cmd/manager.go index 20c7858682aca..1817ce26e49e2 100644 --- a/cmd/manager.go +++ b/cmd/manager.go @@ -58,7 +58,8 @@ var ( Name: "timeout", Value: 60 * time.Second, Usage: "Timeout for the flushing process", - }, cli.BoolFlag{ + }, + cli.BoolFlag{ Name: "non-blocking", Usage: "Set to true to not wait for flush to complete before returning", }, diff --git a/cmd/restore_repo.go b/cmd/restore_repo.go index 541995879bf4c..24c089ccc7b78 100644 --- a/cmd/restore_repo.go +++ b/cmd/restore_repo.go @@ -68,7 +68,7 @@ func runRestoreRepository(ctx *cli.Context) error { return err } - var opts = base.MigrateOptions{ + opts := base.MigrateOptions{ RepoName: ctx.String("repo_name"), } diff --git a/cmd/serv.go b/cmd/serv.go index a8db623e162e7..363364b6ba550 100644 --- a/cmd/serv.go +++ b/cmd/serv.go @@ -227,7 +227,7 @@ func runServ(c *cli.Context) error { os.Setenv(models.EnvKeyID, fmt.Sprintf("%d", results.KeyID)) os.Setenv(models.EnvAppURL, setting.AppURL) - //LFS token authentication + // LFS token authentication if verb == lfsAuthenticateVerb { url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName)) diff --git a/cmd/web.go b/cmd/web.go index 423917ba4e112..7ee8c2246eff2 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -64,8 +64,7 @@ func runHTTPRedirector() { http.Redirect(w, r, target, http.StatusTemporaryRedirect) }) - var err = runHTTP("tcp", source, "HTTP Redirector", context2.ClearHandler(handler)) - + err := runHTTP("tcp", source, "HTTP Redirector", context2.ClearHandler(handler)) if err != nil { log.Fatal("Failed to start port redirection: %v", err) } diff --git a/cmd/web_letsencrypt.go b/cmd/web_letsencrypt.go index 7754393729173..8bfb94494f88b 100644 --- a/cmd/web_letsencrypt.go +++ b/cmd/web_letsencrypt.go @@ -16,7 +16,6 @@ import ( ) func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error { - // If HTTP Challenge enabled, needs to be serving on port 80. For TLSALPN needs 443. // Due to docker port mapping this can't be checked programatically // TODO: these are placeholders until we add options for each in settings with appropriate warning @@ -46,7 +45,7 @@ func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) go func() { log.Info("Running Let's Encrypt handler on %s", setting.HTTPAddr+":"+setting.PortToRedirect) // all traffic coming into HTTP will be redirect to HTTPS automatically (LE HTTP-01 validation happens here) - var err = runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler))) + err := runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler))) if err != nil { log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err) } diff --git a/contrib/fixtures/fixture_generation.go b/contrib/fixtures/fixture_generation.go index 802a2ca30c935..462d62c8f12f2 100644 --- a/contrib/fixtures/fixture_generation.go +++ b/contrib/fixtures/fixture_generation.go @@ -64,7 +64,7 @@ func generate(name string) error { return err } path := filepath.Join(fixturesDir, name+".yml") - if err := ioutil.WriteFile(path, []byte(data), 0644); err != nil { + if err := ioutil.WriteFile(path, []byte(data), 0o644); err != nil { return fmt.Errorf("%s: %+v", path, err) } fmt.Printf("%s created.\n", path) diff --git a/contrib/pr/checkout.go b/contrib/pr/checkout.go index 63eca484a51d4..7f0a03265b566 100644 --- a/contrib/pr/checkout.go +++ b/contrib/pr/checkout.go @@ -93,13 +93,13 @@ func runPR() { routers.NewServices() setting.Database.LogSQL = true - //x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared") + // x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared") models.NewEngine(context.Background(), func(_ *xorm.Engine) error { return nil }) models.HasEngine = true - //x.ShowSQL(true) + // x.ShowSQL(true) err = models.InitFixtures( path.Join(curDir, "models/fixtures/"), ) @@ -113,7 +113,7 @@ func runPR() { util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath) log.Printf("[PR] Setting up router\n") - //routers.GlobalInit() + // routers.GlobalInit() external.RegisterParsers() markup.Init() c := routes.NormalRoutes() @@ -135,7 +135,7 @@ func runPR() { } */ - //Start the server + // Start the server http.ListenAndServe(":8080", context2.ClearHandler(c)) log.Printf("[PR] Cleaning up ...\n") @@ -158,7 +158,7 @@ func runPR() { } func main() { - var runPRFlag = flag.Bool("run", false, "Run the PR code") + runPRFlag := flag.Bool("run", false, "Run the PR code") flag.Parse() if *runPRFlag { runPR() @@ -171,15 +171,15 @@ func main() { force = false } - //Otherwise checkout PR + // Otherwise checkout PR if len(os.Args) != 2 { log.Fatal("Need only one arg: the PR number") } pr := os.Args[1] - codeFilePath = filepath.FromSlash(codeFilePath) //Convert to running OS + codeFilePath = filepath.FromSlash(codeFilePath) // Convert to running OS - //Copy this file if it will not exist in the PR branch + // Copy this file if it will not exist in the PR branch dat, err := ioutil.ReadFile(codeFilePath) if err != nil { log.Fatalf("Failed to cache this code file : %v", err) @@ -190,16 +190,16 @@ func main() { log.Fatalf("Failed to open the repo : %v", err) } - //Find remote upstream + // Find remote upstream remotes, err := repo.Remotes() if err != nil { log.Fatalf("Failed to list remotes of repo : %v", err) } - remoteUpstream := "origin" //Default + remoteUpstream := "origin" // Default for _, r := range remotes { if r.Config().URLs[0] == "https://github.com/go-gitea/gitea.git" || r.Config().URLs[0] == "https://github.com/go-gitea/gitea" || - r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { //fetch at index 0 + r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { // fetch at index 0 remoteUpstream = r.Config().Name break } @@ -210,7 +210,7 @@ func main() { log.Printf("Fetching PR #%s in %s\n", pr, branch) if runtime.GOOS == "windows" { - //Use git cli command for windows + // Use git cli command for windows runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch)) } else { ref := fmt.Sprintf("refs/pull/%s/head:%s", pr, branchRef) @@ -238,22 +238,23 @@ func main() { log.Fatalf("Failed to checkout %s : %v", branch, err) } - //Copy this file if not exist + // Copy this file if not exist if _, err := os.Stat(codeFilePath); os.IsNotExist(err) { - err = os.MkdirAll(filepath.Dir(codeFilePath), 0755) + err = os.MkdirAll(filepath.Dir(codeFilePath), 0o755) if err != nil { log.Fatalf("Failed to duplicate this code file in PR : %v", err) } - err = ioutil.WriteFile(codeFilePath, dat, 0644) + err = ioutil.WriteFile(codeFilePath, dat, 0o644) if err != nil { log.Fatalf("Failed to duplicate this code file in PR : %v", err) } } - //Force build of js, css, bin, ... + // Force build of js, css, bin, ... runCmd("make", "build") - //Start with integration test + // Start with integration test runCmd("go", "run", "-mod", "vendor", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run") } + func runCmd(cmd ...string) { log.Printf("Executing : %s ...\n", cmd) c := exec.Command(cmd[0], cmd[1:]...) diff --git a/integrations/api_admin_org_test.go b/integrations/api_admin_org_test.go index b10f5607d300f..be2d0fb6b8286 100644 --- a/integrations/api_admin_org_test.go +++ b/integrations/api_admin_org_test.go @@ -21,7 +21,7 @@ func TestAPIAdminOrgCreate(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.CreateOrgOption{ + org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", Description: "This organization created by admin for user2", @@ -55,7 +55,7 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.CreateOrgOption{ + org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", Description: "This organization created by admin for user2", @@ -73,7 +73,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { nonAdminUsername := "user2" session := loginUser(t, nonAdminUsername) token := getTokenForLoggedInUser(t, session) - var org = api.CreateOrgOption{ + org := api.CreateOrgOption{ UserName: "user2_org", FullName: "User2's organization", Description: "This organization created by admin for user2", diff --git a/integrations/api_branch_test.go b/integrations/api_branch_test.go index 26d8fb4b451f9..2a09c032281a5 100644 --- a/integrations/api_branch_test.go +++ b/integrations/api_branch_test.go @@ -106,7 +106,6 @@ func TestAPICreateBranch(t *testing.T) { } func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { - username := "user2" ctx := NewAPITestContext(t, username, "my-noo-repo") giteaURL.Path = ctx.GitPath() diff --git a/integrations/api_comment_test.go b/integrations/api_comment_test.go index f64f4a1c9c0f2..2ad015294bef7 100644 --- a/integrations/api_comment_test.go +++ b/integrations/api_comment_test.go @@ -41,10 +41,10 @@ func TestAPIListRepoComments(t *testing.T) { models.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID}) } - //test before and since filters + // test before and since filters query := url.Values{} - before := "2000-01-01T00:00:11+00:00" //unix: 946684811 - since := "2000-01-01T00:00:12+00:00" //unix: 946684812 + before := "2000-01-01T00:00:11+00:00" // unix: 946684811 + since := "2000-01-01T00:00:12+00:00" // unix: 946684812 query.Add("before", before) link.RawQuery = query.Encode() req = NewRequest(t, "GET", link.String()) diff --git a/integrations/api_gpg_keys_test.go b/integrations/api_gpg_keys_test.go index e664c3c256553..134840e66c732 100644 --- a/integrations/api_gpg_keys_test.go +++ b/integrations/api_gpg_keys_test.go @@ -28,16 +28,18 @@ func TestGPGKeys(t *testing.T) { token string results []int }{ - {name: "NoLogin", makeRequest: MakeRequest, token: "", + { + name: "NoLogin", makeRequest: MakeRequest, token: "", results: []int{http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized}, }, - {name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, - results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusCreated}}, + { + name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, + results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusCreated}, + }, } for _, tc := range tt { - - //Basic test on result code + // Basic test on result code t.Run(tc.name, func(t *testing.T) { t.Run("ViewOwnGPGKeys", func(t *testing.T) { testViewOwnGPGKeys(t, tc.makeRequest, tc.token, tc.results[0]) @@ -67,33 +69,32 @@ func TestGPGKeys(t *testing.T) { }) } - //Check state after basic add + // Check state after basic add t.Run("CheckState", func(t *testing.T) { - var keys []*api.GPGKey - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) //GET all keys + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) // GET all keys resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &keys) - primaryKey1 := keys[0] //Primary key 1 + primaryKey1 := keys[0] // Primary key 1 assert.EqualValues(t, "38EA3BCED732982C", primaryKey1.KeyID) assert.EqualValues(t, 1, len(primaryKey1.Emails)) assert.EqualValues(t, "user2@example.com", primaryKey1.Emails[0].Email) assert.EqualValues(t, true, primaryKey1.Emails[0].Verified) - subKey := primaryKey1.SubsKey[0] //Subkey of 38EA3BCED732982C + subKey := primaryKey1.SubsKey[0] // Subkey of 38EA3BCED732982C assert.EqualValues(t, "70D7C694D17D03AD", subKey.KeyID) assert.EqualValues(t, 0, len(subKey.Emails)) - primaryKey2 := keys[1] //Primary key 2 + primaryKey2 := keys[1] // Primary key 2 assert.EqualValues(t, "FABF39739FE1E927", primaryKey2.KeyID) assert.EqualValues(t, 1, len(primaryKey2.Emails)) assert.EqualValues(t, "user21@example.com", primaryKey2.Emails[0].Email) assert.EqualValues(t, false, primaryKey2.Emails[0].Verified) var key api.GPGKey - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) //Primary key 1 + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) // Primary key 1 resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "38EA3BCED732982C", key.KeyID) @@ -101,23 +102,22 @@ func TestGPGKeys(t *testing.T) { assert.EqualValues(t, "user2@example.com", key.Emails[0].Email) assert.EqualValues(t, true, key.Emails[0].Verified) - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) //Subkey of 38EA3BCED732982C + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) // Subkey of 38EA3BCED732982C resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID) assert.EqualValues(t, 0, len(key.Emails)) - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey2.ID, 10)+"?token="+token) //Primary key 2 + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey2.ID, 10)+"?token="+token) // Primary key 2 resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "FABF39739FE1E927", key.KeyID) assert.EqualValues(t, 1, len(key.Emails)) assert.EqualValues(t, "user21@example.com", key.Emails[0].Email) assert.EqualValues(t, false, key.Emails[0].Verified) - }) - //Check state after basic add + // Check state after basic add t.Run("CheckCommits", func(t *testing.T) { t.Run("NotSigned", func(t *testing.T) { var branch api.Branch @@ -197,7 +197,7 @@ INx/MmBfmtCq05FqNclvU+sj2R3N1JJOtBOjZrJHQbJhzoILou8AkxeX1A+q9OAz } func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - //User2 //primary & activated + // User2 //primary & activated testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW @@ -231,7 +231,7 @@ uy6MA3VSB99SK9ducGmE1Jv8mcziREroz2TEGr0zPs6h } func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - //User2 //secondary and not activated + // User2 //secondary and not activated testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFmGWN4BCAC18V4tVGO65VLCV7p14FuXJlUtZ5CuYMvgEkcOqrvRaBSW9ao4 diff --git a/integrations/api_issue_label_test.go b/integrations/api_issue_label_test.go index 64c3515dd2bb3..0da513c965fbe 100644 --- a/integrations/api_issue_label_test.go +++ b/integrations/api_issue_label_test.go @@ -50,21 +50,21 @@ func TestAPIModifyLabels(t *testing.T) { }) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //ListLabels + // ListLabels req = NewRequest(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) assert.Len(t, apiLabels, 2) - //GetLabel + // GetLabel singleURLStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels/%d?token=%s", owner.Name, repo.Name, dbLabel.ID, token) req = NewRequest(t, "GET", singleURLStr) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) - //EditLabel + // EditLabel newName := "LabelNewName" newColor := "09876a" newColorWrong := "09g76a" @@ -80,10 +80,9 @@ func TestAPIModifyLabels(t *testing.T) { }) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //DeleteLabel + // DeleteLabel req = NewRequest(t, "DELETE", singleURLStr) resp = session.MakeRequest(t, req, http.StatusNoContent) - } func TestAPIAddIssueLabels(t *testing.T) { @@ -170,21 +169,21 @@ func TestAPIModifyOrgLabels(t *testing.T) { }) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //ListLabels + // ListLabels req = NewRequest(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) assert.Len(t, apiLabels, 4) - //GetLabel + // GetLabel singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d?token=%s", owner.Name, dbLabel.ID, token) req = NewRequest(t, "GET", singleURLStr) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) - //EditLabel + // EditLabel newName := "LabelNewName" newColor := "09876a" newColorWrong := "09g76a" @@ -200,8 +199,7 @@ func TestAPIModifyOrgLabels(t *testing.T) { }) session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //DeleteLabel + // DeleteLabel req = NewRequest(t, "DELETE", singleURLStr) resp = session.MakeRequest(t, req, http.StatusNoContent) - } diff --git a/integrations/api_issue_reaction_test.go b/integrations/api_issue_reaction_test.go index 20b83db2aab69..8256326b38505 100644 --- a/integrations/api_issue_reaction_test.go +++ b/integrations/api_issue_reaction_test.go @@ -31,19 +31,19 @@ func TestAPIIssuesReactions(t *testing.T) { urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) - //Try to add not allowed reaction + // Try to add not allowed reaction req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "wrong", }) resp := session.MakeRequest(t, req, http.StatusForbidden) - //Delete not allowed reaction + // Delete not allowed reaction req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "zzz", }) resp = session.MakeRequest(t, req, http.StatusOK) - //Add allowed reaction + // Add allowed reaction req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "rocket", }) @@ -51,10 +51,10 @@ func TestAPIIssuesReactions(t *testing.T) { var apiNewReaction api.Reaction DecodeJSON(t, resp, &apiNewReaction) - //Add existing reaction + // Add existing reaction resp = session.MakeRequest(t, req, http.StatusForbidden) - //Get end result of reaction list of issue #1 + // Get end result of reaction list of issue #1 req = NewRequestf(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) var apiReactions []*api.Reaction @@ -91,19 +91,19 @@ func TestAPICommentReactions(t *testing.T) { urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s", owner.Name, issue.Repo.Name, comment.ID, token) - //Try to add not allowed reaction + // Try to add not allowed reaction req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "wrong", }) resp := session.MakeRequest(t, req, http.StatusForbidden) - //Delete none existing reaction + // Delete none existing reaction req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "eyes", }) resp = session.MakeRequest(t, req, http.StatusOK) - //Add allowed reaction + // Add allowed reaction req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "+1", }) @@ -111,10 +111,10 @@ func TestAPICommentReactions(t *testing.T) { var apiNewReaction api.Reaction DecodeJSON(t, resp, &apiNewReaction) - //Add existing reaction + // Add existing reaction resp = session.MakeRequest(t, req, http.StatusForbidden) - //Get end result of reaction list of issue #1 + // Get end result of reaction list of issue #1 req = NewRequestf(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) var apiReactions []*api.Reaction diff --git a/integrations/api_issue_subscription_test.go b/integrations/api_issue_subscription_test.go index d0b192101556b..92b42e93f1069 100644 --- a/integrations/api_issue_subscription_test.go +++ b/integrations/api_issue_subscription_test.go @@ -30,7 +30,6 @@ func TestAPIIssueSubscriptions(t *testing.T) { token := getTokenForLoggedInUser(t, session) testSubscription := func(issue *models.Issue, isWatching bool) { - issueRepo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token) diff --git a/integrations/api_issue_test.go b/integrations/api_issue_test.go index f932f79feea07..e9bfdb24e3b2f 100644 --- a/integrations/api_issue_test.go +++ b/integrations/api_issue_test.go @@ -44,7 +44,6 @@ func TestAPIListIssues(t *testing.T) { assert.EqualValues(t, 3, apiIssues[0].Milestone.ID) assert.EqualValues(t, 1, apiIssues[1].Milestone.ID) } - } func TestAPICreateIssue(t *testing.T) { @@ -187,7 +186,7 @@ func TestAPISearchIssues(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.EqualValues(t, "14", resp.Header().Get("X-Total-Count")) - assert.Len(t, apiIssues, 10) //there are more but 10 is page item limit + assert.Len(t, apiIssues, 10) // there are more but 10 is page item limit query.Add("limit", "20") link.RawQuery = query.Encode() diff --git a/integrations/api_issue_tracked_time_test.go b/integrations/api_issue_tracked_time_test.go index 1a0ee99a43ad8..528ec32c51ac2 100644 --- a/integrations/api_issue_tracked_time_test.go +++ b/integrations/api_issue_tracked_time_test.go @@ -46,8 +46,8 @@ func TestAPIGetTrackedTimes(t *testing.T) { } // test filter - since := "2000-01-01T00%3A00%3A02%2B00%3A00" //946684802 - before := "2000-01-01T00%3A00%3A12%2B00%3A00" //946684812 + since := "2000-01-01T00%3A00%3A02%2B00%3A00" // 946684802 + before := "2000-01-01T00%3A00%3A12%2B00%3A00" // 946684812 req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?since=%s&before=%s&token=%s", user2.Name, issue2.Repo.Name, issue2.Index, since, before, token) resp = session.MakeRequest(t, req, http.StatusOK) @@ -69,17 +69,17 @@ func TestAPIDeleteTrackedTime(t *testing.T) { session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session) - //Deletion not allowed + // Deletion not allowed req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) session.MakeRequest(t, req, http.StatusForbidden) time3 := models.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 3}).(*models.TrackedTime) req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID, token) session.MakeRequest(t, req, http.StatusNoContent) - //Delete non existing time + // Delete non existing time session.MakeRequest(t, req, http.StatusNotFound) - //Reset time of user 2 on issue 2 + // Reset time of user 2 on issue 2 trackedSeconds, err := models.GetTrackedSeconds(models.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) assert.NoError(t, err) assert.Equal(t, int64(3661), trackedSeconds) diff --git a/integrations/api_notification_test.go b/integrations/api_notification_test.go index 42041734200b0..ee0112bb377b1 100644 --- a/integrations/api_notification_test.go +++ b/integrations/api_notification_test.go @@ -27,7 +27,7 @@ func TestAPINotification(t *testing.T) { // -- GET /notifications -- // test filter - since := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801 + since := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s&token=%s", since, token)) resp := session.MakeRequest(t, req, http.StatusOK) var apiNL []api.NotificationThread @@ -37,7 +37,7 @@ func TestAPINotification(t *testing.T) { assert.EqualValues(t, 5, apiNL[0].ID) // test filter - before := "2000-01-01T01%3A06%3A59%2B00%3A00" //946688819 + before := "2000-01-01T01%3A06%3A59%2B00%3A00" // 946688819 req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=%s&before=%s&token=%s", "true", before, token)) resp = session.MakeRequest(t, req, http.StatusOK) @@ -97,7 +97,7 @@ func TestAPINotification(t *testing.T) { DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 2) - lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801 <- only Notification 4 is in this filter ... + lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) resp = session.MakeRequest(t, req, http.StatusResetContent) diff --git a/integrations/api_org_test.go b/integrations/api_org_test.go index 551da30326949..687df7f069772 100644 --- a/integrations/api_org_test.go +++ b/integrations/api_org_test.go @@ -22,7 +22,7 @@ func TestAPIOrgCreate(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.CreateOrgOption{ + org := api.CreateOrgOption{ UserName: "user1_org", FullName: "User1's organization", Description: "This organization created by user1", @@ -79,7 +79,7 @@ func TestAPIOrgEdit(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.EditOrgOption{ + org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", Website: "https://try.gitea.io/new", @@ -106,7 +106,7 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - var org = api.EditOrgOption{ + org := api.EditOrgOption{ FullName: "User3 organization new full name", Description: "A new description", Website: "https://try.gitea.io/new", @@ -125,7 +125,7 @@ func TestAPIOrgDeny(t *testing.T) { setting.Service.RequireSignInView = false }() - var orgName = "user1_org" + orgName := "user1_org" req := NewRequestf(t, "GET", "/api/v1/orgs/%s", orgName) MakeRequest(t, req, http.StatusNotFound) diff --git a/integrations/api_pull_review_test.go b/integrations/api_pull_review_test.go index 8be194602fc3d..daa349e19e7e9 100644 --- a/integrations/api_pull_review_test.go +++ b/integrations/api_pull_review_test.go @@ -76,22 +76,23 @@ func TestAPIPullReview(t *testing.T) { req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ Body: "body1", // Event: "" # will result in PENDING - Comments: []api.CreatePullReviewComment{{ - Path: "README.md", - Body: "first new line", - OldLineNum: 0, - NewLineNum: 1, - }, { - Path: "README.md", - Body: "first old line", - OldLineNum: 1, - NewLineNum: 0, - }, { - Path: "iso-8859-1.txt", - Body: "this line contains a non-utf-8 character", - OldLineNum: 0, - NewLineNum: 1, - }, + Comments: []api.CreatePullReviewComment{ + { + Path: "README.md", + Body: "first new line", + OldLineNum: 0, + NewLineNum: 1, + }, { + Path: "README.md", + Body: "first old line", + OldLineNum: 1, + NewLineNum: 0, + }, { + Path: "iso-8859-1.txt", + Body: "this line contains a non-utf-8 character", + OldLineNum: 0, + NewLineNum: 1, + }, }, }) resp = session.MakeRequest(t, req, http.StatusOK) diff --git a/integrations/api_repo_edit_test.go b/integrations/api_repo_edit_test.go index c1b513d0753c1..3b5de8962b674 100644 --- a/integrations/api_repo_edit_test.go +++ b/integrations/api_repo_edit_test.go @@ -170,7 +170,7 @@ func TestAPIRepoEdit(t *testing.T) { assert.Equal(t, *repoEditOption.Private, *repo1editedOption.Private) assert.Equal(t, *repoEditOption.HasWiki, *repo1editedOption.HasWiki) - //Test editing repo1 to use internal issue and wiki (default) + // Test editing repo1 to use internal issue and wiki (default) *repoEditOption.HasIssues = true repoEditOption.ExternalTracker = nil repoEditOption.InternalTracker = &api.InternalTracker{ @@ -194,7 +194,7 @@ func TestAPIRepoEdit(t *testing.T) { assert.Equal(t, *repo1editedOption.HasWiki, true) assert.Nil(t, repo1editedOption.ExternalWiki) - //Test editing repo1 to use external issue and wiki + // Test editing repo1 to use external issue and wiki repoEditOption.ExternalTracker = &api.ExternalTracker{ ExternalTrackerURL: "http://www.somewebsite.com", ExternalTrackerFormat: "http://www.somewebsite.com/{user}/{repo}?issue={index}", @@ -228,7 +228,7 @@ func TestAPIRepoEdit(t *testing.T) { req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) resp = session.MakeRequest(t, req, http.StatusUnprocessableEntity) - //Test small repo change through API with issue and wiki option not set; They shall not be touched. + // Test small repo change through API with issue and wiki option not set; They shall not be touched. *repoEditOption.Description = "small change" repoEditOption.HasIssues = nil repoEditOption.ExternalTracker = nil diff --git a/integrations/api_repo_lfs_locks_test.go b/integrations/api_repo_lfs_locks_test.go index 69981d1c42000..8f2c690157419 100644 --- a/integrations/api_repo_lfs_locks_test.go +++ b/integrations/api_repo_lfs_locks_test.go @@ -50,8 +50,8 @@ func TestAPILFSLocksNotLogin(t *testing.T) { func TestAPILFSLocksLogged(t *testing.T) { defer prepareTestEnv(t)() setting.LFS.StartServer = true - user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) //in org 3 - user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) //in org 3 + user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // in org 3 + user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // in org 3 repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // own by org 3 @@ -98,7 +98,7 @@ func TestAPILFSLocksLogged(t *testing.T) { lockID string }{} - //create locks + // create locks for _, test := range tests { session := loginUser(t, test.user.Name) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks", test.repo.FullName()), map[string]string{"path": test.path}) @@ -108,14 +108,14 @@ func TestAPILFSLocksLogged(t *testing.T) { if len(test.addTime) > 0 { var lfsLock api.LFSLockResponse DecodeJSON(t, resp, &lfsLock) - assert.EqualValues(t, lfsLock.Lock.LockedAt.Format(time.RFC3339), lfsLock.Lock.LockedAt.Format(time.RFC3339Nano)) //locked at should be rounded to second + assert.EqualValues(t, lfsLock.Lock.LockedAt.Format(time.RFC3339), lfsLock.Lock.LockedAt.Format(time.RFC3339Nano)) // locked at should be rounded to second for _, id := range test.addTime { resultsTests[id].locksTimes = append(resultsTests[id].locksTimes, time.Now()) } } } - //check creation + // check creation for _, test := range resultsTests { session := loginUser(t, test.user.Name) req := NewRequestf(t, "GET", "/%s.git/info/lfs/locks", test.repo.FullName()) @@ -127,7 +127,7 @@ func TestAPILFSLocksLogged(t *testing.T) { for i, lock := range lfsLocks.Locks { assert.EqualValues(t, test.locksOwners[i].DisplayName(), lock.Owner.Name) assert.WithinDuration(t, test.locksTimes[i], lock.LockedAt, 10*time.Second) - assert.EqualValues(t, lock.LockedAt.Format(time.RFC3339), lock.LockedAt.Format(time.RFC3339Nano)) //locked at should be rounded to second + assert.EqualValues(t, lock.LockedAt.Format(time.RFC3339), lock.LockedAt.Format(time.RFC3339Nano)) // locked at should be rounded to second } req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks/verify", test.repo.FullName()), map[string]string{}) @@ -151,7 +151,7 @@ func TestAPILFSLocksLogged(t *testing.T) { } } - //remove all locks + // remove all locks for _, test := range deleteTests { session := loginUser(t, test.user.Name) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks/%s/unlock", test.repo.FullName(), test.lockID), map[string]string{}) diff --git a/integrations/api_repo_test.go b/integrations/api_repo_test.go index cfd3b58d649d6..6cfd1570e4e76 100644 --- a/integrations/api_repo_test.go +++ b/integrations/api_repo_test.go @@ -76,76 +76,99 @@ func TestAPISearchRepo(t *testing.T) { name, requestURL string expectedResults }{ - {name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{ - nil: {count: 30}, - user: {count: 30}, - user2: {count: 30}}, + { + name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{ + nil: {count: 30}, + user: {count: 30}, + user2: {count: 30}, + }, }, - {name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{ - nil: {count: 10}, - user: {count: 10}, - user2: {count: 10}}, + { + name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{ + nil: {count: 10}, + user: {count: 10}, + user2: {count: 10}, + }, }, - {name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{ - nil: {count: 10}, - user: {count: 10}, - user2: {count: 10}}, + { + name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{ + nil: {count: 10}, + user: {count: 10}, + user2: {count: 10}, + }, }, - {name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{ - nil: {count: 7, repoName: "big_test_"}, - user: {count: 7, repoName: "big_test_"}, - user2: {count: 7, repoName: "big_test_"}}, + { + name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{ + nil: {count: 7, repoName: "big_test_"}, + user: {count: 7, repoName: "big_test_"}, + user2: {count: 7, repoName: "big_test_"}, + }, }, - {name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{ - nil: {count: 5}, - user: {count: 9, includesPrivate: true}, - user2: {count: 6, includesPrivate: true}}, + { + name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{ + nil: {count: 5}, + user: {count: 9, includesPrivate: true}, + user2: {count: 6, includesPrivate: true}, + }, }, - {name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{ - nil: {count: 1}, - user: {count: 2, includesPrivate: true}, - user2: {count: 2, includesPrivate: true}, - user4: {count: 1}}, + { + name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{ + nil: {count: 1}, + user: {count: 2, includesPrivate: true}, + user2: {count: 2, includesPrivate: true}, + user4: {count: 1}, + }, }, - {name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{ - nil: {count: 1}, - user: {count: 4, includesPrivate: true}, - user2: {count: 3, includesPrivate: true}, - user3: {count: 4, includesPrivate: true}}, + { + name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{ + nil: {count: 1}, + user: {count: 4, includesPrivate: true}, + user2: {count: 3, includesPrivate: true}, + user3: {count: 4, includesPrivate: true}, + }, }, - {name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{ - nil: {count: 1, repoOwnerID: orgUser.ID}, - user: {count: 2, repoOwnerID: orgUser.ID, includesPrivate: true}, - user2: {count: 1, repoOwnerID: orgUser.ID}}, + { + name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{ + nil: {count: 1, repoOwnerID: orgUser.ID}, + user: {count: 2, repoOwnerID: orgUser.ID, includesPrivate: true}, + user2: {count: 1, repoOwnerID: orgUser.ID}, + }, }, {name: "RepositoriesAccessibleAndRelatedToUser4", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user4.ID), expectedResults: expectedResults{ nil: {count: 3}, user: {count: 4, includesPrivate: true}, - user4: {count: 7, includesPrivate: true}}}, + user4: {count: 7, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeSource", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "source"), expectedResults: expectedResults{ nil: {count: 0}, user: {count: 1, includesPrivate: true}, - user4: {count: 1, includesPrivate: true}}}, + user4: {count: 1, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "fork"), expectedResults: expectedResults{ nil: {count: 1}, user: {count: 1}, - user4: {count: 2, includesPrivate: true}}}, + user4: {count: 2, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "fork"), expectedResults: expectedResults{ nil: {count: 1}, user: {count: 1}, - user4: {count: 2, includesPrivate: true}}}, + user4: {count: 2, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "mirror"), expectedResults: expectedResults{ nil: {count: 2}, user: {count: 2}, - user4: {count: 4, includesPrivate: true}}}, + user4: {count: 4, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "mirror"), expectedResults: expectedResults{ nil: {count: 1}, user: {count: 1}, - user4: {count: 2, includesPrivate: true}}}, + user4: {count: 2, includesPrivate: true}, + }}, {name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeCollaborative", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "collaborative"), expectedResults: expectedResults{ nil: {count: 0}, user: {count: 1, includesPrivate: true}, - user4: {count: 1, includesPrivate: true}}}, + user4: {count: 1, includesPrivate: true}, + }}, } for _, testCase := range testCases { @@ -461,7 +484,7 @@ func TestAPIRepoTransfer(t *testing.T) { defer prepareTestEnv(t)() - //create repo to move + // create repo to move user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -477,7 +500,7 @@ func TestAPIRepoTransfer(t *testing.T) { resp := session.MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, repo) - //start testing + // start testing for _, testCase := range testCases { user = models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) repo = models.AssertExistsAndLoadBean(t, &models.Repository{ID: repo.ID}).(*models.Repository) @@ -490,7 +513,7 @@ func TestAPIRepoTransfer(t *testing.T) { session.MakeRequest(t, req, testCase.expectedStatus) } - //cleanup + // cleanup repo = models.AssertExistsAndLoadBean(t, &models.Repository{ID: repo.ID}).(*models.Repository) _ = models.DeleteRepository(user, repo.OwnerID, repo.ID) } diff --git a/integrations/api_repo_topic_test.go b/integrations/api_repo_topic_test.go index b96489ae2211d..e14fd2fe1c08f 100644 --- a/integrations/api_repo_topic_test.go +++ b/integrations/api_repo_topic_test.go @@ -120,5 +120,4 @@ func TestAPIRepoTopic(t *testing.T) { // Test add a topic to repo with write access (requires repo admin access) req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user3.Name, repo3.Name, "topicName", token4) res = session.MakeRequest(t, req, http.StatusForbidden) - } diff --git a/integrations/api_team_test.go b/integrations/api_team_test.go index d89385447092f..9c77c7105b69c 100644 --- a/integrations/api_team_test.go +++ b/integrations/api_team_test.go @@ -156,5 +156,4 @@ func TestAPITeamSearch(t *testing.T) { session = loginUser(t, user5.Name) req = NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s", org.Name, "team") resp = session.MakeRequest(t, req, http.StatusForbidden) - } diff --git a/integrations/api_user_orgs_test.go b/integrations/api_user_orgs_test.go index c72ee76098d92..b4bd842e97fd3 100644 --- a/integrations/api_user_orgs_test.go +++ b/integrations/api_user_orgs_test.go @@ -53,7 +53,7 @@ func TestUserOrgs(t *testing.T) { } func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organization) { - var token = "" + token := "" session := emptyTestSession(t) if len(userDoer) != 0 { session = loginUser(t, userDoer) diff --git a/integrations/attachment_test.go b/integrations/attachment_test.go index a28e38b9907cf..341c788678137 100644 --- a/integrations/attachment_test.go +++ b/integrations/attachment_test.go @@ -32,7 +32,7 @@ func generateImg() bytes.Buffer { func createAttachment(t *testing.T, session *TestSession, repoURL, filename string, buff bytes.Buffer, expectedStatus int) string { body := &bytes.Buffer{} - //Setup multi-part + // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("file", filename) assert.NoError(t, err) @@ -86,7 +86,7 @@ func TestCreateIssueAttachment(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusFound) test.RedirectURL(resp) // check that redirect URL exists - //Validate that attachment is available + // Validate that attachment is available req = NewRequest(t, "GET", "/attachments/"+uuid) session.MakeRequest(t, req, http.StatusOK) } @@ -120,12 +120,12 @@ func TestGetAttachment(t *testing.T) { } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - //Write empty file to be available for response + // Write empty file to be available for response if tc.createFile { _, err := storage.Attachments.Save(models.AttachmentRelativePath(tc.uuid), strings.NewReader("hello world")) assert.NoError(t, err) } - //Actual test + // Actual test req := NewRequest(t, "GET", "/attachments/"+tc.uuid) tc.session.MakeRequest(t, req, tc.want) }) diff --git a/integrations/benchmarks_test.go b/integrations/benchmarks_test.go index 7c7aff994e491..cef372ffd4d45 100644 --- a/integrations/benchmarks_test.go +++ b/integrations/benchmarks_test.go @@ -47,7 +47,7 @@ func BenchmarkRepo(b *testing.B) { resp := session.MakeRequest(b, req, http.StatusOK) b.StopTimer() if len(branches) == 0 { - DecodeJSON(b, resp, &branches) //Store for next phase + DecodeJSON(b, resp, &branches) // Store for next phase } b.StartTimer() } @@ -64,7 +64,7 @@ func BenchmarkRepo(b *testing.B) { } } -//StringWithCharset random string (from https://www.calhoun.io/creating-random-strings-in-go/) +// StringWithCharset random string (from https://www.calhoun.io/creating-random-strings-in-go/) func StringWithCharset(length int, charset string) string { b := make([]byte, length) for i := range b { @@ -100,7 +100,7 @@ func BenchmarkRepoBranchCommit(b *testing.B) { resp := session.MakeRequest(b, req, http.StatusOK) DecodeJSON(b, resp, &branches) branchCount := len(branches) - b.ResetTimer() //We measure from here + b.ResetTimer() // We measure from here for i := 0; i < b.N; i++ { req := NewRequestf(b, "GET", "/%s/%s/commits/%s", owner.Name, repo.Name, branches[i%branchCount].Name) session.MakeRequest(b, req, http.StatusOK) @@ -110,4 +110,4 @@ func BenchmarkRepoBranchCommit(b *testing.B) { } } -//TODO list commits /repos/{owner}/{repo}/commits +// TODO list commits /repos/{owner}/{repo}/commits diff --git a/integrations/cmd_keys_test.go b/integrations/cmd_keys_test.go index 27ae20cccd8d0..a7f9bb7eb980f 100644 --- a/integrations/cmd_keys_test.go +++ b/integrations/cmd_keys_test.go @@ -29,7 +29,8 @@ func Test_CmdKeys(t *testing.T) { }{ {"test_empty_1", []string{"keys", "--username=git", "--type=test", "--content=test"}, true, ""}, {"test_empty_2", []string{"keys", "-e", "git", "-u", "git", "-t", "test", "-k", "test"}, true, ""}, - {"with_key", + { + "with_key", []string{"keys", "-e", "git", "-u", "git", "-t", "ssh-rsa", "-k", "AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM="}, false, "# gitea public key\ncommand=\"" + setting.AppPath + " --config=" + util.ShellEscape(setting.CustomConf) + " serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n", @@ -38,7 +39,7 @@ func Test_CmdKeys(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - realStdout := os.Stdout //Backup Stdout + realStdout := os.Stdout // Backup Stdout r, w, _ := os.Pipe() os.Stdout = w @@ -56,7 +57,7 @@ func Test_CmdKeys(t *testing.T) { if tt.expectedOutput != commandOutput { t.Errorf("expectedOutput: %#v, commandOutput: %#v", tt.expectedOutput, commandOutput) } - //Restore stdout + // Restore stdout os.Stdout = realStdout }) } diff --git a/integrations/editor_test.go b/integrations/editor_test.go index a46712293e86c..05892aa90684d 100644 --- a/integrations/editor_test.go +++ b/integrations/editor_test.go @@ -120,7 +120,6 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa } func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, branch, targetBranch, filePath, newContent string) *httptest.ResponseRecorder { - // Get to the 'edit this file' page req := NewRequest(t, "GET", path.Join(user, repo, "_edit", branch, filePath)) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/integrations/eventsource_test.go b/integrations/eventsource_test.go index caaf8c2cefff8..0461757096161 100644 --- a/integrations/eventsource_test.go +++ b/integrations/eventsource_test.go @@ -65,7 +65,7 @@ func TestEventSourceManagerRun(t *testing.T) { DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 2) - lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801 <- only Notification 4 is in this filter ... + lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) resp = session.MakeRequest(t, req, http.StatusResetContent) diff --git a/integrations/git_helper_for_declarative_test.go b/integrations/git_helper_for_declarative_test.go index d99d80a7c706b..b46980cdbbcc7 100644 --- a/integrations/git_helper_for_declarative_test.go +++ b/integrations/git_helper_for_declarative_test.go @@ -27,12 +27,11 @@ import ( ) func withKeyFile(t *testing.T, keyname string, callback func(string)) { - tmpDir, err := ioutil.TempDir("", "key-file") assert.NoError(t, err) defer util.RemoveAll(tmpDir) - err = os.Chmod(tmpDir, 0700) + err = os.Chmod(tmpDir, 0o700) assert.NoError(t, err) keyFile := filepath.Join(tmpDir, keyname) @@ -40,10 +39,10 @@ func withKeyFile(t *testing.T, keyname string, callback func(string)) { assert.NoError(t, err) err = ioutil.WriteFile(path.Join(tmpDir, "ssh"), []byte("#!/bin/bash\n"+ - "ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0700) + "ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0o700) assert.NoError(t, err) - //Setup ssh wrapper + // Setup ssh wrapper os.Setenv("GIT_SSH", path.Join(tmpDir, "ssh")) os.Setenv("GIT_SSH_COMMAND", "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -i \""+keyFile+"\"") @@ -103,7 +102,7 @@ func onGiteaRun(t *testing.T, callback func(*testing.T, *url.URL), prepare ...bo }() go s.Serve(listener) - //Started by config go ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers, setting.SSH.ServerKeyExchanges, setting.SSH.ServerMACs) + // Started by config go ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers, setting.SSH.ServerKeyExchanges, setting.SSH.ServerMACs) callback(t, u) } @@ -133,7 +132,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) { return func(t *testing.T) { // Init repository in dstPath assert.NoError(t, git.InitRepository(dstPath, false)) - assert.NoError(t, ioutil.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644)) + assert.NoError(t, ioutil.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644)) assert.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@example.com", diff --git a/integrations/git_test.go b/integrations/git_test.go index d8e7c4fe51f76..a2dc6dc0ff53f 100644 --- a/integrations/git_test.go +++ b/integrations/git_test.go @@ -26,8 +26,8 @@ import ( ) const ( - littleSize = 1024 //1ko - bigSize = 128 * 1024 * 1024 //128Mo + littleSize = 1024 // 1ko + bigSize = 128 * 1024 * 1024 // 128Mo ) func TestGit(t *testing.T) { @@ -89,15 +89,15 @@ func testGit(t *testing.T, u *url.URL) { t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, models.AccessModeRead)) t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username)) - //Setup key the user ssh key + // Setup key the user ssh key withKeyFile(t, keyname, func(keyFile string) { t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile)) - //Setup remote link - //TODO: get url from api + // Setup remote link + // TODO: get url from api sshURL := createSSHUrl(sshContext.GitPath(), u) - //Setup clone folder + // Setup clone folder dstPath, err := ioutil.TempDir("", sshContext.Reponame) assert.NoError(t, err) defer util.RemoveAll(dstPath) @@ -127,7 +127,6 @@ func ensureAnonymousClone(t *testing.T, u *url.URL) { assert.NoError(t, err) defer util.RemoveAll(dstLocalPath) t.Run("CloneAnonymous", doGitClone(dstLocalPath, u)) - } func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) { @@ -292,13 +291,13 @@ func lockFileTest(t *testing.T, filename, repoPath string) { func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string { name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix) assert.NoError(t, err) - _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) //Push + _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) // Push assert.NoError(t, err) return name } func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) { - //Generate random file + // Generate random file bufSize := 4 * 1024 if bufSize > size { bufSize = size @@ -331,7 +330,7 @@ func generateCommitWithNewData(size int, repoPath, email, fullName, prefix strin return "", err } - //Commit + // Commit // Now here we should explicitly allow lfs filters to run globalArgs := allowLFSFilters() err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name())) @@ -402,7 +401,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes } } -func doProtectBranch(ctx APITestContext, branch string, userToWhitelist string) func(t *testing.T) { +func doProtectBranch(ctx APITestContext, branch, userToWhitelist string) func(t *testing.T) { // We are going to just use the owner to set the protection. return func(t *testing.T) { csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/settings/branches", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame))) diff --git a/integrations/gpg_git_test.go b/integrations/gpg_git_test.go index 8c78faf7d23c1..2fc7a2549cf72 100644 --- a/integrations/gpg_git_test.go +++ b/integrations/gpg_git_test.go @@ -31,7 +31,7 @@ func TestGPGGit(t *testing.T) { assert.NoError(t, err) defer util.RemoveAll(tmpDir) - err = os.Chmod(tmpDir, 0700) + err = os.Chmod(tmpDir, 0o700) assert.NoError(t, err) oldGNUPGHome := os.Getenv("GNUPGHOME") @@ -256,7 +256,6 @@ func TestGPGGit(t *testing.T) { } assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email) })) - }) }, false) var pr api.PullRequest @@ -320,7 +319,6 @@ func TestGPGGit(t *testing.T) { assert.NotNil(t, branch.Commit.Verification) assert.True(t, branch.Commit.Verification.Verified) })) - }) }, false) } diff --git a/integrations/integration_test.go b/integrations/integration_test.go index 10331a1560f70..bdacba510962e 100644 --- a/integrations/integration_test.go +++ b/integrations/integration_test.go @@ -332,7 +332,7 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession return session } -//token has to be unique this counter take care of +// token has to be unique this counter take care of var tokenCounter int64 func getTokenForLoggedInUser(t testing.TB, session *TestSession) string { diff --git a/integrations/issue_test.go b/integrations/issue_test.go index 9b1447bd8de92..72cb5696cd73f 100644 --- a/integrations/issue_test.go +++ b/integrations/issue_test.go @@ -118,7 +118,6 @@ func TestNoLoginViewIssue(t *testing.T) { } func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content string) string { - req := NewRequest(t, "GET", path.Join(user, repo, "issues", "new")) resp := session.MakeRequest(t, req, http.StatusOK) @@ -146,7 +145,6 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content } func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content, status string) int64 { - req := NewRequest(t, "GET", issueURL) resp := session.MakeRequest(t, req, http.StatusOK) @@ -241,7 +239,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNone}) + RefAction: references.XRefActionNone, + }) // Edit title, neuter ref testIssueChangeInfo(t, "user2", issueRefURL, "title", "Title no ref") @@ -251,7 +250,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNeutered}) + RefAction: references.XRefActionNeutered, + }) // Ref from issue content issueRefURL, issueRef = testIssueWithBean(t, "user2", 1, "TitleXRef", fmt.Sprintf("Description ref #%d", issueBase.Index)) @@ -261,7 +261,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNone}) + RefAction: references.XRefActionNone, + }) // Edit content, neuter ref testIssueChangeInfo(t, "user2", issueRefURL, "content", "Description no ref") @@ -271,7 +272,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNeutered}) + RefAction: references.XRefActionNeutered, + }) // Ref from a comment session := loginUser(t, "user2") @@ -282,7 +284,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: commentID, RefIsPull: false, - RefAction: references.XRefActionNone} + RefAction: references.XRefActionNone, + } models.AssertExistsAndLoadBean(t, comment) // Ref from a different repository @@ -293,7 +296,8 @@ func TestIssueCrossReference(t *testing.T) { RefIssueID: issueRef.ID, RefCommentID: 0, RefIsPull: false, - RefAction: references.XRefActionNone}) + RefAction: references.XRefActionNone, + }) } func testIssueWithBean(t *testing.T, user string, repoID int64, title, content string) (string, *models.Issue) { @@ -307,7 +311,7 @@ func testIssueWithBean(t *testing.T, user string, repoID int64, title, content s return issueURL, issue } -func testIssueChangeInfo(t *testing.T, user, issueURL, info string, value string) { +func testIssueChangeInfo(t *testing.T, user, issueURL, info, value string) { session := loginUser(t, user) req := NewRequest(t, "GET", issueURL) diff --git a/integrations/links_test.go b/integrations/links_test.go index e16b688c8de3b..7eb16810d7bf0 100644 --- a/integrations/links_test.go +++ b/integrations/links_test.go @@ -20,7 +20,7 @@ import ( func TestLinksNoLogin(t *testing.T) { defer prepareTestEnv(t)() - var links = []string{ + links := []string{ "/explore/repos", "/explore/repos?q=test&tab=", "/explore/users", @@ -46,7 +46,7 @@ func TestLinksNoLogin(t *testing.T) { func TestRedirectsNoLogin(t *testing.T) { defer prepareTestEnv(t)() - var redirects = map[string]string{ + redirects := map[string]string{ "/user2/repo1/commits/master": "/user2/repo1/commits/branch/master", "/user2/repo1/src/master": "/user2/repo1/src/branch/master", "/user2/repo1/src/master/file.txt": "/user2/repo1/src/branch/master/file.txt", @@ -64,7 +64,7 @@ func TestRedirectsNoLogin(t *testing.T) { func TestNoLoginNotExist(t *testing.T) { defer prepareTestEnv(t)() - var links = []string{ + links := []string{ "/user5/repo4/projects", "/user5/repo4/projects/3", } @@ -76,7 +76,7 @@ func TestNoLoginNotExist(t *testing.T) { } func testLinksAsUser(userName string, t *testing.T) { - var links = []string{ + links := []string{ "/explore/repos", "/explore/repos?q=test&tab=", "/explore/users", @@ -135,7 +135,7 @@ func testLinksAsUser(userName string, t *testing.T) { var apiRepos []*api.Repository DecodeJSON(t, respAPI, &apiRepos) - var repoLinks = []string{ + repoLinks := []string{ "", "/issues", "/pulls", diff --git a/integrations/migration-test/migration_test.go b/integrations/migration-test/migration_test.go index 852c0b737c2da..f88de53e5d377 100644 --- a/integrations/migration-test/migration_test.go +++ b/integrations/migration-test/migration_test.go @@ -295,6 +295,5 @@ func TestMigrations(t *testing.T) { t.Run(fmt.Sprintf("Migrate-%s-%s", dialect, version), func(t *testing.T) { doMigrationTest(t, version) }) - } } diff --git a/integrations/nonascii_branches_test.go b/integrations/nonascii_branches_test.go index 22d71e6ee20e1..6c0042df8a01f 100644 --- a/integrations/nonascii_branches_test.go +++ b/integrations/nonascii_branches_test.go @@ -174,5 +174,4 @@ func TestNonasciiBranches(t *testing.T) { } setDefaultBranch(t, session, user, repo, "master") - } diff --git a/integrations/privateactivity_test.go b/integrations/privateactivity_test.go index 23c6a7e8ccf4e..b9d3dcab97fac 100644 --- a/integrations/privateactivity_test.go +++ b/integrations/privateactivity_test.go @@ -15,8 +15,10 @@ import ( "github.com/stretchr/testify/assert" ) -const privateActivityTestAdmin = "user1" -const privateActivityTestUser = "user2" +const ( + privateActivityTestAdmin = "user1" + privateActivityTestUser = "user2" +) // user3 is an organization so it is not usable here const privateActivityTestOtherUser = "user4" diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go index 79f62c32c10f8..b12ac044d4f78 100644 --- a/integrations/pull_merge_test.go +++ b/integrations/pull_merge_test.go @@ -61,7 +61,7 @@ func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum str func TestPullMerge(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := models.HookTasks(1, 1) //Retrieve previous hook number + hookTasks, err := models.HookTasks(1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -83,7 +83,7 @@ func TestPullMerge(t *testing.T) { func TestPullRebase(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := models.HookTasks(1, 1) //Retrieve previous hook number + hookTasks, err := models.HookTasks(1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -105,7 +105,7 @@ func TestPullRebase(t *testing.T) { func TestPullRebaseMerge(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := models.HookTasks(1, 1) //Retrieve previous hook number + hookTasks, err := models.HookTasks(1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -127,7 +127,7 @@ func TestPullRebaseMerge(t *testing.T) { func TestPullSquash(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := models.HookTasks(1, 1) //Retrieve previous hook number + hookTasks, err := models.HookTasks(1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) diff --git a/integrations/pull_update_test.go b/integrations/pull_update_test.go index 2dc966316e6c0..df8e388e68566 100644 --- a/integrations/pull_update_test.go +++ b/integrations/pull_update_test.go @@ -21,12 +21,12 @@ import ( func TestAPIPullUpdate(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - //Create PR to test + // Create PR to test user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) org26 := models.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User) pr := createOutdatedPR(t, user, org26) - //Test GetDiverging + // Test GetDiverging diffCount, err := pull_service.GetDiverging(pr) assert.NoError(t, err) assert.EqualValues(t, 1, diffCount.Behind) @@ -39,7 +39,7 @@ func TestAPIPullUpdate(t *testing.T) { req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) session.MakeRequest(t, req, http.StatusOK) - //Test GetDiverging after update + // Test GetDiverging after update diffCount, err = pull_service.GetDiverging(pr) assert.NoError(t, err) assert.EqualValues(t, 0, diffCount.Behind) @@ -64,7 +64,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *models.User) *models.PullReq assert.NoError(t, err) assert.NotEmpty(t, headRepo) - //create a commit on base Repo + // create a commit on base Repo _, err = repofiles.CreateOrUpdateRepoFile(baseRepo, actor, &repofiles.UpdateRepoFileOptions{ TreePath: "File_A", Message: "Add File A", @@ -87,7 +87,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *models.User) *models.PullReq }) assert.NoError(t, err) - //create a commit on head Repo + // create a commit on head Repo _, err = repofiles.CreateOrUpdateRepoFile(headRepo, actor, &repofiles.UpdateRepoFileOptions{ TreePath: "File_B", Message: "Add File on PR branch", @@ -110,7 +110,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *models.User) *models.PullReq }) assert.NoError(t, err) - //create Pull + // create Pull pullIssue := &models.Issue{ RepoID: baseRepo.ID, Title: "Test Pull -to-update-", diff --git a/integrations/repo_activity_test.go b/integrations/repo_activity_test.go index 56b70c9595dc4..e711fbe8e0fc4 100644 --- a/integrations/repo_activity_test.go +++ b/integrations/repo_activity_test.go @@ -18,7 +18,6 @@ import ( func TestRepoActivity(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - session := loginUser(t, "user1") // Create PRs (1 merged & 2 proposed) diff --git a/integrations/repo_commits_test.go b/integrations/repo_commits_test.go index 042849db7cf5b..94657cceb57ce 100644 --- a/integrations/repo_commits_test.go +++ b/integrations/repo_commits_test.go @@ -71,10 +71,10 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) { assert.True(t, sel.HasClass(class)) } - //By SHA + // By SHA req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/statuses") testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), state) - //By Ref + // By Ref req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/statuses") testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), state) req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/v1.1/statuses") diff --git a/integrations/repofiles_update_test.go b/integrations/repofiles_update_test.go index 9e99b36ae4226..b8abede75102f 100644 --- a/integrations/repofiles_update_test.go +++ b/integrations/repofiles_update_test.go @@ -399,7 +399,7 @@ func TestCreateOrUpdateRepoFileErrors(t *testing.T) { t.Run("create file that already exists", func(t *testing.T) { opts := getCreateRepoFileOptions(repo) - opts.TreePath = "README.md" //already exists + opts.TreePath = "README.md" // already exists fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts) assert.Nil(t, fileResponse) assert.Error(t, err) diff --git a/integrations/setting_test.go b/integrations/setting_test.go index eb495acb24454..c0455a452023c 100644 --- a/integrations/setting_test.go +++ b/integrations/setting_test.go @@ -77,7 +77,6 @@ func TestSettingShowUserEmailProfile(t *testing.T) { htmlDoc.doc.Find(".user.profile").Text(), "user2@example.com", ) - } func TestSettingLandingPage(t *testing.T) { diff --git a/integrations/ssh_key_test.go b/integrations/ssh_key_test.go index 91774f633594c..f53589f0cc2d6 100644 --- a/integrations/ssh_key_test.go +++ b/integrations/ssh_key_test.go @@ -28,7 +28,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, ioutil.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0644)) + assert.NoError(t, ioutil.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, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@example.com", @@ -67,7 +67,7 @@ func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) { t.Run("InitTestRepository", doGitInitTestRepository(dstPath)) - //Setup remote link + // Setup remote link sshURL := createSSHUrl(ctx.GitPath(), u) t.Run("AddRemote", doGitAddRemote(dstPath, "origin", sshURL)) diff --git a/integrations/testlogger.go b/integrations/testlogger.go index 9ea357ba27bfc..86fdef36736ea 100644 --- a/integrations/testlogger.go +++ b/integrations/testlogger.go @@ -171,7 +171,7 @@ func (log *TestLogger) Init(config string) error { func (log *TestLogger) Flush() { } -//ReleaseReopen does nothing +// ReleaseReopen does nothing func (log *TestLogger) ReleaseReopen() error { return nil } diff --git a/integrations/timetracking_test.go b/integrations/timetracking_test.go index 7cf5f9bc8f0eb..17e9174e5d91e 100644 --- a/integrations/timetracking_test.go +++ b/integrations/timetracking_test.go @@ -19,15 +19,16 @@ func TestViewTimetrackingControls(t *testing.T) { defer prepareTestEnv(t)() session := loginUser(t, "user2") testViewTimetrackingControls(t, session, "user2", "repo1", "1", true) - //user2/repo1 + // user2/repo1 } func TestNotViewTimetrackingControls(t *testing.T) { defer prepareTestEnv(t)() session := loginUser(t, "user5") testViewTimetrackingControls(t, session, "user2", "repo1", "1", false) - //user2/repo1 + // user2/repo1 } + func TestViewTimetrackingControlsDisabled(t *testing.T) { defer prepareTestEnv(t)() session := loginUser(t, "user2") diff --git a/integrations/user_test.go b/integrations/user_test.go index 199d5e242f822..9d9dbeaedab42 100644 --- a/integrations/user_test.go +++ b/integrations/user_test.go @@ -118,15 +118,15 @@ func TestRenameReservedUsername(t *testing.T) { func TestExportUserGPGKeys(t *testing.T) { defer prepareTestEnv(t)() - //Export empty key list + // Export empty key list testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK----- =twTO -----END PGP PUBLIC KEY BLOCK----- `) - //Import key - //User1 + // Import key + // User1 session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK----- @@ -160,7 +160,7 @@ GrE0MHOxUbc9tbtyk0F1SuzREUBH =DDXw -----END PGP PUBLIC KEY BLOCK----- `) - //Export new key + // Export new key testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK----- xsBNBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo @@ -199,6 +199,6 @@ func testExportUserGPGKeys(t *testing.T, user, expected string) { t.Logf("Testing username %s export gpg keys", user) req := NewRequest(t, "GET", "/"+user+".gpg") resp := session.MakeRequest(t, req, http.StatusOK) - //t.Log(resp.Body.String()) + // t.Log(resp.Body.String()) assert.Equal(t, expected, resp.Body.String()) } diff --git a/main.go b/main.go index 6cbdc244018b4..19b9dd63275fc 100644 --- a/main.go +++ b/main.go @@ -186,7 +186,7 @@ DEFAULT CONFIGURATION: } func formatBuiltWith() string { - var version = runtime.Version() + version := runtime.Version() if len(MakeVersion) > 0 { version = MakeVersion + ", " + runtime.Version() } diff --git a/models/consistency.go b/models/consistency.go index 9d76d26bbb64b..60106bf53a6eb 100644 --- a/models/consistency.go +++ b/models/consistency.go @@ -386,7 +386,6 @@ func FixIssueLabelWithOutsideLabels() (int64, error) { WHERE issue.repo_id != label.repo_id OR (label.repo_id = 0 AND label.org_id != repository.owner_id) ) AS il_too )`) - if err != nil { return 0, err } diff --git a/modules/auth/ldap/ldap.go b/modules/auth/ldap/ldap.go index 6c557de018c4b..0f440f6ac9c5d 100644 --- a/modules/auth/ldap/ldap.go +++ b/modules/auth/ldap/ldap.go @@ -304,7 +304,7 @@ func (ls *Source) SearchEntry(name, passwd string, directBind bool) *SearchResul return nil } - var isAttributeSSHPublicKeySet = len(strings.TrimSpace(ls.AttributeSSHPublicKey)) > 0 + isAttributeSSHPublicKeySet := len(strings.TrimSpace(ls.AttributeSSHPublicKey)) > 0 attribs := []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail} if len(strings.TrimSpace(ls.UserUID)) > 0 { @@ -440,7 +440,7 @@ func (ls *Source) SearchEntries() ([]*SearchResult, error) { userFilter := fmt.Sprintf(ls.Filter, "*") - var isAttributeSSHPublicKeySet = len(strings.TrimSpace(ls.AttributeSSHPublicKey)) > 0 + isAttributeSSHPublicKeySet := len(strings.TrimSpace(ls.AttributeSSHPublicKey)) > 0 attribs := []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail} if isAttributeSSHPublicKeySet { diff --git a/modules/auth/oauth2/oauth2.go b/modules/auth/oauth2/oauth2.go index e2c97b72f31d2..67f195843f2fa 100644 --- a/modules/auth/oauth2/oauth2.go +++ b/modules/auth/oauth2/oauth2.go @@ -49,7 +49,6 @@ func Init(x *xorm.Engine) error { store, err := xormstore.NewOptions(x, xormstore.Options{ TableName: "oauth2_session", }, []byte(sessionUsersStoreKey)) - if err != nil { return err } @@ -80,7 +79,7 @@ func Auth(provider string, request *http.Request, response http.ResponseWriter) // don't use the default gothic begin handler to prevent issues when some error occurs // normally the gothic library will write some custom stuff to the response instead of our own nice error page - //gothic.BeginAuthHandler(response, request) + // gothic.BeginAuthHandler(response, request) url, err := gothic.GetAuthURL(response, request) if err == nil { diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go index 931e5c7945e33..28546f603183f 100644 --- a/modules/auth/openid/discovery_cache_test.go +++ b/modules/auth/openid/discovery_cache_test.go @@ -14,9 +14,11 @@ type testDiscoveredInfo struct{} func (s *testDiscoveredInfo) ClaimedID() string { return "claimedID" } + func (s *testDiscoveredInfo) OpEndpoint() string { return "opEndpoint" } + func (s *testDiscoveredInfo) OpLocalID() string { return "opLocalID" } @@ -25,7 +27,7 @@ func TestTimedDiscoveryCache(t *testing.T) { dc := newTimedDiscoveryCache(1 * time.Second) // Put some initial values - dc.Put("foo", &testDiscoveredInfo{}) //openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"}) + dc.Put("foo", &testDiscoveredInfo{}) // openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"}) // Make sure we can retrieve them if di := dc.Get("foo"); di == nil { diff --git a/modules/auth/openid/openid.go b/modules/auth/openid/openid.go index 40f38c2d2e716..8926fc6d7a20f 100644 --- a/modules/auth/openid/openid.go +++ b/modules/auth/openid/openid.go @@ -17,8 +17,10 @@ import ( // If you have multiple servers for example, you may need to share at // least // the nonceStore between them. -var nonceStore = openid.NewSimpleNonceStore() -var discoveryCache = newTimedDiscoveryCache(24 * time.Hour) +var ( + nonceStore = openid.NewSimpleNonceStore() + discoveryCache = newTimedDiscoveryCache(24 * time.Hour) +) // Verify handles response from OpenID provider func Verify(fullURL string) (id string, err error) { diff --git a/modules/auth/pam/pam.go b/modules/auth/pam/pam.go index f21602c6b5663..a73e060694dd1 100644 --- a/modules/auth/pam/pam.go +++ b/modules/auth/pam/pam.go @@ -26,7 +26,6 @@ func Auth(serviceName, userName, passwd string) (string, error) { } return "", errors.New("Unrecognized PAM message style") }) - if err != nil { return "", err } diff --git a/modules/auth/sso/basic.go b/modules/auth/sso/basic.go index d2d25c6cece65..9e1787dccdf6a 100644 --- a/modules/auth/sso/basic.go +++ b/modules/auth/sso/basic.go @@ -24,8 +24,7 @@ var ( // Basic implements the SingleSignOn interface and authenticates requests (API requests // only) by looking for Basic authentication data or "x-oauth-basic" token in the "Authorization" // header. -type Basic struct { -} +type Basic struct{} // Init does nothing as the Basic implementation does not need to allocate any resources func (b *Basic) Init() error { diff --git a/modules/auth/sso/oauth2.go b/modules/auth/sso/oauth2.go index fcd6845b38cc4..14f128979bf5a 100644 --- a/modules/auth/sso/oauth2.go +++ b/modules/auth/sso/oauth2.go @@ -48,8 +48,7 @@ func CheckOAuthAccessToken(accessToken string) int64 { // OAuth2 implements the SingleSignOn interface and authenticates requests // (API requests only) by looking for an OAuth token in query parameters or the // "Authorization" header. -type OAuth2 struct { -} +type OAuth2 struct{} // Init does nothing as the OAuth2 implementation does not need to allocate any resources func (o *OAuth2) Init() error { diff --git a/modules/auth/sso/reverseproxy.go b/modules/auth/sso/reverseproxy.go index ca9450e71429d..f7ef08b133e77 100644 --- a/modules/auth/sso/reverseproxy.go +++ b/modules/auth/sso/reverseproxy.go @@ -26,8 +26,7 @@ var ( // On successful authentication the proxy is expected to populate the username in the // "setting.ReverseProxyAuthUser" header. Optionally it can also populate the email of the // user in the "setting.ReverseProxyAuthEmail" header. -type ReverseProxy struct { -} +type ReverseProxy struct{} // getUserName extracts the username from the "setting.ReverseProxyAuthUser" header func (r *ReverseProxy) getUserName(req *http.Request) string { diff --git a/modules/auth/sso/session.go b/modules/auth/sso/session.go index 7a546577d86ee..453159863769c 100644 --- a/modules/auth/sso/session.go +++ b/modules/auth/sso/session.go @@ -17,8 +17,7 @@ var ( // Session checks if there is a user uid stored in the session and returns the user // object for that uid. -type Session struct { -} +type Session struct{} // Init does nothing as the Session implementation does not need to allocate any resources func (s *Session) Init() error { diff --git a/modules/avatar/avatar_test.go b/modules/avatar/avatar_test.go index 85356056529a4..b492109fc48ed 100644 --- a/modules/avatar/avatar_test.go +++ b/modules/avatar/avatar_test.go @@ -56,6 +56,7 @@ func Test_PrepareWithInvalidImage(t *testing.T) { _, err := Prepare([]byte{}) assert.EqualError(t, err, "DecodeConfig: image: unknown format") } + func Test_PrepareWithInvalidImageSize(t *testing.T) { setting.Avatar.MaxWidth = 5 setting.Avatar.MaxHeight = 5 diff --git a/modules/base/tool.go b/modules/base/tool.go index d721d47e9d773..137ac69c9eef4 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -35,8 +35,10 @@ const sniffLen = 512 // SVGMimeType MIME type of SVG images. const SVGMimeType = "image/svg+xml" -var svgTagRegex = regexp.MustCompile(`(?si)\A\s*(?:(||>))\s*)*\/]`) -var svgTagInXMLRegex = regexp.MustCompile(`(?si)\A<\?xml\b.*?\?>\s*(?:(||>))\s*)*\/]`) +var ( + svgTagRegex = regexp.MustCompile(`(?si)\A\s*(?:(||>))\s*)*\/]`) + svgTagInXMLRegex = regexp.MustCompile(`(?si)\A<\?xml\b.*?\?>\s*(?:(||>))\s*)*\/]`) +) // EncodeMD5 encodes string to md5 hex value. func EncodeMD5(str string) string { @@ -159,10 +161,10 @@ func PrettyNumber(v int64) string { } // Subtract deals with subtraction of all types of number. -func Subtract(left interface{}, right interface{}) interface{} { +func Subtract(left, right interface{}) interface{} { var rleft, rright int64 var fleft, fright float64 - var isInt = true + isInt := true switch v := left.(type) { case int: rleft = int64(v) diff --git a/modules/cache/cache.go b/modules/cache/cache.go index 3a2732c34366e..c89fa72d4b0c9 100644 --- a/modules/cache/cache.go +++ b/modules/cache/cache.go @@ -15,9 +15,7 @@ import ( _ "gitea.com/go-chi/cache/memcache" // memcache plugin for cache ) -var ( - conn mc.Cache -) +var conn mc.Cache func newCache(cacheConfig setting.Cache) (mc.Cache, error) { return mc.NewCacher(mc.Options{ diff --git a/modules/cache/cache_test.go b/modules/cache/cache_test.go index 92be69252dd58..f418f77e46ea8 100644 --- a/modules/cache/cache_test.go +++ b/modules/cache/cache_test.go @@ -113,6 +113,7 @@ func TestGetInt(t *testing.T) { // TODO: uncommented code works in IDE but not with go test } + func TestGetInt64(t *testing.T) { createTestCache() diff --git a/modules/charset/charset_test.go b/modules/charset/charset_test.go index 33f0c10a7a201..8376a0698af8a 100644 --- a/modules/charset/charset_test.go +++ b/modules/charset/charset_test.go @@ -56,36 +56,48 @@ func TestToUTF8WithErr(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // "áéíóú" - res, err = ToUTF8WithErr([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, - 0xc3, 0xba}) + res, err = ToUTF8WithErr([]byte{ + 0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, + 0xc3, 0xba, + }) assert.NoError(t, err) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) // Japanese (Shift-JIS) // 日属秘ぞしちゅ。 - res, err = ToUTF8WithErr([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, - 0xBF, 0x82, 0xE3, 0x81, 0x42}) + res, err = ToUTF8WithErr([]byte{ + 0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, + 0xBF, 0x82, 0xE3, 0x81, 0x42, + }) assert.NoError(t, err) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, []byte(res)) res, err = ToUTF8WithErr([]byte{0x00, 0x00, 0x00, 0x00}) @@ -108,10 +120,14 @@ func TestToUTF8WithFallback(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res) // "Hola, así cómo ños" - res = ToUTF8WithFallback([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73}) - assert.Equal(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, - 0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73}, res) + res = ToUTF8WithFallback([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, + }) + assert.Equal(t, []byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, + 0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73, + }, res) // "Hola, así cómo " minmatch := []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, 0xC3, 0xB3, 0x6D, 0x6F, 0x20} @@ -127,8 +143,10 @@ func TestToUTF8WithFallback(t *testing.T) { // Japanese (Shift-JIS) // "日属秘ぞしちゅ。" res = ToUTF8WithFallback([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42}) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, res) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, res) res = ToUTF8WithFallback([]byte{0x00, 0x00, 0x00, 0x00}) assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res) @@ -148,21 +166,29 @@ func TestToUTF8(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // BOM + "áéíóú" - res = ToUTF8(string([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, - 0xc3, 0xba})) + res = ToUTF8(string([]byte{ + 0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, + 0xc3, 0xba, + })) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // Latin1 // Hola, así cómo ños - res = ToUTF8(string([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73})) - assert.Equal(t, []byte{0x48, 0x6f, 0x6c, 0x61, 0x2c, 0x20, 0x61, 0x73, 0xc3, 0xad, 0x20, 0x63, - 0xc3, 0xb3, 0x6d, 0x6f, 0x20, 0xc3, 0xb1, 0x6f, 0x73}, []byte(res)) + res = ToUTF8(string([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, + })) + assert.Equal(t, []byte{ + 0x48, 0x6f, 0x6c, 0x61, 0x2c, 0x20, 0x61, 0x73, 0xc3, 0xad, 0x20, 0x63, + 0xc3, 0xb3, 0x6d, 0x6f, 0x20, 0xc3, 0xb1, 0x6f, 0x73, + }, []byte(res)) // Latin1 // Hola, así cómo \x07ños - res = ToUTF8(string([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73})) + res = ToUTF8(string([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, + })) // Hola, bytesMustStartWith(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C}, []byte(res)) @@ -173,10 +199,14 @@ func TestToUTF8(t *testing.T) { // Japanese (Shift-JIS) // 日属秘ぞしちゅ。 - res = ToUTF8(string([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, - 0xBF, 0x82, 0xE3, 0x81, 0x42})) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, + res = ToUTF8(string([]byte{ + 0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, + 0xBF, 0x82, 0xE3, 0x81, 0x42, + })) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, []byte(res)) res = ToUTF8("\x00\x00\x00\x00") @@ -216,8 +246,10 @@ func TestToUTF8DropErrors(t *testing.T) { // Japanese (Shift-JIS) // "日属秘ぞしちゅ。" res = ToUTF8DropErrors([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42}) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, res) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, res) res = ToUTF8DropErrors([]byte{0x00, 0x00, 0x00, 0x00}) assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res) @@ -261,14 +293,14 @@ func TestDetectEncoding(t *testing.T) { assert.Error(t, err) } -func stringMustStartWith(t *testing.T, expected string, value string) { +func stringMustStartWith(t *testing.T, expected, value string) { assert.Equal(t, expected, string(value[:len(expected)])) } -func stringMustEndWith(t *testing.T, expected string, value string) { +func stringMustEndWith(t *testing.T, expected, value string) { assert.Equal(t, expected, string(value[len(value)-len(expected):])) } -func bytesMustStartWith(t *testing.T, expected []byte, value []byte) { +func bytesMustStartWith(t *testing.T, expected, value []byte) { assert.Equal(t, expected, value[:len(expected)]) } diff --git a/modules/context/api.go b/modules/context/api.go index 4757c2eeb463f..8aabab89245ae 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -50,29 +50,29 @@ type APIInvalidTopicsError struct { Message string `json:"message"` } -//APIEmpty is an empty response +// APIEmpty is an empty response // swagger:response empty type APIEmpty struct{} -//APIForbiddenError is a forbidden error response +// APIForbiddenError is a forbidden error response // swagger:response forbidden type APIForbiddenError struct { APIError } -//APINotFound is a not found empty response +// APINotFound is a not found empty response // swagger:response notFound type APINotFound struct{} -//APIConflict is a conflict empty response +// APIConflict is a conflict empty response // swagger:response conflict type APIConflict struct{} -//APIRedirect is a redirect response +// APIRedirect is a redirect response // swagger:response redirect type APIRedirect struct{} -//APIString is a string response +// APIString is a string response // swagger:response string type APIString string @@ -121,9 +121,7 @@ func (ctx *APIContext) InternalServerError(err error) { }) } -var ( - apiContextKey interface{} = "default_api_context" -) +var apiContextKey interface{} = "default_api_context" // WithAPIContext set up api context in request func WithAPIContext(req *http.Request, ctx *APIContext) *http.Request { @@ -219,13 +217,12 @@ func (ctx *APIContext) CheckForOTP() { // APIContexter returns apicontext as middleware func APIContexter() func(http.Handler) http.Handler { - var csrfOpts = getCsrfOpts() + csrfOpts := getCsrfOpts() return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var locale = middleware.Locale(w, req) - var ctx = APIContext{ + locale := middleware.Locale(w, req) + ctx := APIContext{ Context: &Context{ Resp: NewResponse(w), Data: map[string]interface{}{}, @@ -309,7 +306,7 @@ func ReferencesGitRepo(allowEmpty bool) func(http.Handler) http.Handler { // NotFound handles 404s for APIContext // String will replace message, errors will be added to a slice func (ctx *APIContext) NotFound(objs ...interface{}) { - var message = "Not Found" + message := "Not Found" var errors []string for _, obj := range objs { // Ignore nil diff --git a/modules/context/api_test.go b/modules/context/api_test.go index e7e3e230afecd..323fdbd2cc9bb 100644 --- a/modules/context/api_test.go +++ b/modules/context/api_test.go @@ -16,7 +16,7 @@ import ( func TestGenAPILinks(t *testing.T) { setting.AppURL = "http://localhost:3000/" - var kases = map[string][]string{ + kases := map[string][]string{ "api/v1/repos/jerrykan/example-repo/issues?state=all": { `; rel="next"`, `; rel="last"`, diff --git a/modules/context/captcha.go b/modules/context/captcha.go index b8540136a186d..6117d30713354 100644 --- a/modules/context/captcha.go +++ b/modules/context/captcha.go @@ -13,8 +13,10 @@ import ( "gitea.com/go-chi/captcha" ) -var imageCaptchaOnce sync.Once -var cpt *captcha.Captcha +var ( + imageCaptchaOnce sync.Once + cpt *captcha.Captcha +) // GetImageCaptcha returns global image captcha func GetImageCaptcha() *captcha.Captcha { diff --git a/modules/context/context.go b/modules/context/context.go index eecc81406d0e0..698b91fe68959 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -182,7 +182,7 @@ func (ctx *Context) RedirectToFirst(location ...string) { // HTML calls Context.HTML and converts template name to string. func (ctx *Context) HTML(status int, name base.TplName) { log.Debug("Template: %s", name) - var startTime = time.Now() + startTime := time.Now() ctx.Data["TmplLoadTimes"] = func() string { return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms" } @@ -198,7 +198,7 @@ func (ctx *Context) HTML(status int, name base.TplName) { // HTMLString render content to a string but not http.ResponseWriter func (ctx *Context) HTMLString(name string, data interface{}) (string, error) { var buf strings.Builder - var startTime = time.Now() + startTime := time.Now() ctx.Data["TmplLoadTimes"] = func() string { return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms" } @@ -359,7 +359,7 @@ func (ctx *Context) ServeFile(file string, names ...string) { // Error returned an error to web browser func (ctx *Context) Error(status int, contents ...string) { - var v = http.StatusText(status) + v := http.StatusText(status) if len(contents) > 0 { v = contents[0] } @@ -570,15 +570,15 @@ func getCsrfOpts() CsrfOptions { // Contexter initializes a classic context for a request. func Contexter() func(next http.Handler) http.Handler { - var rnd = templates.HTMLRenderer() - var csrfOpts = getCsrfOpts() + rnd := templates.HTMLRenderer() + csrfOpts := getCsrfOpts() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - var locale = middleware.Locale(resp, req) - var startTime = time.Now() - var link = setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/") - var ctx = Context{ + locale := middleware.Locale(resp, req) + startTime := time.Now() + link := setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/") + ctx := Context{ Resp: NewResponse(resp), Cache: mc.GetCache(), Locale: locale, diff --git a/modules/context/csrf.go b/modules/context/csrf.go index ba0e9f6cde773..8ec36b521f4a9 100644 --- a/modules/context/csrf.go +++ b/modules/context/csrf.go @@ -56,9 +56,9 @@ type csrf struct { Form string // Cookie name value for setting and getting csrf token. Cookie string - //Cookie domain + // Cookie domain CookieDomain string - //Cookie path + // Cookie path CookiePath string // Cookie HttpOnly flag value used for the csrf token. CookieHTTPOnly bool diff --git a/modules/context/pagination.go b/modules/context/pagination.go index b678fccd1558a..107cbf618637c 100644 --- a/modules/context/pagination.go +++ b/modules/context/pagination.go @@ -20,14 +20,14 @@ type Pagination struct { } // NewPagination creates a new instance of the Pagination struct -func NewPagination(total int, page int, issueNum int, numPages int) *Pagination { +func NewPagination(total, page, issueNum, numPages int) *Pagination { p := &Pagination{} p.Paginater = paginater.New(total, page, issueNum, numPages) return p } // AddParam adds a value from context identified by ctxKey as link param under a given paramKey -func (p *Pagination) AddParam(ctx *Context, paramKey string, ctxKey string) { +func (p *Pagination) AddParam(ctx *Context, paramKey, ctxKey string) { _, exists := ctx.Data[ctxKey] if !exists { return @@ -38,7 +38,7 @@ func (p *Pagination) AddParam(ctx *Context, paramKey string, ctxKey string) { } // AddParamString adds a string parameter directly -func (p *Pagination) AddParamString(key string, value string) { +func (p *Pagination) AddParamString(key, value string) { urlParam := fmt.Sprintf("%s=%v", url.QueryEscape(key), url.QueryEscape(value)) p.urlParams = append(p.urlParams, urlParam) } diff --git a/modules/context/private.go b/modules/context/private.go index dfefa1d2f0192..5d3d639f32f13 100644 --- a/modules/context/private.go +++ b/modules/context/private.go @@ -14,9 +14,7 @@ type PrivateContext struct { *Context } -var ( - privateContextKey interface{} = "default_private_context" -) +var privateContextKey interface{} = "default_private_context" // WithPrivateContext set up private context in request func WithPrivateContext(req *http.Request, ctx *PrivateContext) *http.Request { diff --git a/modules/context/repo.go b/modules/context/repo.go index ba3cfe9bf256a..b8b5ac70338ac 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -104,7 +104,6 @@ type CanCommitToBranchResults struct { // and branch is not protected for push func (r *Repository) CanCommitToBranch(doer *models.User) (CanCommitToBranchResults, error) { protectedBranch, err := models.GetProtectedBranchBy(r.Repository.ID, r.BranchName) - if err != nil { return CanCommitToBranchResults{}, err } @@ -173,7 +172,7 @@ func (r *Repository) GetCommitsCount() (int64, error) { } // GetCommitGraphsCount returns cached commit count for current view -func (r *Repository) GetCommitGraphsCount(hidePRRefs bool, branches []string, files []string) (int64, error) { +func (r *Repository) GetCommitGraphsCount(hidePRRefs bool, branches, files []string) (int64, error) { cacheKey := fmt.Sprintf("commits-count-%d-graph-%t-%s-%s", r.Repository.ID, hidePRRefs, branches, files) return cache.GetInt64(cacheKey, func() (int64, error) { @@ -199,7 +198,7 @@ func (r *Repository) BranchNameSubURL() string { } // FileExists returns true if a file exists in the given repo branch -func (r *Repository) FileExists(path string, branch string) (bool, error) { +func (r *Repository) FileExists(path, branch string) (bool, error) { if branch == "" { branch = r.Repository.DefaultBranch } diff --git a/modules/context/response.go b/modules/context/response.go index bdbbb97af78ba..826c72d72b9c4 100644 --- a/modules/context/response.go +++ b/modules/context/response.go @@ -15,9 +15,7 @@ type ResponseWriter interface { Size() int } -var ( - _ ResponseWriter = &Response{} -) +var _ ResponseWriter = &Response{} // Response represents a response type Response struct { diff --git a/modules/context/secret.go b/modules/context/secret.go index fcb488d211a0a..cacc9a4db142b 100644 --- a/modules/context/secret.go +++ b/modules/context/secret.go @@ -75,7 +75,7 @@ func AesDecrypt(key, text []byte) ([]byte, error) { } // EncryptSecret encrypts a string with given key into a hex string -func EncryptSecret(key string, str string) (string, error) { +func EncryptSecret(key, str string) (string, error) { keyHash := sha256.Sum256([]byte(key)) plaintext := []byte(str) ciphertext, err := AesEncrypt(keyHash[:], plaintext) @@ -86,7 +86,7 @@ func EncryptSecret(key string, str string) (string, error) { } // DecryptSecret decrypts a previously encrypted hex string -func DecryptSecret(key string, cipherhex string) (string, error) { +func DecryptSecret(key, cipherhex string) (string, error) { keyHash := sha256.Sum256([]byte(key)) ciphertext, err := base64.StdEncoding.DecodeString(cipherhex) if err != nil { diff --git a/modules/convert/git_commit.go b/modules/convert/git_commit.go index 4e30ec2c0b334..86f49ad91337a 100644 --- a/modules/convert/git_commit.go +++ b/modules/convert/git_commit.go @@ -71,7 +71,6 @@ func ToPayloadCommit(repo *models.Repository, c *git.Commit) *api.PayloadCommit // ToCommit convert a git.Commit to api.Commit func ToCommit(repo *models.Repository, commit *git.Commit, userCache map[string]*models.User) (*api.Commit, error) { - var apiAuthor, apiCommitter *api.User // Retrieve author and committer information diff --git a/modules/convert/notification.go b/modules/convert/notification.go index 49abe01253246..188d0c046f19d 100644 --- a/modules/convert/notification.go +++ b/modules/convert/notification.go @@ -19,12 +19,12 @@ func ToNotificationThread(n *models.Notification) *api.NotificationThread { URL: n.APIURL(), } - //since user only get notifications when he has access to use minimal access mode + // since user only get notifications when he has access to use minimal access mode if n.Repository != nil { result.Repository = ToRepo(n.Repository, models.AccessModeRead) } - //handle Subject + // handle Subject switch n.Source { case models.NotificationSourceIssue: result.Subject = &api.NotificationSubject{Type: "Issue"} @@ -67,7 +67,7 @@ func ToNotificationThread(n *models.Notification) *api.NotificationThread { // ToNotifications convert list of Notification to api.NotificationThread list func ToNotifications(nl models.NotificationList) []*api.NotificationThread { - var result = make([]*api.NotificationThread, 0, len(nl)) + result := make([]*api.NotificationThread, 0, len(nl)) for _, n := range nl { result = append(result, ToNotificationThread(n)) } diff --git a/modules/convert/pull_test.go b/modules/convert/pull_test.go index adf42d8ca4421..a3d29633d7eeb 100644 --- a/modules/convert/pull_test.go +++ b/modules/convert/pull_test.go @@ -14,7 +14,7 @@ import ( ) func TestPullRequest_APIFormat(t *testing.T) { - //with HeadRepo + // with HeadRepo assert.NoError(t, models.PrepareTestDatabase()) headRepo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) pr := models.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) @@ -30,7 +30,7 @@ func TestPullRequest_APIFormat(t *testing.T) { Repository: ToRepo(headRepo, models.AccessModeNone), }, apiPullRequest.Head) - //withOut HeadRepo + // withOut HeadRepo pr = models.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) assert.NoError(t, pr.LoadIssue()) assert.NoError(t, pr.LoadAttributes()) diff --git a/modules/convert/repository.go b/modules/convert/repository.go index 813201ca6844c..4b414df47b0c8 100644 --- a/modules/convert/repository.go +++ b/modules/convert/repository.go @@ -33,7 +33,7 @@ func innerToRepo(repo *models.Repository, mode models.AccessMode, isParent bool) } } - //check enabled/disabled units + // check enabled/disabled units hasIssues := false var externalTracker *api.ExternalTracker var internalTracker *api.InternalTracker diff --git a/modules/convert/status.go b/modules/convert/status.go index f972fc333c133..cbb630d716576 100644 --- a/modules/convert/status.go +++ b/modules/convert/status.go @@ -32,7 +32,6 @@ func ToCommitStatus(status *models.CommitStatus) *api.CommitStatus { // ToCombinedStatus converts List of CommitStatus to a CombinedStatus func ToCombinedStatus(statuses []*models.CommitStatus, repo *api.Repository) *api.CombinedStatus { - if len(statuses) == 0 { return nil } diff --git a/modules/convert/user_test.go b/modules/convert/user_test.go index eff60d51830eb..cb0115a6e3fdf 100644 --- a/modules/convert/user_test.go +++ b/modules/convert/user_test.go @@ -12,7 +12,6 @@ import ( ) func TestUser_ToUser(t *testing.T) { - user1 := models.AssertExistsAndLoadBean(t, &models.User{ID: 1, IsAdmin: true}).(*models.User) apiUser := ToUser(user1, true, true) diff --git a/modules/cron/cron.go b/modules/cron/cron.go index ae309bd86692f..19f703caf1848 100644 --- a/modules/cron/cron.go +++ b/modules/cron/cron.go @@ -43,7 +43,6 @@ func NewContext() { started = false lock.Unlock() }) - } // TaskTableRow represents a task row in the tasks table diff --git a/modules/cron/tasks.go b/modules/cron/tasks.go index 6f3a96fd3f850..410d997703890 100644 --- a/modules/cron/tasks.go +++ b/modules/cron/tasks.go @@ -17,10 +17,12 @@ import ( "code.gitea.io/gitea/modules/setting" ) -var lock = sync.Mutex{} -var started = false -var tasks = []*Task{} -var tasksMap = map[string]*Task{} +var ( + lock = sync.Mutex{} + started = false + tasks = []*Task{} + tasksMap = map[string]*Task{} +) // Task represents a Cron task type Task struct { diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go index 0ca1e841eefd5..8f4aa56abfc17 100644 --- a/modules/doctor/misc.go +++ b/modules/doctor/misc.go @@ -108,7 +108,6 @@ func checkEnablePushOptions(logger log.Logger, autofix bool) error { logger.Info("Enabled push options for %d repositories.", numRepos) } else { logger.Info("Checked %d repositories, %d need updates.", numRepos, numNeedUpdate) - } return nil diff --git a/modules/doctor/paths.go b/modules/doctor/paths.go index 53409b5fa4dfd..252e365ca5b27 100644 --- a/modules/doctor/paths.go +++ b/modules/doctor/paths.go @@ -27,7 +27,7 @@ func checkConfigurationFile(logger log.Logger, autofix bool, fileOpts configurat fi, err := os.Stat(fileOpts.Path) if err != nil { if os.IsNotExist(err) && autofix && fileOpts.IsDirectory { - if err := os.MkdirAll(fileOpts.Path, 0777); err != nil { + if err := os.MkdirAll(fileOpts.Path, 0o777); err != nil { logger.Error(" Directory does not exist and could not be created. ERROR: %v", err) return fmt.Errorf("Configuration directory: \"%q\" does not exist and could not be created. ERROR: %v", fileOpts.Path, err) } diff --git a/modules/emoji/emoji.go b/modules/emoji/emoji.go index 01fb764ce368e..a940a8c6c79a2 100644 --- a/modules/emoji/emoji.go +++ b/modules/emoji/emoji.go @@ -43,9 +43,7 @@ var ( ) func loadMap() { - once.Do(func() { - // initialize codeMap = make(map[string]int, len(GemojiData)) aliasMap = make(map[string]int, len(GemojiData)) @@ -86,7 +84,6 @@ func loadMap() { codeReplacer = strings.NewReplacer(codePairs...) aliasReplacer = strings.NewReplacer(aliasPairs...) }) - } // FromCode retrieves the emoji data based on the provided unicode code (ie, diff --git a/modules/eventsource/event.go b/modules/eventsource/event.go index a3407a94d2124..19e9ea43e9a3d 100644 --- a/modules/eventsource/event.go +++ b/modules/eventsource/event.go @@ -14,7 +14,7 @@ import ( jsoniter "github.com/json-iterator/go" ) -func wrapNewlines(w io.Writer, prefix []byte, value []byte) (sum int64, err error) { +func wrapNewlines(w io.Writer, prefix, value []byte) (sum int64, err error) { if len(value) == 0 { return } diff --git a/modules/forms/repo_form_test.go b/modules/forms/repo_form_test.go index 4f65d59ca6d61..198437f7ea322 100644 --- a/modules/forms/repo_form_test.go +++ b/modules/forms/repo_form_test.go @@ -13,7 +13,6 @@ import ( ) func TestSubmitReviewForm_IsEmpty(t *testing.T) { - cases := []struct { form SubmitReviewForm expected bool @@ -43,7 +42,6 @@ func TestSubmitReviewForm_IsEmpty(t *testing.T) { } func TestIssueLock_HasValidReason(t *testing.T) { - // Init settings _ = setting.Repository diff --git a/modules/git/batch_reader.go b/modules/git/batch_reader.go index 6014508b9300e..31b514cc017cd 100644 --- a/modules/git/batch_reader.go +++ b/modules/git/batch_reader.go @@ -235,7 +235,6 @@ func ParseTreeLine(rd *bufio.Reader, modeBuf, fnameBuf, shaBuf []byte) (mode, fn modeBuf = modeBuf[:len(readBytes)] } else { modeBuf = append(modeBuf, readBytes[len(modeBuf):]...) - } mode = modeBuf[:len(modeBuf)-1] // Drop the SP diff --git a/modules/git/command_test.go b/modules/git/command_test.go index 00801ae31ff25..b427f40adc435 100644 --- a/modules/git/command_test.go +++ b/modules/git/command_test.go @@ -13,7 +13,6 @@ import ( ) func TestRunInDirTimeoutPipelineNoTimeout(t *testing.T) { - maxLoops := 1000 // 'git --version' does not block so it must be finished before the timeout triggered. @@ -26,7 +25,6 @@ func TestRunInDirTimeoutPipelineNoTimeout(t *testing.T) { } func TestRunInDirTimeoutPipelineAlwaysTimeout(t *testing.T) { - maxLoops := 1000 // 'git hash-object --stdin' blocks on stdin so we can have the timeout triggered. diff --git a/modules/git/commit.go b/modules/git/commit.go index 027642720d0ab..f14e671e20cee 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -40,7 +40,7 @@ type Commit struct { // CommitGPGSignature represents a git commit signature part. type CommitGPGSignature struct { Signature string - Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data + Payload string // TODO check if can be reconstruct from the rest of commit information to not have duplicate data } // Message returns the commit message. Same as retrieving CommitMessage directly. diff --git a/modules/git/commit_info_gogit.go b/modules/git/commit_info_gogit.go index 6d95e22d0c7c8..c27bcf987e88f 100644 --- a/modules/git/commit_info_gogit.go +++ b/modules/git/commit_info_gogit.go @@ -155,7 +155,7 @@ func getFileHashes(c cgobject.CommitNode, treePath string, paths []string) (map[ func getLastCommitForPathsByCache(commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*object.Commit, []string, error) { var unHitEntryPaths []string - var results = make(map[string]*object.Commit) + results := make(map[string]*object.Commit) for _, p := range paths { lastCommit, err := cache.Get(commitID, path.Join(treePath, p)) if err != nil { diff --git a/modules/git/commit_info_nogogit.go b/modules/git/commit_info_nogogit.go index b844468c8c41b..cce1c1d635f72 100644 --- a/modules/git/commit_info_nogogit.go +++ b/modules/git/commit_info_nogogit.go @@ -103,7 +103,7 @@ func (tes Entries) GetCommitsInfo(commit *Commit, treePath string, cache *LastCo func getLastCommitForPathsByCache(commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*Commit, []string, error) { var unHitEntryPaths []string - var results = make(map[string]*Commit) + results := make(map[string]*Commit) for _, p := range paths { lastCommit, err := cache.Get(commitID, path.Join(treePath, p)) if err != nil { diff --git a/modules/git/commit_info_test.go b/modules/git/commit_info_test.go index 3966419bc146f..82885f2413431 100644 --- a/modules/git/commit_info_test.go +++ b/modules/git/commit_info_test.go @@ -14,8 +14,10 @@ import ( "github.com/stretchr/testify/assert" ) -const testReposDir = "tests/repos/" -const benchmarkReposDir = "benchmark/repos/" +const ( + testReposDir = "tests/repos/" + benchmarkReposDir = "benchmark/repos/" +) func cloneRepo(url, dir, name string) (string, error) { repoDir := filepath.Join(dir, name) diff --git a/modules/git/hook.go b/modules/git/hook.go index c23fbf8aa1bb2..d33e74c0bf3d4 100644 --- a/modules/git/hook.go +++ b/modules/git/hook.go @@ -22,10 +22,8 @@ var hookNames = []string{ "post-receive", } -var ( - // ErrNotValidHook error when a git hook is not valid - ErrNotValidHook = errors.New("not a valid Git hook") -) +// ErrNotValidHook error when a git hook is not valid +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 { @@ -141,5 +139,5 @@ func SetUpdateHook(repoPath, content string) (err error) { if err != nil { return err } - return ioutil.WriteFile(hookPath, []byte(content), 0777) + return ioutil.WriteFile(hookPath, []byte(content), 0o777) } diff --git a/modules/git/last_commit_cache_gogit.go b/modules/git/last_commit_cache_gogit.go index 65d6299bef387..fca32f20ac8a3 100644 --- a/modules/git/last_commit_cache_gogit.go +++ b/modules/git/last_commit_cache_gogit.go @@ -61,7 +61,6 @@ func (c *LastCommitCache) Get(ref, entryPath string) (interface{}, error) { // CacheCommit will cache the commit from the gitRepository func (c *LastCommitCache) CacheCommit(commit *Commit) error { - commitNodeIndex, _ := commit.repo.CommitNodeIndex() index, err := commitNodeIndex.Get(commit.ID) diff --git a/modules/git/parse_nogogit_test.go b/modules/git/parse_nogogit_test.go index a9e7dcc7f8b15..39910888e4f82 100644 --- a/modules/git/parse_nogogit_test.go +++ b/modules/git/parse_nogogit_test.go @@ -13,7 +13,6 @@ import ( ) func TestParseTreeEntries(t *testing.T) { - testCases := []struct { Input string Expected []*TreeEntry diff --git a/modules/git/repo.go b/modules/git/repo.go index 515899ab04984..f76acf3af3ff4 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -347,7 +347,7 @@ type DivergeObject struct { Behind int } -func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) { +func checkDivergence(repoPath, baseBranch, targetBranch string) (int, error) { branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch) cmd := NewCommand("rev-list", "--count", branches) stdout, err := cmd.RunInDir(repoPath) @@ -362,7 +362,7 @@ func checkDivergence(repoPath string, baseBranch string, targetBranch string) (i } // GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch -func GetDivergingCommits(repoPath string, baseBranch string, targetBranch string) (DivergeObject, error) { +func GetDivergingCommits(repoPath, baseBranch, targetBranch string) (DivergeObject, error) { // $(git rev-list --count master..feature) commits ahead of master ahead, errorAhead := checkDivergence(repoPath, baseBranch, targetBranch) if errorAhead != nil { diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go index aa5e4c10e70d8..f1a3ec52a1519 100644 --- a/modules/git/repo_attribute.go +++ b/modules/git/repo_attribute.go @@ -64,7 +64,7 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[ return nil, fmt.Errorf("Wrong number of fields in return from check-attr") } - var name2attribute2info = make(map[string]map[string]string) + name2attribute2info := make(map[string]map[string]string) for i := 0; i < (len(fields) / 3); i++ { filename := string(fields[3*i]) diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index ea0aeeb35d370..b4b2af8aae95f 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -122,7 +122,6 @@ var BranchesRangeSize = 20 func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) (*list.List, error) { stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize), "--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunInDirBytes(repo.Path) - if err != nil { return nil, err } @@ -297,7 +296,7 @@ func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (in } // CommitsBetween returns a list that contains commits between [last, before). -func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) { +func (repo *Repository) CommitsBetween(last, before *Commit) (*list.List, error) { var stdout []byte var err error if before == nil { @@ -317,7 +316,7 @@ func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List } // CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [last, before) -func (repo *Repository) CommitsBetweenLimit(last *Commit, before *Commit, limit, skip int) (*list.List, error) { +func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip int) (*list.List, error) { var stdout []byte var err error if before == nil { diff --git a/modules/git/repo_compare.go b/modules/git/repo_compare.go index 3255e68392a2d..66058e1c7a357 100644 --- a/modules/git/repo_compare.go +++ b/modules/git/repo_compare.go @@ -28,7 +28,7 @@ type CompareInfo struct { } // GetMergeBase checks and returns merge base of two branches and the reference used as base. -func (repo *Repository) GetMergeBase(tmpRemote string, base, head string) (string, string, error) { +func (repo *Repository) GetMergeBase(tmpRemote, base, head string) (string, string, error) { if tmpRemote == "" { tmpRemote = "origin" } diff --git a/modules/git/repo_language_stats.go b/modules/git/repo_language_stats.go index ac23caa0fc04b..daeb4b591f5bf 100644 --- a/modules/git/repo_language_stats.go +++ b/modules/git/repo_language_stats.go @@ -4,5 +4,7 @@ package git -const fileSizeLimit int64 = 16 * 1024 // 16 KiB -const bigFileSize int64 = 1024 * 1024 // 1 MiB +const ( + fileSizeLimit int64 = 16 * 1024 // 16 KiB + bigFileSize int64 = 1024 * 1024 // 1 MiB +) diff --git a/modules/git/repo_object.go b/modules/git/repo_object.go index f054c349029e5..b10e2f373f809 100644 --- a/modules/git/repo_object.go +++ b/modules/git/repo_object.go @@ -46,7 +46,6 @@ func (repo *Repository) hashObject(reader io.Reader) (string, error) { stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) err := cmd.RunInDirFullPipeline(repo.Path, stdout, stderr, reader) - if err != nil { return "", err } diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 59ab7020964df..ce16faabdbf60 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -178,7 +178,7 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, error) { tagNames = tagNames[skip : skip+pageSize] } - var tags = make([]*Tag, 0, len(tagNames)) + tags := make([]*Tag, 0, len(tagNames)) for _, tagName := range tagNames { tagName = strings.TrimSpace(tagName) if len(tagName) == 0 { diff --git a/modules/git/repo_tree.go b/modules/git/repo_tree.go index 2053b6a1de17d..d7705719aba06 100644 --- a/modules/git/repo_tree.go +++ b/modules/git/repo_tree.go @@ -23,7 +23,7 @@ type CommitTreeOpts struct { } // CommitTree creates a commit from a given tree id for the user with provided message -func (repo *Repository) CommitTree(author *Signature, committer *Signature, tree *Tree, opts CommitTreeOpts) (SHA1, error) { +func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opts CommitTreeOpts) (SHA1, error) { err := LoadGitVersion() if err != nil { return SHA1{}, err diff --git a/modules/git/submodule_test.go b/modules/git/submodule_test.go index ff8dc579f6d51..653f0a6f084cc 100644 --- a/modules/git/submodule_test.go +++ b/modules/git/submodule_test.go @@ -11,7 +11,7 @@ import ( ) func TestGetRefURL(t *testing.T) { - var kases = []struct { + kases := []struct { refURL string prefixURL string parentPath string diff --git a/modules/git/tag.go b/modules/git/tag.go index 0323cc42edd7c..2ec2f99795d21 100644 --- a/modules/git/tag.go +++ b/modules/git/tag.go @@ -10,8 +10,10 @@ import ( "strings" ) -const beginpgp = "\n-----BEGIN PGP SIGNATURE-----\n" -const endpgp = "\n-----END PGP SIGNATURE-----" +const ( + beginpgp = "\n-----BEGIN PGP SIGNATURE-----\n" + endpgp = "\n-----END PGP SIGNATURE-----" +) // Tag represents a Git tag. type Tag struct { diff --git a/modules/git/tree_blob_gogit.go b/modules/git/tree_blob_gogit.go index 93ebc8a367da4..2fc08f43f49d6 100644 --- a/modules/git/tree_blob_gogit.go +++ b/modules/git/tree_blob_gogit.go @@ -21,7 +21,7 @@ func (t *Tree) GetTreeEntryByPath(relpath string) (*TreeEntry, error) { if len(relpath) == 0 { return &TreeEntry{ ID: t.ID, - //Type: ObjectTree, + // Type: ObjectTree, gogitTreeEntry: &object.TreeEntry{ Name: "", Mode: filemode.Dir, diff --git a/modules/git/tree_entry_mode.go b/modules/git/tree_entry_mode.go index b029c6fc476f8..d999ccc02a81d 100644 --- a/modules/git/tree_entry_mode.go +++ b/modules/git/tree_entry_mode.go @@ -13,15 +13,15 @@ type EntryMode int // one of these. const ( // EntryModeBlob - EntryModeBlob EntryMode = 0100644 + EntryModeBlob EntryMode = 0o100644 // EntryModeExec - EntryModeExec EntryMode = 0100755 + EntryModeExec EntryMode = 0o100755 // EntryModeSymlink - EntryModeSymlink EntryMode = 0120000 + EntryModeSymlink EntryMode = 0o120000 // EntryModeCommit - EntryModeCommit EntryMode = 0160000 + EntryModeCommit EntryMode = 0o160000 // EntryModeTree - EntryModeTree EntryMode = 0040000 + EntryModeTree EntryMode = 0o040000 ) // String converts an EntryMode to a string diff --git a/modules/git/utils.go b/modules/git/utils.go index d95218941606b..684fa20e15b5d 100644 --- a/modules/git/utils.go +++ b/modules/git/utils.go @@ -123,7 +123,7 @@ func SplitRefName(refStr string) (string, string) { // 0 is false, true // Any other integer is true, true // Anything else will return false, false -func ParseBool(value string) (result bool, valid bool) { +func ParseBool(value string) (result, valid bool) { // Empty strings are true but invalid if len(value) == 0 { return true, false diff --git a/modules/gitgraph/graph.go b/modules/gitgraph/graph.go index 85056786395c2..453282a5ec2e1 100644 --- a/modules/gitgraph/graph.go +++ b/modules/gitgraph/graph.go @@ -17,7 +17,7 @@ import ( ) // GetCommitGraph return a list of commit (GraphItems) from all branches -func GetCommitGraph(r *git.Repository, page int, maxAllowedColors int, hidePRRefs bool, branches, files []string) (*Graph, error) { +func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bool, branches, files []string) (*Graph, error) { format := "DATA:%D|%H|%ad|%h|%s" if page == 0 { diff --git a/modules/gitgraph/graph_test.go b/modules/gitgraph/graph_test.go index c2726a731a45a..9b0b10d16a1e5 100644 --- a/modules/gitgraph/graph_test.go +++ b/modules/gitgraph/graph_test.go @@ -14,7 +14,6 @@ import ( ) func BenchmarkGetCommitGraph(b *testing.B) { - currentRepo, err := git.OpenRepository(".") if err != nil || currentRepo == nil { b.Error("Could not open repository") @@ -256,7 +255,6 @@ func TestCommitStringParsing(t *testing.T) { } for _, test := range tests { - t.Run(test.testName, func(t *testing.T) { testString := fmt.Sprintf("%s%s", dataFirstPart, test.commitMessage) idx := strings.Index(testString, "DATA:") diff --git a/modules/gitgraph/parser.go b/modules/gitgraph/parser.go index 62e05056520fe..5432962784f03 100644 --- a/modules/gitgraph/parser.go +++ b/modules/gitgraph/parser.go @@ -144,7 +144,6 @@ func (parser *Parser) releaseUnusedColors() { // ParseGlyphs parses the provided glyphs and sets the internal state func (parser *Parser) ParseGlyphs(glyphs []byte) { - // Clean state for parsing this row parser.glyphs, parser.oldGlyphs = parser.oldGlyphs, parser.glyphs parser.glyphs = parser.glyphs[0:0] diff --git a/modules/graceful/manager.go b/modules/graceful/manager.go index 903d05ed21f41..708369eec126a 100644 --- a/modules/graceful/manager.go +++ b/modules/graceful/manager.go @@ -184,6 +184,7 @@ func (g *Manager) RunAtHammer(ctx context.Context, hammer func()) { } }() } + func (g *Manager) doShutdown() { if !g.setStateTransition(stateRunning, stateShuttingDown) { return diff --git a/modules/highlight/highlight.go b/modules/highlight/highlight.go index 914ba8210ebf6..e6b74560265c0 100644 --- a/modules/highlight/highlight.go +++ b/modules/highlight/highlight.go @@ -67,7 +67,7 @@ func Code(fileName, code string) string { htmlw := bufio.NewWriter(&htmlbuf) if val, ok := highlightMapping[filepath.Ext(fileName)]; ok { - //change file name to one with mapped extension so we look that up instead + // change file name to one with mapped extension so we look that up instead fileName = "mapped." + val } @@ -145,7 +145,7 @@ func File(numLines int, fileName string, code []byte) map[int]string { for k, v := range strings.SplitN(htmlbuf.String(), "\n", numLines) { line := k + 1 content := string(v) - //need to keep lines that are only \n so copy/paste works properly in browser + // need to keep lines that are only \n so copy/paste works properly in browser if content == "" { content = "\n" } @@ -160,7 +160,7 @@ func plainText(code string, numLines int) map[int]string { for k, v := range strings.SplitN(string(code), "\n", numLines) { line := k + 1 content := string(v) - //need to keep lines that are only \n so copy/paste works properly in browser + // need to keep lines that are only \n so copy/paste works properly in browser if content == "" { content = "\n" } diff --git a/modules/httplib/httplib.go b/modules/httplib/httplib.go index 62f284d2e192f..8e71bf3b34fd9 100644 --- a/modules/httplib/httplib.go +++ b/modules/httplib/httplib.go @@ -26,9 +26,11 @@ import ( jsoniter "github.com/json-iterator/go" ) -var defaultSetting = Settings{false, "GiteaServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false} -var defaultCookieJar http.CookieJar -var settingMutex sync.Mutex +var ( + defaultSetting = Settings{false, "GiteaServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false} + defaultCookieJar http.CookieJar + settingMutex sync.Mutex +) // createDefaultCookie creates a global cookiejar to store cookies. func createDefaultCookie() { @@ -283,7 +285,7 @@ func (r *Request) getResponse() (*http.Response, error) { if err != nil { log.Fatal(err) } - //iocopy + // iocopy _, err = io.Copy(fileWriter, fh) fh.Close() if err != nil { @@ -457,7 +459,7 @@ func (r *Request) Response() (*http.Response, error) { } // TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field. -func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) { +func TimeoutDialer(cTimeout, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) { return func(netw, addr string) (net.Conn, error) { conn, err := net.DialTimeout(netw, addr, cTimeout) if err != nil { diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 573ea8b88cbc4..f65b9ca8d7ae8 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -37,8 +37,10 @@ import ( "github.com/go-enry/go-enry/v2" ) -const unicodeNormalizeName = "unicodeNormalize" -const maxBatchSize = 16 +const ( + unicodeNormalizeName = "unicodeNormalize" + maxBatchSize = 16 +) // numericEqualityQuery a numeric equality query for the given value and field func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery { @@ -157,9 +159,7 @@ func createBleveIndexer(path string, latestVersion int) (bleve.Index, error) { return indexer, nil } -var ( - _ Indexer = &BleveIndexer{} -) +var _ Indexer = &BleveIndexer{} // BleveIndexer represents a bleve indexer implementation type BleveIndexer struct { @@ -322,7 +322,7 @@ func (b *BleveIndexer) Search(repoIDs []int64, language, keyword string, page, p } if len(repoIDs) > 0 { - var repoQueries = make([]query.Query, 0, len(repoIDs)) + repoQueries := make([]query.Query, 0, len(repoIDs)) for _, repoID := range repoIDs { repoQueries = append(repoQueries, numericEqualityQuery(repoID, "RepoID")) } diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index 5327eb1e51e9d..adfa607f1e754 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -36,9 +36,7 @@ const ( esMultiMatchTypePhrasePrefix = "phrase_prefix" ) -var ( - _ Indexer = &ElasticSearchIndexer{} -) +var _ Indexer = &ElasticSearchIndexer{} // ElasticSearchIndexer implements Indexer interface type ElasticSearchIndexer struct { @@ -129,7 +127,7 @@ func (b *ElasticSearchIndexer) init() (bool, error) { return false, err } if !exists { - var mapping = defaultMapping + mapping := defaultMapping createIndex, err := b.client.CreateIndex(b.realIndexerName()).BodyString(mapping).Do(ctx) if err != nil { @@ -317,7 +315,7 @@ func convertResult(searchResult *elastic.SearchResult, kw string, pageSize int) } repoID, fileName := parseIndexerID(hit.Id) - var res = make(map[string]interface{}) + res := make(map[string]interface{}) json := jsoniter.ConfigCompatibleWithStandardLibrary if err := json.Unmarshal(hit.Source, &res); err != nil { return 0, nil, nil, err @@ -369,7 +367,7 @@ func (b *ElasticSearchIndexer) Search(repoIDs []int64, language, keyword string, query := elastic.NewBoolQuery() query = query.Must(kwQuery) if len(repoIDs) > 0 { - var repoStrs = make([]interface{}, 0, len(repoIDs)) + repoStrs := make([]interface{}, 0, len(repoIDs)) for _, repoID := range repoIDs { repoStrs = append(repoStrs, repoID) } diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index 919d7854062f4..218d8eb3c1fe4 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -72,7 +72,7 @@ func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) { if err != nil { return nil, err } - var idxCount = 0 + idxCount := 0 updates := make([]fileUpdate, len(entries)) for _, entry := range entries { if isIndexable(entry) { diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go index a7d78e9fdc82c..1beb2131a9fbb 100644 --- a/modules/indexer/code/indexer.go +++ b/modules/indexer/code/indexer.go @@ -78,9 +78,7 @@ type IndexerData struct { IsDelete bool } -var ( - indexerQueue queue.Queue -) +var indexerQueue queue.Queue func index(indexer Indexer, repoID int64) error { repo, err := models.GetRepositoryByID(repoID) diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index 8fcb7a0e8a677..cbb7dd6ded9fb 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -22,45 +22,43 @@ func testIndexer(name string, t *testing.T, indexer Indexer) { var repoID int64 = 1 err := index(indexer, repoID) assert.NoError(t, err) - var ( - keywords = []struct { - RepoIDs []int64 - Keyword string - IDs []int64 - Langs int - }{ - { - RepoIDs: nil, - Keyword: "Description", - IDs: []int64{repoID}, - Langs: 1, - }, - { - RepoIDs: []int64{2}, - Keyword: "Description", - IDs: []int64{}, - Langs: 0, - }, - { - RepoIDs: nil, - Keyword: "repo1", - IDs: []int64{repoID}, - Langs: 1, - }, - { - RepoIDs: []int64{2}, - Keyword: "repo1", - IDs: []int64{}, - Langs: 0, - }, - { - RepoIDs: nil, - Keyword: "non-exist", - IDs: []int64{}, - Langs: 0, - }, - } - ) + keywords := []struct { + RepoIDs []int64 + Keyword string + IDs []int64 + Langs int + }{ + { + RepoIDs: nil, + Keyword: "Description", + IDs: []int64{repoID}, + Langs: 1, + }, + { + RepoIDs: []int64{2}, + Keyword: "Description", + IDs: []int64{}, + Langs: 0, + }, + { + RepoIDs: nil, + Keyword: "repo1", + IDs: []int64{repoID}, + Langs: 1, + }, + { + RepoIDs: []int64{2}, + Keyword: "repo1", + IDs: []int64{}, + Langs: 0, + }, + { + RepoIDs: nil, + Keyword: "non-exist", + IDs: []int64{}, + Langs: 0, + }, + } for _, kw := range keywords { t.Run(kw.Keyword, func(t *testing.T) { @@ -69,7 +67,7 @@ func testIndexer(name string, t *testing.T, indexer Indexer) { assert.EqualValues(t, len(kw.IDs), total) assert.EqualValues(t, kw.Langs, len(langs)) - var ids = make([]int64, 0, len(res)) + ids := make([]int64, 0, len(res)) for _, hit := range res { ids = append(ids, hit.RepoID) assert.EqualValues(t, "# repo1\n\nDescription for repo1", hit.Content) diff --git a/modules/indexer/code/wrapped.go b/modules/indexer/code/wrapped.go index 5b19f9c625737..23d63e1ffdccb 100644 --- a/modules/indexer/code/wrapped.go +++ b/modules/indexer/code/wrapped.go @@ -11,9 +11,7 @@ import ( "code.gitea.io/gitea/models" ) -var ( - indexer = newWrappedIndexer() -) +var indexer = newWrappedIndexer() // ErrWrappedIndexerClosed is the error returned if the indexer was closed before it was ready var ErrWrappedIndexerClosed = fmt.Errorf("Indexer closed before ready") @@ -79,7 +77,6 @@ func (w *wrappedIndexer) Search(repoIDs []int64, language, keyword string, page, return 0, nil, nil, err } return indexer.Search(repoIDs, language, keyword, page, pageSize, isMatch) - } func (w *wrappedIndexer) Close() { diff --git a/modules/indexer/issues/bleve.go b/modules/indexer/issues/bleve.go index b1385eb676256..77cfb746ad5cb 100644 --- a/modules/indexer/issues/bleve.go +++ b/modules/indexer/issues/bleve.go @@ -154,9 +154,7 @@ func createIssueIndexer(path string, latestVersion int) (bleve.Index, error) { return index, nil } -var ( - _ Indexer = &BleveIndexer{} -) +var _ Indexer = &BleveIndexer{} // BleveIndexer implements Indexer interface type BleveIndexer struct { @@ -254,7 +252,7 @@ func (b *BleveIndexer) Search(keyword string, repoIDs []int64, limit, start int) return nil, err } - var ret = SearchResult{ + ret := SearchResult{ Hits: make([]Match, 0, len(result.Hits)), } for _, hit := range result.Hits { diff --git a/modules/indexer/issues/bleve_test.go b/modules/indexer/issues/bleve_test.go index 2a8ed15d820b8..230a22e53f6d0 100644 --- a/modules/indexer/issues/bleve_test.go +++ b/modules/indexer/issues/bleve_test.go @@ -52,43 +52,41 @@ func TestBleveIndexAndSearch(t *testing.T) { }) assert.NoError(t, err) - var ( - keywords = []struct { - Keyword string - IDs []int64 - }{ - { - Keyword: "search", - IDs: []int64{1}, - }, - { - Keyword: "test1", - IDs: []int64{1}, - }, - { - Keyword: "test2", - IDs: []int64{1}, - }, - { - Keyword: "support", - IDs: []int64{1, 2}, - }, - { - Keyword: "chinese", - IDs: []int64{1, 2}, - }, - { - Keyword: "help", - IDs: []int64{}, - }, - } - ) + keywords := []struct { + Keyword string + IDs []int64 + }{ + { + Keyword: "search", + IDs: []int64{1}, + }, + { + Keyword: "test1", + IDs: []int64{1}, + }, + { + Keyword: "test2", + IDs: []int64{1}, + }, + { + Keyword: "support", + IDs: []int64{1, 2}, + }, + { + Keyword: "chinese", + IDs: []int64{1, 2}, + }, + { + Keyword: "help", + IDs: []int64{}, + }, + } for _, kw := range keywords { res, err := indexer.Search(kw.Keyword, []int64{2}, 10, 0) assert.NoError(t, err) - var ids = make([]int64, 0, len(res.Hits)) + ids := make([]int64, 0, len(res.Hits)) for _, hit := range res.Hits { ids = append(ids, hit.ID) } diff --git a/modules/indexer/issues/db.go b/modules/indexer/issues/db.go index d0cca4fd18087..f02cbddce8fb5 100644 --- a/modules/indexer/issues/db.go +++ b/modules/indexer/issues/db.go @@ -7,8 +7,7 @@ package issues import "code.gitea.io/gitea/models" // DBIndexer implements Indexer interface to use database's like search -type DBIndexer struct { -} +type DBIndexer struct{} // Init dummy function func (db *DBIndexer) Init() (bool, error) { @@ -35,7 +34,7 @@ func (db *DBIndexer) Search(kw string, repoIDs []int64, limit, start int) (*Sear if err != nil { return nil, err } - var result = SearchResult{ + result := SearchResult{ Total: total, Hits: make([]Match, 0, limit), } diff --git a/modules/indexer/issues/elastic_search.go b/modules/indexer/issues/elastic_search.go index 3af64ed30e535..187b69b74946b 100644 --- a/modules/indexer/issues/elastic_search.go +++ b/modules/indexer/issues/elastic_search.go @@ -16,9 +16,7 @@ import ( "github.com/olivere/elastic/v7" ) -var ( - _ Indexer = &ElasticSearchIndexer{} -) +var _ Indexer = &ElasticSearchIndexer{} // ElasticSearchIndexer implements Indexer interface type ElasticSearchIndexer struct { @@ -102,7 +100,7 @@ func (b *ElasticSearchIndexer) Init() (bool, error) { } if !exists { - var mapping = defaultMapping + mapping := defaultMapping createIndex, err := b.client.CreateIndex(b.indexerName).BodyString(mapping).Do(ctx) if err != nil { @@ -195,7 +193,7 @@ func (b *ElasticSearchIndexer) Search(keyword string, repoIDs []int64, limit, st query := elastic.NewBoolQuery() query = query.Must(kwQuery) if len(repoIDs) > 0 { - var repoStrs = make([]interface{}, 0, len(repoIDs)) + repoStrs := make([]interface{}, 0, len(repoIDs)) for _, repoID := range repoIDs { repoStrs = append(repoStrs, repoID) } diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 8c163f78d15dd..ed34051a7ea6b 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -70,7 +70,6 @@ func TestBleveSearchIssues(t *testing.T) { ids, err = SearchIssuesByKeyword([]int64{1}, "good") assert.NoError(t, err) assert.EqualValues(t, []int64{1}, ids) - } func TestDBSearchIssues(t *testing.T) { diff --git a/modules/indexer/stats/db.go b/modules/indexer/stats/db.go index bc3fbc13d8932..0149b11fb8e09 100644 --- a/modules/indexer/stats/db.go +++ b/modules/indexer/stats/db.go @@ -11,8 +11,7 @@ import ( ) // DBIndexer implements Indexer interface to use database's like search -type DBIndexer struct { -} +type DBIndexer struct{} // Index repository status function func (db *DBIndexer) Index(id int64) error { diff --git a/modules/lfs/locks.go b/modules/lfs/locks.go index f2688c32607f8..59a663a4f0bb4 100644 --- a/modules/lfs/locks.go +++ b/modules/lfs/locks.go @@ -17,7 +17,7 @@ import ( jsoniter "github.com/json-iterator/go" ) -//checkIsValidRequest check if it a valid request in case of bad request it write the response to ctx. +// checkIsValidRequest check if it a valid request in case of bad request it write the response to ctx. func checkIsValidRequest(ctx *context.Context) bool { if !setting.LFS.StartServer { log.Debug("Attempt to access LFS server but LFS server is disabled") @@ -103,7 +103,7 @@ func GetListLockHandler(ctx *context.Context) { limit = 0 } id := ctx.Query("id") - if id != "" { //Case where we request a specific id + if id != "" { // Case where we request a specific id v, err := strconv.ParseInt(id, 10, 64) if err != nil { ctx.JSON(400, api.LFSLockError{ @@ -120,7 +120,7 @@ func GetListLockHandler(ctx *context.Context) { } path := ctx.Query("path") - if path != "" { //Case where we request a specific id + if path != "" { // Case where we request a specific id lock, err := models.GetLFSLock(repository, path) if err != nil && !models.IsErrLFSLockNotExist(err) { log.Error("Unable to get lock for repository %-v with path %s: Error: %v", repository, path, err) @@ -129,7 +129,7 @@ func GetListLockHandler(ctx *context.Context) { return } - //If no query params path or id + // If no query params path or id lockList, err := models.GetLFSLockByRepoID(repository.ID, cursor, limit) if err != nil { log.Error("Unable to list locks for repository ID[%d]: Error: %v", repository.ID, err) diff --git a/modules/lfs/server.go b/modules/lfs/server.go index 45cba9d9b7512..817a3b71b3242 100644 --- a/modules/lfs/server.go +++ b/modules/lfs/server.go @@ -483,7 +483,7 @@ func Represent(rv *RequestVars, meta *models.LFSMetaObject, download, upload boo header := make(map[string]string) if rv.Authorization == "" { - //https://github.com/github/git-lfs/issues/1088 + // https://github.com/github/git-lfs/issues/1088 header["Authorization"] = "Authorization: Basic dummy" } else { header["Authorization"] = rv.Authorization @@ -552,7 +552,6 @@ func unpack(ctx *context.Context) *RequestVars { // TODO cheap hack, unify with unpack func unpackbatch(ctx *context.Context) *BatchVars { - r := ctx.Req var bv BatchVars diff --git a/modules/log/colors.go b/modules/log/colors.go index 5d56fd739077e..8e99e90e72b75 100644 --- a/modules/log/colors.go +++ b/modules/log/colors.go @@ -169,10 +169,12 @@ var levelToColor = map[Level][]byte{ NONE: ColorBytes(Reset), } -var resetBytes = ColorBytes(Reset) -var fgCyanBytes = ColorBytes(FgCyan) -var fgGreenBytes = ColorBytes(FgGreen) -var fgBoldBytes = ColorBytes(Bold) +var ( + resetBytes = ColorBytes(Reset) + fgCyanBytes = ColorBytes(FgCyan) + fgGreenBytes = ColorBytes(FgGreen) + fgBoldBytes = ColorBytes(Bold) +) type protectedANSIWriterMode int @@ -335,7 +337,6 @@ func NewColoredValuePointer(value *interface{}, color ...ColorAttribute) *Colore resetBytes: &resetBytes, Value: value, } - } // NewColoredValueBytes creates a value from the provided value with color bytes diff --git a/modules/log/conn_test.go b/modules/log/conn_test.go index dc5de732f4117..f7756d053068a 100644 --- a/modules/log/conn_test.go +++ b/modules/log/conn_test.go @@ -135,7 +135,7 @@ func TestConnLoggerFailConnect(t *testing.T) { date := time.Date(2019, time.January, 13, 22, 3, 30, 15, location) - //dateString := date.UTC().Format("2006/01/02 15:04:05") + // dateString := date.UTC().Format("2006/01/02 15:04:05") event := Event{ level: INFO, @@ -224,7 +224,6 @@ func TestConnLoggerClose(t *testing.T) { err := logger.LogEvent(&event) assert.NoError(t, err) logger.Close() - }() wg.Wait() logger.Flush() diff --git a/modules/log/file.go b/modules/log/file.go index d5b38d4e0172d..dd72a58dc14d2 100644 --- a/modules/log/file.go +++ b/modules/log/file.go @@ -76,7 +76,7 @@ func (mw *MuxWriter) SetFd(fd *os.File) { func NewFileLogger() LoggerProvider { log := &FileLogger{ Filename: "", - Maxsize: 1 << 28, //256 MB + Maxsize: 1 << 28, // 256 MB Daily: true, Maxdays: 7, Rotate: true, @@ -138,7 +138,7 @@ func (log *FileLogger) docheck(size int) { func (log *FileLogger) createLogFile() (*os.File, error) { // Open the log file - return os.OpenFile(log.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) + return os.OpenFile(log.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o660) } func (log *FileLogger) initFd() error { @@ -203,7 +203,7 @@ func compressOldLogFile(fname string, compressionLevel int) error { } defer reader.Close() buffer := bufio.NewReader(reader) - fw, err := os.OpenFile(fname+".gz", os.O_WRONLY|os.O_CREATE, 0660) + fw, err := os.OpenFile(fname+".gz", os.O_WRONLY|os.O_CREATE, 0o660) if err != nil { return err } @@ -235,7 +235,6 @@ func (log *FileLogger) deleteOldLog() { if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*log.Maxdays) { if strings.HasPrefix(filepath.Base(path), filepath.Base(log.Filename)) { - if err := util.Remove(path); err != nil { returnErr = fmt.Errorf("Failed to remove %s: %v", path, err) } diff --git a/modules/log/file_test.go b/modules/log/file_test.go index af6fbcb29d11b..81534d86731de 100644 --- a/modules/log/file_test.go +++ b/modules/log/file_test.go @@ -26,11 +26,11 @@ func TestFileLoggerFails(t *testing.T) { prefix := "TestPrefix " level := INFO flags := LstdFlags | LUTC | Lfuncname - //filename := filepath.Join(tmpDir, "test.log") + // filename := filepath.Join(tmpDir, "test.log") fileLogger := NewFileLogger() - //realFileLogger, ok := fileLogger.(*FileLogger) - //assert.Equal(t, true, ok) + // realFileLogger, ok := fileLogger.(*FileLogger) + // assert.Equal(t, true, ok) // Fail if there is bad json err = fileLogger.Init("{") @@ -43,7 +43,6 @@ func TestFileLoggerFails(t *testing.T) { // Fail if the file isn't a filename err = fileLogger.Init(fmt.Sprintf("{\"prefix\":\"%s\",\"level\":\"%s\",\"flags\":%d,\"filename\":\"%s\"}", prefix, level.String(), flags, filepath.ToSlash(tmpDir))) assert.Error(t, err) - } func TestFileLogger(t *testing.T) { @@ -124,7 +123,7 @@ func TestFileLogger(t *testing.T) { assert.Equal(t, expected, string(logData)) for num := 2; num <= 999; num++ { - file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0666) + file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0o666) assert.NoError(t, err) file.Close() } @@ -201,7 +200,7 @@ func TestCompressFileLogger(t *testing.T) { fileLogger.Flush() for num := 2; num <= 999; num++ { - file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d.gz", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0666) + file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d.gz", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0o666) assert.NoError(t, err) file.Close() } @@ -216,9 +215,9 @@ func TestCompressOldFile(t *testing.T) { fname := filepath.Join(tmpDir, "test") nonGzip := filepath.Join(tmpDir, "test-nonGzip") - f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, 0660) + f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, 0o660) assert.NoError(t, err) - ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0660) + ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0o660) assert.NoError(t, err) for i := 0; i < 999; i++ { diff --git a/modules/log/log_test.go b/modules/log/log_test.go index 810505dea5b47..68a722e830e65 100644 --- a/modules/log/log_test.go +++ b/modules/log/log_test.go @@ -136,7 +136,6 @@ func TestNewLogggerRecreate(t *testing.T) { // We should be able to redelete without a problem go DelLogger("console") - } func TestNewNamedLogger(t *testing.T) { diff --git a/modules/log/logger.go b/modules/log/logger.go index 75f361ccdba43..0045d793229dd 100644 --- a/modules/log/logger.go +++ b/modules/log/logger.go @@ -65,7 +65,6 @@ func (l *LevelLoggerLogger) IsTrace() bool { // Debug records debug log func (l *LevelLoggerLogger) Debug(format string, v ...interface{}) { l.Log(1, DEBUG, format, v...) - } // IsDebug returns true if the logger is DEBUG diff --git a/modules/log/multichannel.go b/modules/log/multichannel.go index d28071c3f72ea..c725df4f3ed57 100644 --- a/modules/log/multichannel.go +++ b/modules/log/multichannel.go @@ -80,7 +80,7 @@ func (l *MultiChannelledLogger) Log(skip int, level Level, format string, v ...i } // SendLog sends a log event at the provided level with the information given -func (l *MultiChannelledLogger) SendLog(level Level, caller, filename string, line int, msg string, stack string) error { +func (l *MultiChannelledLogger) SendLog(level Level, caller, filename string, line int, msg, stack string) error { if l.GetLevel() > level { return nil } diff --git a/modules/log/stack.go b/modules/log/stack.go index 568c10cd00d02..0e6f480173efd 100644 --- a/modules/log/stack.go +++ b/modules/log/stack.go @@ -11,9 +11,7 @@ import ( "runtime" ) -var ( - unknown = []byte("???") -) +var unknown = []byte("???") // Stack will skip back the provided number of frames and return a stack trace with source code. // Although we could just use debug.Stack(), this routine will return the source code and diff --git a/modules/log/writer.go b/modules/log/writer.go index 6f656c7ce1521..1c4f5b4a19513 100644 --- a/modules/log/writer.go +++ b/modules/log/writer.go @@ -73,7 +73,7 @@ func (logger *WriterLogger) GetStacktraceLevel() Level { } // Copy of cheap integer to fixed-width decimal to ascii from logger. -func itoa(buf *[]byte, i int, wid int) { +func itoa(buf *[]byte, i, wid int) { var logger [20]byte bp := len(logger) - 1 for i >= 10 || wid > 1 { @@ -189,7 +189,7 @@ func (logger *WriterLogger) createMsg(buf *[]byte, event *Event) { *buf = append(*buf, ' ') } - var msg = []byte(event.msg) + msg := []byte(event.msg) if len(msg) > 0 && msg[len(msg)-1] == '\n' { msg = msg[:len(msg)-1] } diff --git a/modules/log/writer_test.go b/modules/log/writer_test.go index 886dd58fb38fd..07428625a05ab 100644 --- a/modules/log/writer_test.go +++ b/modules/log/writer_test.go @@ -251,7 +251,6 @@ func TestBaseLoggerMultiLineNoFlagsRegexp(t *testing.T) { assert.Equal(t, expected, string(written)) assert.Equal(t, false, closed) written = written[:0] - } func TestBrokenRegexp(t *testing.T) { diff --git a/modules/markup/common/footnote.go b/modules/markup/common/footnote.go index 9baf8a4998b7c..c64e7533c68ed 100644 --- a/modules/markup/common/footnote.go +++ b/modules/markup/common/footnote.go @@ -179,8 +179,7 @@ func NewFootnoteList() *FootnoteList { var footnoteListKey = parser.NewContextKey() -type footnoteBlockParser struct { -} +type footnoteBlockParser struct{} var defaultFootnoteBlockParser = &footnoteBlockParser{} @@ -266,8 +265,7 @@ func (b *footnoteBlockParser) CanAcceptIndentedLine() bool { return false } -type footnoteParser struct { -} +type footnoteParser struct{} var defaultFootnoteParser = &footnoteParser{} @@ -338,8 +336,7 @@ func (s *footnoteParser) Parse(parent ast.Node, block text.Reader, pc parser.Con return NewFootnoteLink(index, name) } -type footnoteASTTransformer struct { -} +type footnoteASTTransformer struct{} var defaultFootnoteASTTransformer = &footnoteASTTransformer{} diff --git a/modules/markup/common/html.go b/modules/markup/common/html.go index 3a47686f1ef80..a2328a2288bfb 100644 --- a/modules/markup/common/html.go +++ b/modules/markup/common/html.go @@ -8,12 +8,10 @@ import ( "mvdan.cc/xurls/v2" ) -var ( - // NOTE: All below regex matching do not perform any extra validation. - // Thus a link is produced even if the linked entity does not exist. - // While fast, this is also incorrect and lead to false positives. - // TODO: fix invalid linking issue +// NOTE: All below regex matching do not perform any extra validation. +// Thus a link is produced even if the linked entity does not exist. +// While fast, this is also incorrect and lead to false positives. +// TODO: fix invalid linking issue - // LinkRegex is a regexp matching a valid link - LinkRegex, _ = xurls.StrictMatchingScheme("https?://") -) +// LinkRegex is a regexp matching a valid link +var LinkRegex, _ = xurls.StrictMatchingScheme("https?://") diff --git a/modules/markup/common/linkify.go b/modules/markup/common/linkify.go index 25621bf8019e0..1e7fb31085e82 100644 --- a/modules/markup/common/linkify.go +++ b/modules/markup/common/linkify.go @@ -20,8 +20,7 @@ import ( var wwwURLRegxp = regexp.MustCompile(`^www\.[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}((?:/|[#?])[-a-zA-Z0-9@:%_\+.~#!?&//=\(\);,'">\^{}\[\]` + "`" + `]*)?`) -type linkifyParser struct { -} +type linkifyParser struct{} var defaultLinkifyParser = &linkifyParser{} @@ -36,10 +35,12 @@ func (s *linkifyParser) Trigger() []byte { return []byte{' ', '*', '_', '~', '('} } -var protoHTTP = []byte("http:") -var protoHTTPS = []byte("https:") -var protoFTP = []byte("ftp:") -var domainWWW = []byte("www.") +var ( + protoHTTP = []byte("http:") + protoHTTPS = []byte("https:") + protoFTP = []byte("ftp:") + domainWWW = []byte("www.") +) func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node { if pc.IsInLinkLabel() { @@ -141,8 +142,7 @@ func (s *linkifyParser) CloseBlock(parent ast.Node, pc parser.Context) { // nothing to do } -type linkify struct { -} +type linkify struct{} // Linkify is an extension that allow you to parse text that seems like a URL. var Linkify = &linkify{} diff --git a/modules/markup/csv/csv.go b/modules/markup/csv/csv.go index 1e3acc9b47e2f..1cbfd1e8081df 100644 --- a/modules/markup/csv/csv.go +++ b/modules/markup/csv/csv.go @@ -20,12 +20,10 @@ var quoteRegexp = regexp.MustCompile(`["'][\s\S]+?["']`) func init() { markup.RegisterParser(Parser{}) - } // Parser implements markup.Parser for orgmode -type Parser struct { -} +type Parser struct{} // Name implements markup.Parser func (Parser) Name() string { diff --git a/modules/markup/csv/csv_test.go b/modules/markup/csv/csv_test.go index 4d4e0871e94d4..191517a1ab199 100644 --- a/modules/markup/csv/csv_test.go +++ b/modules/markup/csv/csv_test.go @@ -12,7 +12,7 @@ import ( func TestRenderCSV(t *testing.T) { var parser Parser - var kases = map[string]string{ + kases := map[string]string{ "a": "
a
", "1,2": "
12
", "1;2": "
12
", diff --git a/modules/markup/html.go b/modules/markup/html.go index a7d66cc2490a7..10067a7372a26 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -313,8 +313,10 @@ func RenderEmoji( return ctx.postProcess(rawHTML) } -var tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL][ />])|(/?[hH][eE][aA][dD][ />]))`) -var nulCleaner = strings.NewReplacer("\000", "") +var ( + tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL][ />])|(/?[hH][eE][aA][dD][ />]))`) + nulCleaner = strings.NewReplacer("\000", "") +) func (ctx *postProcessCtx) postProcess(rawHTML []byte) ([]byte, error) { if ctx.procs == nil { @@ -504,7 +506,6 @@ func createEmoji(content, class, name string) *html.Node { } func createCustomEmoji(alias, class string) *html.Node { - span := &html.Node{ Type: html.ElementNode, Data: atom.Span.String(), @@ -815,7 +816,6 @@ func fullIssuePatternProcessor(ctx *postProcessCtx, node *html.Node) { // TODO if m[4]:m[5] is not nil, then link is to a comment, // and we should indicate that in the text somehow replaceContent(node, m[0], m[1], createLink(link, id, "ref-issue")) - } else { orgRepoID := matchOrg + "/" + matchRepo + id replaceContent(node, m[0], m[1], createLink(link, orgRepoID, "ref-issue")) @@ -945,7 +945,6 @@ func fullSha1PatternProcessor(ctx *postProcessCtx, node *html.Node) { // emojiShortCodeProcessor for rendering text like :smile: into emoji func emojiShortCodeProcessor(ctx *postProcessCtx, node *html.Node) { - m := EmojiShortCodeRegex.FindStringSubmatchIndex(node.Data) if m == nil { return diff --git a/modules/markup/html_internal_test.go b/modules/markup/html_internal_test.go index 7e4bb6f22f31e..a265301b8c892 100644 --- a/modules/markup/html_internal_test.go +++ b/modules/markup/html_internal_test.go @@ -15,9 +15,11 @@ import ( "github.com/stretchr/testify/assert" ) -const AppURL = "http://localhost:3000/" -const Repo = "gogits/gogs" -const AppSubURL = AppURL + Repo + "/" +const ( + AppURL = "http://localhost:3000/" + Repo = "gogits/gogs" + AppSubURL = AppURL + Repo + "/" +) // alphanumLink an HTML link to an alphanumeric-style issue func alphanumIssueLink(baseURL, class, name string) string { diff --git a/modules/markup/html_test.go b/modules/markup/html_test.go index a78b936f87f1c..75516d09920af 100644 --- a/modules/markup/html_test.go +++ b/modules/markup/html_test.go @@ -32,10 +32,10 @@ func TestRender_Commits(t *testing.T) { assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } - var sha = "65f1bf27bc3bf70f64657658635e66094edbcb4d" - var commit = util.URLJoin(AppSubURL, "commit", sha) - var subtree = util.URLJoin(commit, "src") - var tree = strings.ReplaceAll(subtree, "/commit/", "/tree/") + sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d" + commit := util.URLJoin(AppSubURL, "commit", sha) + subtree := util.URLJoin(commit, "src") + tree := strings.ReplaceAll(subtree, "/commit/", "/tree/") test(sha, `

65f1bf27bc

`) test(sha[:7], `

65f1bf2

`) @@ -78,8 +78,8 @@ func TestMisc_IsSameDomain(t *testing.T) { setting.AppURL = AppURL setting.AppSubURL = AppSubURL - var sha = "b6dd6210eaebc915fd5be5579c58cce4da2e2579" - var commit = util.URLJoin(AppSubURL, "commit", sha) + sha := "b6dd6210eaebc915fd5be5579c58cce4da2e2579" + commit := util.URLJoin(AppSubURL, "commit", sha) assert.True(t, IsSameDomain(commit)) assert.False(t, IsSameDomain("http://google.com/ncr")) @@ -258,7 +258,7 @@ func TestRender_emoji(t *testing.T) { `

`+emoji.GemojiData[i].Emoji+`

`) } - //Text that should be turned into or recognized as emoji + // Text that should be turned into or recognized as emoji test( ":gitea:", `

:gitea:

`) @@ -388,7 +388,7 @@ func Test_ParseClusterFuzz(t *testing.T) { setting.AppURL = AppURL setting.AppSubURL = AppSubURL - var localMetas = map[string]string{ + localMetas := map[string]string{ "user": "go-gitea", "repo": "gitea", } diff --git a/modules/markup/markdown/goldmark.go b/modules/markup/markdown/goldmark.go index 07e2e36e1da44..3ed81d7806080 100644 --- a/modules/markup/markdown/goldmark.go +++ b/modules/markup/markdown/goldmark.go @@ -42,7 +42,7 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa metaData := meta.GetItems(pc) firstChild := node.FirstChild() createTOC := false - var toc = []Header{} + toc := []Header{} rc := &RenderConfig{ Meta: "table", Icon: "table", @@ -227,7 +227,7 @@ func (p *prefixedIDs) Generate(value []byte, kind ast.NodeKind) []byte { } // Generate generates a new element id. -func (p *prefixedIDs) GenerateWithDefault(value []byte, dft []byte) []byte { +func (p *prefixedIDs) GenerateWithDefault(value, dft []byte) []byte { result := common.CleanValue(value) if len(result) == 0 { result = dft diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go index 93235d77e5afe..9b3ec3408e9ca 100644 --- a/modules/markup/markdown/markdown.go +++ b/modules/markup/markdown/markdown.go @@ -28,12 +28,16 @@ import ( "github.com/yuin/goldmark/util" ) -var converter goldmark.Markdown -var once = sync.Once{} +var ( + converter goldmark.Markdown + once = sync.Once{} +) -var urlPrefixKey = parser.NewContextKey() -var isWikiKey = parser.NewContextKey() -var renderMetasKey = parser.NewContextKey() +var ( + urlPrefixKey = parser.NewContextKey() + isWikiKey = parser.NewContextKey() + renderMetasKey = parser.NewContextKey() +) type closesWithError interface { io.WriteCloser @@ -155,7 +159,6 @@ func actualRender(body []byte, urlPrefix string, metas map[string]string, wikiMa util.Prioritized(NewHTMLRenderer(), 10), ), ) - }) rd, wr := io.Pipe() @@ -211,10 +214,8 @@ func render(body []byte, urlPrefix string, metas map[string]string, wikiMarkdown return actualRender(body, urlPrefix, metas, wikiMarkdown) } -var ( - // MarkupName describes markup's name - MarkupName = "markdown" -) +// MarkupName describes markup's name +var MarkupName = "markdown" func init() { markup.RegisterParser(Parser{}) diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go index 5b3ef21fb66b9..76c10b88e94ba 100644 --- a/modules/markup/markdown/markdown_test.go +++ b/modules/markup/markdown/markdown_test.go @@ -15,9 +15,11 @@ import ( "github.com/stretchr/testify/assert" ) -const AppURL = "http://localhost:3000/" -const Repo = "gogits/gogs" -const AppSubURL = AppURL + Repo + "/" +const ( + AppURL = "http://localhost:3000/" + Repo = "gogits/gogs" + AppSubURL = AppURL + Repo + "/" +) // these values should match the Repo const above var localMetas = map[string]string{ @@ -337,5 +339,4 @@ func TestRenderSiblingImages_Issue12925(t *testing.T) { ` res := string(RenderRaw([]byte(testcase), "", false)) assert.Equal(t, expected, res) - } diff --git a/modules/markup/markup.go b/modules/markup/markup.go index f8deb2b29b1a2..4ef5e76e7e5c2 100644 --- a/modules/markup/markup.go +++ b/modules/markup/markup.go @@ -71,7 +71,7 @@ func RenderByType(tp string, rawBytes []byte, urlPrefix string, metas map[string } // RenderString renders Markdown to HTML with special links and returns string type. -func RenderString(filename string, raw, urlPrefix string, metas map[string]string) string { +func RenderString(filename, raw, urlPrefix string, metas map[string]string) string { return string(renderFile(filename, []byte(raw), urlPrefix, metas, false)) } diff --git a/modules/markup/mdstripper/mdstripper.go b/modules/markup/mdstripper/mdstripper.go index 52464f3e1b376..64079194fff78 100644 --- a/modules/markup/mdstripper/mdstripper.go +++ b/modules/markup/mdstripper/mdstripper.go @@ -6,12 +6,11 @@ package mdstripper import ( "bytes" + "io" "net/url" "strings" "sync" - "io" - "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/markup/common" "code.gitea.io/gitea/modules/setting" @@ -148,8 +147,10 @@ func StripMarkdown(rawBytes []byte) (string, []string) { return string(buf), links } -var stripParser parser.Parser -var once = sync.Once{} +var ( + stripParser parser.Parser + once = sync.Once{} +) // StripMarkdownBytes parses markdown content by removing all markup and code blocks // in order to extract links and other references diff --git a/modules/markup/mdstripper/mdstripper_test.go b/modules/markup/mdstripper/mdstripper_test.go index 9efcc359496ca..180857dcd337b 100644 --- a/modules/markup/mdstripper/mdstripper_test.go +++ b/modules/markup/mdstripper/mdstripper_test.go @@ -52,7 +52,8 @@ A HIDDEN ` + "`" + `GHOST` + "`" + ` IN THIS LINE. }, []string{ "link", - }}, + }, + }, { "Simply closes: #29 yes", []string{ diff --git a/modules/markup/orgmode/orgmode.go b/modules/markup/orgmode/orgmode.go index ddd445aba2ad4..739be6328782f 100644 --- a/modules/markup/orgmode/orgmode.go +++ b/modules/markup/orgmode/orgmode.go @@ -22,8 +22,7 @@ func init() { } // Parser implements markup.Parser for orgmode -type Parser struct { -} +type Parser struct{} // Name implements markup.Parser func (Parser) Name() string { @@ -56,7 +55,7 @@ func Render(rawBytes []byte, urlPrefix string, metas map[string]string, isWiki b } // RenderString reners orgmode string to HTML string -func RenderString(rawContent string, urlPrefix string, metas map[string]string, isWiki bool) string { +func RenderString(rawContent, urlPrefix string, metas map[string]string, isWiki bool) string { return string(Render([]byte(rawContent), urlPrefix, metas, isWiki)) } diff --git a/modules/markup/orgmode/orgmode_test.go b/modules/markup/orgmode/orgmode_test.go index 020a3f592ad85..39f44fbc2cb6a 100644 --- a/modules/markup/orgmode/orgmode_test.go +++ b/modules/markup/orgmode/orgmode_test.go @@ -14,9 +14,11 @@ import ( "github.com/stretchr/testify/assert" ) -const AppURL = "http://localhost:3000/" -const Repo = "gogits/gogs" -const AppSubURL = AppURL + Repo + "/" +const ( + AppURL = "http://localhost:3000/" + Repo = "gogits/gogs" + AppSubURL = AppURL + Repo + "/" +) func TestRender_StandardLinks(t *testing.T) { setting.AppURL = AppURL diff --git a/modules/markup/sanitizer.go b/modules/markup/sanitizer.go index 9214a75fb355b..02de823f624dc 100644 --- a/modules/markup/sanitizer.go +++ b/modules/markup/sanitizer.go @@ -70,7 +70,8 @@ func ReplaceSanitizer() { sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^((icon(\s+[\p{L}\p{N}_-]+)+)|(emoji))$|^([a-z][a-z0-9]{0,2})$`)).OnElements("span") // Allow generally safe attributes - generalSafeAttrs := []string{"abbr", "accept", "accept-charset", + generalSafeAttrs := []string{ + "abbr", "accept", "accept-charset", "accesskey", "action", "align", "alt", "aria-describedby", "aria-hidden", "aria-label", "aria-labelledby", "axis", "border", "cellpadding", "cellspacing", "char", diff --git a/modules/metrics/collector.go b/modules/metrics/collector.go index 6f6cf7cb64659..fe8b167b15cfc 100644 --- a/modules/metrics/collector.go +++ b/modules/metrics/collector.go @@ -153,7 +153,6 @@ func NewCollector() Collector { nil, nil, ), } - } // Describe returns all possible prometheus.Desc diff --git a/modules/migrations/base/null_downloader.go b/modules/migrations/base/null_downloader.go index a93c20339b60d..b893de3af00c0 100644 --- a/modules/migrations/base/null_downloader.go +++ b/modules/migrations/base/null_downloader.go @@ -10,12 +10,9 @@ import ( ) // NullDownloader implements a blank downloader -type NullDownloader struct { -} +type NullDownloader struct{} -var ( - _ Downloader = &NullDownloader{} -) +var _ Downloader = &NullDownloader{} // SetContext set context func (n NullDownloader) SetContext(_ context.Context) {} diff --git a/modules/migrations/base/retry_downloader.go b/modules/migrations/base/retry_downloader.go index eeb3cabbc18fb..fa5cbf70d6b95 100644 --- a/modules/migrations/base/retry_downloader.go +++ b/modules/migrations/base/retry_downloader.go @@ -9,9 +9,7 @@ import ( "time" ) -var ( - _ Downloader = &RetryDownloader{} -) +var _ Downloader = &RetryDownloader{} // RetryDownloader retry the downloads type RetryDownloader struct { diff --git a/modules/migrations/dump.go b/modules/migrations/dump.go index 297095883be4b..7cfe95288ef69 100644 --- a/modules/migrations/dump.go +++ b/modules/migrations/dump.go @@ -25,9 +25,7 @@ import ( "gopkg.in/yaml.v2" ) -var ( - _ base.Uploader = &RepositoryDumper{} -) +var _ base.Uploader = &RepositoryDumper{} // RepositoryDumper implements an Uploader to the local directory type RepositoryDumper struct { @@ -401,7 +399,7 @@ func (g *RepositoryDumper) createItems(dir string, itemFiles map[int64]*os.File, // CreateComments creates comments of issues func (g *RepositoryDumper) CreateComments(comments ...*base.Comment) error { - var commentsMap = make(map[int64][]interface{}, len(comments)) + commentsMap := make(map[int64][]interface{}, len(comments)) for _, comment := range comments { commentsMap[comment.IssueIndex] = append(commentsMap[comment.IssueIndex], comment) } @@ -524,7 +522,7 @@ func (g *RepositoryDumper) CreatePullRequests(prs ...*base.PullRequest) error { // CreateReviews create pull request reviews func (g *RepositoryDumper) CreateReviews(reviews ...*base.Review) error { - var reviewsMap = make(map[int64][]interface{}, len(reviews)) + reviewsMap := make(map[int64][]interface{}, len(reviews)) for _, review := range reviews { reviewsMap[review.IssueIndex] = append(reviewsMap[review.IssueIndex], review) } @@ -564,12 +562,12 @@ func DumpRepository(ctx context.Context, baseDir, ownerName string, opts base.Mi } // RestoreRepository restore a repository from the disk directory -func RestoreRepository(ctx context.Context, baseDir string, ownerName, repoName string) error { +func RestoreRepository(ctx context.Context, baseDir, ownerName, repoName string) error { doer, err := models.GetAdminUser() if err != nil { return err } - var uploader = NewGiteaLocalUploader(ctx, doer, ownerName, repoName) + uploader := NewGiteaLocalUploader(ctx, doer, ownerName, repoName) downloader, err := NewRepositoryRestorer(ctx, baseDir, ownerName, repoName) if err != nil { return err diff --git a/modules/migrations/error.go b/modules/migrations/error.go index 1c77fa9f2f288..8bcb6ba93364e 100644 --- a/modules/migrations/error.go +++ b/modules/migrations/error.go @@ -11,10 +11,8 @@ import ( "github.com/google/go-github/v32/github" ) -var ( - // ErrRepoNotCreated returns the error that repository not created - ErrRepoNotCreated = errors.New("repository is not created yet") -) +// ErrRepoNotCreated returns the error that repository not created +var ErrRepoNotCreated = errors.New("repository is not created yet") // IsRateLimitError returns true if the err is github.RateLimitError func IsRateLimitError(err error) bool { diff --git a/modules/migrations/git.go b/modules/migrations/git.go index 7e4194547499b..f2fa74d0f3271 100644 --- a/modules/migrations/git.go +++ b/modules/migrations/git.go @@ -10,9 +10,7 @@ import ( "code.gitea.io/gitea/modules/migrations/base" ) -var ( - _ base.Downloader = &PlainGitDownloader{} -) +var _ base.Downloader = &PlainGitDownloader{} // PlainGitDownloader implements a Downloader interface to clone git from a http/https URL type PlainGitDownloader struct { diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 87ec9c102a1e7..d06285e8b4eed 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -32,8 +32,7 @@ func init() { } // GiteaDownloaderFactory defines a gitea downloader factory -type GiteaDownloaderFactory struct { -} +type GiteaDownloaderFactory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GiteaDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) { @@ -158,7 +157,7 @@ func (g *GiteaDownloader) GetTopics() ([]string, error) { // GetMilestones returns milestones func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { - var milestones = make([]*base.Milestone, 0, g.maxPerPage) + milestones := make([]*base.Milestone, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully @@ -223,7 +222,7 @@ func (g *GiteaDownloader) convertGiteaLabel(label *gitea_sdk.Label) *base.Label // GetLabels returns labels func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { - var labels = make([]*base.Label, 0, g.maxPerPage) + labels := make([]*base.Label, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully @@ -297,7 +296,7 @@ func (g *GiteaDownloader) convertGiteaRelease(rel *gitea_sdk.Release) *base.Rele // GetReleases returns releases func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { - var releases = make([]*base.Release, 0, g.maxPerPage) + releases := make([]*base.Release, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully @@ -372,7 +371,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err if perPage > g.maxPerPage { perPage = g.maxPerPage } - var allIssues = make([]*base.Issue, 0, perPage) + allIssues := make([]*base.Issue, 0, perPage) issues, _, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gitea_sdk.ListIssueOption{ ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: perPage}, @@ -384,7 +383,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err } for _, issue := range issues { - var labels = make([]*base.Label, 0, len(issue.Labels)) + labels := make([]*base.Label, 0, len(issue.Labels)) for i := range issue.Labels { labels = append(labels, g.convertGiteaLabel(issue.Labels[i])) } @@ -436,7 +435,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err // GetComments returns comments according issueNumber func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { - var allComments = make([]*base.Comment, 0, g.maxPerPage) + allComments := make([]*base.Comment, 0, g.maxPerPage) // for i := 1; ; i++ { // make sure gitea can shutdown gracefully @@ -489,7 +488,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques if perPage > g.maxPerPage { perPage = g.maxPerPage } - var allPRs = make([]*base.PullRequest, 0, perPage) + allPRs := make([]*base.PullRequest, 0, perPage) prs, _, err := g.client.ListRepoPullRequests(g.repoOwner, g.repoName, gitea_sdk.ListPullRequestsOptions{ ListOptions: gitea_sdk.ListOptions{ @@ -507,7 +506,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques milestone = pr.Milestone.Title } - var labels = make([]*base.Label, 0, len(pr.Labels)) + labels := make([]*base.Label, 0, len(pr.Labels)) for i := range pr.Labels { labels = append(labels, g.convertGiteaLabel(pr.Labels[i])) } @@ -615,7 +614,7 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { return nil, nil } - var allReviews = make([]*base.Review, 0, g.maxPerPage) + allReviews := make([]*base.Review, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully diff --git a/modules/migrations/gitea_uploader.go b/modules/migrations/gitea_uploader.go index aa1ea4bc09d04..03031ea6b0bb5 100644 --- a/modules/migrations/gitea_uploader.go +++ b/modules/migrations/gitea_uploader.go @@ -31,9 +31,7 @@ import ( gouuid "github.com/google/uuid" ) -var ( - _ base.Uploader = &GiteaLocalUploader{} -) +var _ base.Uploader = &GiteaLocalUploader{} // GiteaLocalUploader implements an Uploader to gitea sites type GiteaLocalUploader struct { @@ -154,7 +152,7 @@ func (g *GiteaLocalUploader) CreateTopics(topics ...string) error { // CreateMilestones creates milestones func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) error { - var mss = make([]*models.Milestone, 0, len(milestones)) + mss := make([]*models.Milestone, 0, len(milestones)) for _, milestone := range milestones { var deadline timeutil.TimeStamp if milestone.Deadline != nil { @@ -163,7 +161,7 @@ func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) err if deadline == 0 { deadline = timeutil.TimeStamp(time.Date(9999, 1, 1, 0, 0, 0, 0, setting.DefaultUILocation).Unix()) } - var ms = models.Milestone{ + ms := models.Milestone{ RepoID: g.repo.ID, Name: milestone.Title, Content: milestone.Description, @@ -189,7 +187,7 @@ func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) err // CreateLabels creates labels func (g *GiteaLocalUploader) CreateLabels(labels ...*base.Label) error { - var lbs = make([]*models.Label, 0, len(labels)) + lbs := make([]*models.Label, 0, len(labels)) for _, label := range labels { lbs = append(lbs, &models.Label{ RepoID: g.repo.ID, @@ -211,9 +209,9 @@ func (g *GiteaLocalUploader) CreateLabels(labels ...*base.Label) error { // CreateReleases creates releases func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error { - var rels = make([]*models.Release, 0, len(releases)) + rels := make([]*models.Release, 0, len(releases)) for _, release := range releases { - var rel = models.Release{ + rel := models.Release{ RepoID: g.repo.ID, TagName: release.TagName, LowerTagName: strings.ToLower(release.TagName), @@ -259,7 +257,7 @@ func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error { } for _, asset := range release.Assets { - var attach = models.Attachment{ + attach := models.Attachment{ UUID: gouuid.New().String(), Name: asset.Name, DownloadCount: int64(*asset.DownloadCount), @@ -306,7 +304,7 @@ func (g *GiteaLocalUploader) SyncTags() error { // CreateIssues creates issues func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error { - var iss = make([]*models.Issue, 0, len(issues)) + iss := make([]*models.Issue, 0, len(issues)) for _, issue := range issues { var labels []*models.Label for _, label := range issue.Labels { @@ -324,7 +322,7 @@ func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error { } } - var is = models.Issue{ + is := models.Issue{ RepoID: g.repo.ID, Repo: g.repo, Index: issue.Number, @@ -376,7 +374,7 @@ func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error { g.userMap[reaction.UserID] = userid } } - var res = models.Reaction{ + res := models.Reaction{ Type: reaction.Content, CreatedUnix: timeutil.TimeStampNow(), } @@ -407,7 +405,7 @@ func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error { // CreateComments creates comments of issues func (g *GiteaLocalUploader) CreateComments(comments ...*base.Comment) error { - var cms = make([]*models.Comment, 0, len(comments)) + cms := make([]*models.Comment, 0, len(comments)) for _, comment := range comments { var issueID int64 if issueIDStr, ok := g.issues.Load(comment.IssueIndex); !ok { @@ -463,7 +461,7 @@ func (g *GiteaLocalUploader) CreateComments(comments ...*base.Comment) error { g.userMap[reaction.UserID] = userid } } - var res = models.Reaction{ + res := models.Reaction{ Type: reaction.Content, CreatedUnix: timeutil.TimeStampNow(), } @@ -488,7 +486,7 @@ func (g *GiteaLocalUploader) CreateComments(comments ...*base.Comment) error { // CreatePullRequests creates pull requests func (g *GiteaLocalUploader) CreatePullRequests(prs ...*base.PullRequest) error { - var gprs = make([]*models.PullRequest, 0, len(prs)) + gprs := make([]*models.PullRequest, 0, len(prs)) for _, pr := range prs { gpr, err := g.newPullRequest(pr) if err != nil { @@ -584,7 +582,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullR return nil, err } - var head = "unknown repository" + head := "unknown repository" if pr.IsForkPullRequest() && pr.State != "closed" { if pr.Head.OwnerName != "" { remote := pr.Head.OwnerName @@ -626,7 +624,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullR head = pr.Head.Ref } - var issue = models.Issue{ + issue := models.Issue{ RepoID: g.repo.ID, Repo: g.repo, Title: pr.Title, @@ -676,7 +674,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullR g.userMap[reaction.UserID] = userid } } - var res = models.Reaction{ + res := models.Reaction{ Type: reaction.Content, CreatedUnix: timeutil.TimeStampNow(), } @@ -690,7 +688,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullR issue.Reactions = append(issue.Reactions, &res) } - var pullRequest = models.PullRequest{ + pullRequest := models.PullRequest{ HeadRepoID: g.repo.ID, HeadBranch: head, BaseRepoID: g.repo.ID, @@ -733,7 +731,7 @@ func convertReviewState(state string) models.ReviewType { // CreateReviews create pull request reviews func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error { - var cms = make([]*models.Review, 0, len(reviews)) + cms := make([]*models.Review, 0, len(reviews)) for _, review := range reviews { var issueID int64 if issueIDStr, ok := g.issues.Load(review.IssueIndex); !ok { @@ -760,7 +758,7 @@ func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error { } } - var cm = models.Review{ + cm := models.Review{ Type: convertReviewState(review.State), IssueID: issueID, Content: review.Content, @@ -816,7 +814,7 @@ func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error { patch, _ = git.CutDiffAroundLine(reader, int64((&models.Comment{Line: int64(line + comment.Position - 1)}).UnsignedLine()), line < 0, setting.UI.CodeCommentLines) - var c = models.Comment{ + c := models.Comment{ Type: models.CommentTypeCode, PosterID: comment.PosterID, IssueID: issueID, diff --git a/modules/migrations/github.go b/modules/migrations/github.go index cb61086b2ad6b..4e0256bcc1051 100644 --- a/modules/migrations/github.go +++ b/modules/migrations/github.go @@ -35,8 +35,7 @@ func init() { } // GithubDownloaderV3Factory defines a github downloader v3 factory -type GithubDownloaderV3Factory struct { -} +type GithubDownloaderV3Factory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GithubDownloaderV3Factory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) { @@ -76,7 +75,7 @@ type GithubDownloaderV3 struct { // NewGithubDownloaderV3 creates a github Downloader via github v3 API func NewGithubDownloaderV3(ctx context.Context, baseURL, userName, password, token, repoOwner, repoName string) *GithubDownloaderV3 { - var downloader = GithubDownloaderV3{ + downloader := GithubDownloaderV3{ userName: userName, password: password, ctx: ctx, @@ -178,8 +177,8 @@ func (g *GithubDownloaderV3) GetTopics() ([]string, error) { // GetMilestones returns milestones func (g *GithubDownloaderV3) GetMilestones() ([]*base.Milestone, error) { - var perPage = g.maxPerPage - var milestones = make([]*base.Milestone, 0, perPage) + perPage := g.maxPerPage + milestones := make([]*base.Milestone, 0, perPage) for i := 1; ; i++ { g.sleep() ms, resp, err := g.client.Issues.ListMilestones(g.ctx, g.repoOwner, g.repoName, @@ -188,7 +187,8 @@ func (g *GithubDownloaderV3) GetMilestones() ([]*base.Milestone, error) { ListOptions: github.ListOptions{ Page: i, PerPage: perPage, - }}) + }, + }) if err != nil { return nil, err } @@ -199,7 +199,7 @@ func (g *GithubDownloaderV3) GetMilestones() ([]*base.Milestone, error) { if m.Description != nil { desc = *m.Description } - var state = "open" + state := "open" if m.State != nil { state = *m.State } @@ -234,8 +234,8 @@ func convertGithubLabel(label *github.Label) *base.Label { // GetLabels returns labels func (g *GithubDownloaderV3) GetLabels() ([]*base.Label, error) { - var perPage = g.maxPerPage - var labels = make([]*base.Label, 0, perPage) + perPage := g.maxPerPage + labels := make([]*base.Label, 0, perPage) for i := 1; ; i++ { g.sleep() ls, resp, err := g.client.Issues.ListLabels(g.ctx, g.repoOwner, g.repoName, @@ -290,7 +290,7 @@ func (g *GithubDownloaderV3) convertGithubRelease(rel *github.RepositoryRelease) } for _, asset := range rel.Assets { - var assetID = *asset.ID // Don't optimize this, for closure we need a local variable + assetID := *asset.ID // Don't optimize this, for closure we need a local variable r.Assets = append(r.Assets, &base.ReleaseAsset{ ID: *asset.ID, Name: *asset.Name, @@ -337,8 +337,8 @@ func (g *GithubDownloaderV3) convertGithubRelease(rel *github.RepositoryRelease) // GetReleases returns releases func (g *GithubDownloaderV3) GetReleases() ([]*base.Release, error) { - var perPage = g.maxPerPage - var releases = make([]*base.Release, 0, perPage) + perPage := g.maxPerPage + releases := make([]*base.Release, 0, perPage) for i := 1; ; i++ { g.sleep() ls, resp, err := g.client.Repositories.ListReleases(g.ctx, g.repoOwner, g.repoName, @@ -376,7 +376,7 @@ func (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool, }, } - var allIssues = make([]*base.Issue, 0, perPage) + allIssues := make([]*base.Issue, 0, perPage) g.sleep() issues, resp, err := g.client.Issues.ListByRepo(g.ctx, g.repoOwner, g.repoName, opt) if err != nil { @@ -396,7 +396,7 @@ func (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool, if issue.Milestone != nil { milestone = *issue.Milestone.Title } - var labels = make([]*base.Label, 0, len(issue.Labels)) + labels := make([]*base.Label, 0, len(issue.Labels)) for _, l := range issue.Labels { labels = append(labels, convertGithubLabel(l)) } @@ -534,7 +534,7 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReq Page: page, }, } - var allPRs = make([]*base.PullRequest, 0, perPage) + allPRs := make([]*base.PullRequest, 0, perPage) g.sleep() prs, resp, err := g.client.PullRequests.List(g.ctx, g.repoOwner, g.repoName, opt) if err != nil { @@ -550,7 +550,7 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReq if pr.Milestone != nil { milestone = *pr.Milestone.Title } - var labels = make([]*base.Label, 0, len(pr.Labels)) + labels := make([]*base.Label, 0, len(pr.Labels)) for _, l := range pr.Labels { labels = append(labels, convertGithubLabel(l)) } @@ -670,7 +670,7 @@ func convertGithubReview(r *github.PullRequestReview) *base.Review { } func (g *GithubDownloaderV3) convertGithubReviewComments(cs []*github.PullRequestComment) ([]*base.ReviewComment, error) { - var rcs = make([]*base.ReviewComment, 0, len(cs)) + rcs := make([]*base.ReviewComment, 0, len(cs)) for _, c := range cs { // get reactions var reactions []*base.Reaction @@ -715,7 +715,7 @@ func (g *GithubDownloaderV3) convertGithubReviewComments(cs []*github.PullReques // GetReviews returns pull requests review func (g *GithubDownloaderV3) GetReviews(pullRequestNumber int64) ([]*base.Review, error) { - var allReviews = make([]*base.Review, 0, g.maxPerPage) + allReviews := make([]*base.Review, 0, g.maxPerPage) opt := &github.ListOptions{ PerPage: g.maxPerPage, } diff --git a/modules/migrations/github_test.go b/modules/migrations/github_test.go index efa8b6ba9bbb3..6844701483db5 100644 --- a/modules/migrations/github_test.go +++ b/modules/migrations/github_test.go @@ -64,7 +64,7 @@ func assertLabelEqual(t *testing.T, name, color, description string, label *base } func TestGitHubDownloadRepo(t *testing.T) { - GithubLimitRateRemaining = 3 //Wait at 3 remaining since we could have 3 CI in // + GithubLimitRateRemaining = 3 // Wait at 3 remaining since we could have 3 CI in // downloader := NewGithubDownloaderV3(context.Background(), "https://github.com", "", "", os.Getenv("GITHUB_READ_TOKEN"), "go-gitea", "test_repo") err := downloader.RefreshRate() assert.NoError(t, err) @@ -276,7 +276,7 @@ func TestGitHubDownloadRepo(t *testing.T) { assert.EqualValues(t, 2, len(prs)) closed1 = time.Date(2019, 11, 12, 21, 39, 27, 0, time.UTC) - var merged1 = time.Date(2019, 11, 12, 21, 39, 27, 0, time.UTC) + merged1 := time.Date(2019, 11, 12, 21, 39, 27, 0, time.UTC) assert.EqualValues(t, []*base.PullRequest{ { @@ -391,7 +391,7 @@ func TestGitHubDownloadRepo(t *testing.T) { ReviewerID: 165205, ReviewerName: "lafriks", CommitID: "076160cf0b039f13e5eff19619932d181269414b", - CreatedAt: time.Date(2019, 11, 12, 21, 38, 00, 0, time.UTC), + CreatedAt: time.Date(2019, 11, 12, 21, 38, 0o0, 0, time.UTC), State: base.ReviewStateApproved, }, }, reviews) @@ -405,7 +405,7 @@ func TestGitHubDownloadRepo(t *testing.T) { ReviewerID: 81045, ReviewerName: "lunny", CommitID: "2be9101c543658591222acbee3eb799edfc3853d", - CreatedAt: time.Date(2020, 01, 04, 05, 33, 18, 0, time.UTC), + CreatedAt: time.Date(2020, 0o1, 0o4, 0o5, 33, 18, 0, time.UTC), State: base.ReviewStateApproved, Comments: []*base.ReviewComment{ { @@ -416,8 +416,8 @@ func TestGitHubDownloadRepo(t *testing.T) { Position: 3, CommitID: "2be9101c543658591222acbee3eb799edfc3853d", PosterID: 81045, - CreatedAt: time.Date(2020, 01, 04, 05, 33, 06, 0, time.UTC), - UpdatedAt: time.Date(2020, 01, 04, 05, 33, 18, 0, time.UTC), + CreatedAt: time.Date(2020, 0o1, 0o4, 0o5, 33, 0o6, 0, time.UTC), + UpdatedAt: time.Date(2020, 0o1, 0o4, 0o5, 33, 18, 0, time.UTC), }, }, }, @@ -427,7 +427,7 @@ func TestGitHubDownloadRepo(t *testing.T) { ReviewerID: 81045, ReviewerName: "lunny", CommitID: "2be9101c543658591222acbee3eb799edfc3853d", - CreatedAt: time.Date(2020, 01, 04, 06, 07, 06, 0, time.UTC), + CreatedAt: time.Date(2020, 0o1, 0o4, 0o6, 0o7, 0o6, 0, time.UTC), State: base.ReviewStateChangesRequested, Content: "Don't add more reviews", }, @@ -437,7 +437,7 @@ func TestGitHubDownloadRepo(t *testing.T) { ReviewerID: 81045, ReviewerName: "lunny", CommitID: "2be9101c543658591222acbee3eb799edfc3853d", - CreatedAt: time.Date(2020, 01, 04, 11, 21, 41, 0, time.UTC), + CreatedAt: time.Date(2020, 0o1, 0o4, 11, 21, 41, 0, time.UTC), State: base.ReviewStateCommented, Comments: []*base.ReviewComment{ { @@ -448,8 +448,8 @@ func TestGitHubDownloadRepo(t *testing.T) { Position: 4, CommitID: "2be9101c543658591222acbee3eb799edfc3853d", PosterID: 81045, - CreatedAt: time.Date(2020, 01, 04, 11, 21, 41, 0, time.UTC), - UpdatedAt: time.Date(2020, 01, 04, 11, 21, 41, 0, time.UTC), + CreatedAt: time.Date(2020, 0o1, 0o4, 11, 21, 41, 0, time.UTC), + UpdatedAt: time.Date(2020, 0o1, 0o4, 11, 21, 41, 0, time.UTC), }, }, }, diff --git a/modules/migrations/gitlab.go b/modules/migrations/gitlab.go index a697075ff892b..7dae5bacddb9f 100644 --- a/modules/migrations/gitlab.go +++ b/modules/migrations/gitlab.go @@ -32,8 +32,7 @@ func init() { } // GitlabDownloaderFactory defines a gitlab downloader factory -type GitlabDownloaderFactory struct { -} +type GitlabDownloaderFactory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GitlabDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) { @@ -187,16 +186,17 @@ func (g *GitlabDownloader) GetTopics() ([]string, error) { // GetMilestones returns milestones func (g *GitlabDownloader) GetMilestones() ([]*base.Milestone, error) { - var perPage = g.maxPerPage - var state = "all" - var milestones = make([]*base.Milestone, 0, perPage) + perPage := g.maxPerPage + state := "all" + milestones := make([]*base.Milestone, 0, perPage) for i := 1; ; i++ { ms, _, err := g.client.Milestones.ListMilestones(g.repoID, &gitlab.ListMilestonesOptions{ State: &state, ListOptions: gitlab.ListOptions{ Page: i, PerPage: perPage, - }}, nil, gitlab.WithContext(g.ctx)) + }, + }, nil, gitlab.WithContext(g.ctx)) if err != nil { return nil, err } @@ -206,7 +206,7 @@ func (g *GitlabDownloader) GetMilestones() ([]*base.Milestone, error) { if m.Description != "" { desc = m.Description } - var state = "open" + state := "open" var closedAt *time.Time if m.State != "" { state = m.State @@ -258,8 +258,8 @@ func (g *GitlabDownloader) normalizeColor(val string) string { // GetLabels returns labels func (g *GitlabDownloader) GetLabels() ([]*base.Label, error) { - var perPage = g.maxPerPage - var labels = make([]*base.Label, 0, perPage) + perPage := g.maxPerPage + labels := make([]*base.Label, 0, perPage) for i := 1; ; i++ { ls, _, err := g.client.Labels.ListLabels(g.repoID, &gitlab.ListLabelsOptions{ListOptions: gitlab.ListOptions{ Page: i, @@ -329,8 +329,8 @@ func (g *GitlabDownloader) convertGitlabRelease(rel *gitlab.Release) *base.Relea // GetReleases returns releases func (g *GitlabDownloader) GetReleases() ([]*base.Release, error) { - var perPage = g.maxPerPage - var releases = make([]*base.Release, 0, perPage) + perPage := g.maxPerPage + releases := make([]*base.Release, 0, perPage) for i := 1; ; i++ { ls, _, err := g.client.Releases.ListReleases(g.repoID, &gitlab.ListReleasesOptions{ Page: i, @@ -369,7 +369,7 @@ func (g *GitlabDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, er }, } - var allIssues = make([]*base.Issue, 0, perPage) + allIssues := make([]*base.Issue, 0, perPage) issues, _, err := g.client.Issues.ListProjectIssues(g.repoID, opt, nil, gitlab.WithContext(g.ctx)) if err != nil { @@ -377,7 +377,7 @@ func (g *GitlabDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, er } for _, issue := range issues { - var labels = make([]*base.Label, 0, len(issue.Labels)) + labels := make([]*base.Label, 0, len(issue.Labels)) for _, l := range issue.Labels { labels = append(labels, &base.Label{ Name: l, @@ -390,7 +390,7 @@ func (g *GitlabDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, er } var reactions []*base.Reaction - var awardPage = 1 + awardPage := 1 for { awards, _, err := g.client.AwardEmoji.ListIssueAwardEmoji(g.repoID, issue.IID, &gitlab.ListAwardEmojiOptions{Page: awardPage, PerPage: perPage}, gitlab.WithContext(g.ctx)) if err != nil { @@ -431,9 +431,9 @@ func (g *GitlabDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, er // GetComments returns comments according issueNumber // TODO: figure out how to transfer comment reactions func (g *GitlabDownloader) GetComments(issueNumber int64) ([]*base.Comment, error) { - var allComments = make([]*base.Comment, 0, g.maxPerPage) + allComments := make([]*base.Comment, 0, g.maxPerPage) - var page = 1 + page := 1 var realIssueNumber int64 for { @@ -483,7 +483,6 @@ func (g *GitlabDownloader) GetComments(issueNumber int64) ([]*base.Comment, erro Created: *c.CreatedAt, }) } - } if resp.NextPage == 0 { break @@ -509,7 +508,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque // Set fetchPRcomments to true here, so PR comments are fetched instead of Issue comments g.fetchPRcomments = true - var allPRs = make([]*base.PullRequest, 0, perPage) + allPRs := make([]*base.PullRequest, 0, perPage) prs, _, err := g.client.MergeRequests.ListProjectMergeRequests(g.repoID, opt, nil, gitlab.WithContext(g.ctx)) if err != nil { @@ -517,7 +516,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque } for _, pr := range prs { - var labels = make([]*base.Label, 0, len(pr.Labels)) + labels := make([]*base.Label, 0, len(pr.Labels)) for _, l := range pr.Labels { labels = append(labels, &base.Label{ Name: l, @@ -530,12 +529,12 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque pr.State = "closed" } - var mergeTime = pr.MergedAt + mergeTime := pr.MergedAt if merged && pr.MergedAt == nil { mergeTime = pr.UpdatedAt } - var closeTime = pr.ClosedAt + closeTime := pr.ClosedAt if merged && pr.ClosedAt == nil { closeTime = pr.UpdatedAt } @@ -551,7 +550,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque } var reactions []*base.Reaction - var awardPage = 1 + awardPage := 1 for { awards, _, err := g.client.AwardEmoji.ListMergeRequestAwardEmoji(g.repoID, pr.IID, &gitlab.ListAwardEmojiOptions{Page: awardPage, PerPage: perPage}, gitlab.WithContext(g.ctx)) if err != nil { @@ -625,7 +624,7 @@ func (g *GitlabDownloader) GetReviews(pullRequestNumber int64) ([]*base.Review, } } - var reviews = make([]*base.Review, 0, len(approvers)) + reviews := make([]*base.Review, 0, len(approvers)) for id, name := range approvers { reviews = append(reviews, &base.Review{ ReviewerID: int64(id), diff --git a/modules/migrations/gitlab_test.go b/modules/migrations/gitlab_test.go index f64d72147cf5c..ef0a0fd065cbd 100644 --- a/modules/migrations/gitlab_test.go +++ b/modules/migrations/gitlab_test.go @@ -151,7 +151,8 @@ func TestGitlabDownloadRepo(t *testing.T) { UserID: 1241334, UserName: "lafriks", Content: "open_mouth", - }}, + }, + }, Closed: &closed1, }, { @@ -199,7 +200,8 @@ func TestGitlabDownloadRepo(t *testing.T) { UserID: 1241334, UserName: "lafriks", Content: "hearts", - }}, + }, + }, Closed: &closed2, }, }, issues) @@ -316,5 +318,4 @@ func TestGitlabDownloadRepo(t *testing.T) { assert.EqualValues(t, "real6543", rvs[0].ReviewerName) assert.EqualValues(t, "APPROVED", rvs[0].State) } - } diff --git a/modules/migrations/gogs.go b/modules/migrations/gogs.go index b616907938ff4..0f121e29d3d69 100644 --- a/modules/migrations/gogs.go +++ b/modules/migrations/gogs.go @@ -29,8 +29,7 @@ func init() { } // GogsDownloaderFactory defines a gogs downloader factory -type GogsDownloaderFactory struct { -} +type GogsDownloaderFactory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GogsDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) { @@ -80,7 +79,7 @@ func (g *GogsDownloader) SetContext(ctx context.Context) { // NewGogsDownloader creates a gogs Downloader via gogs API func NewGogsDownloader(ctx context.Context, baseURL, userName, password, token, repoOwner, repoName string) *GogsDownloader { - var downloader = GogsDownloader{ + downloader := GogsDownloader{ ctx: ctx, baseURL: baseURL, userName: userName, @@ -138,8 +137,8 @@ func (g *GogsDownloader) GetRepoInfo() (*base.Repository, error) { // GetMilestones returns milestones func (g *GogsDownloader) GetMilestones() ([]*base.Milestone, error) { - var perPage = 100 - var milestones = make([]*base.Milestone, 0, perPage) + perPage := 100 + milestones := make([]*base.Milestone, 0, perPage) ms, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName) if err != nil { @@ -165,8 +164,8 @@ func (g *GogsDownloader) GetMilestones() ([]*base.Milestone, error) { // GetLabels returns labels func (g *GogsDownloader) GetLabels() ([]*base.Label, error) { - var perPage = 100 - var labels = make([]*base.Label, 0, perPage) + perPage := 100 + labels := make([]*base.Label, 0, perPage) ls, err := g.client.ListRepoLabels(g.repoOwner, g.repoName) if err != nil { return nil, err @@ -206,7 +205,7 @@ func (g *GogsDownloader) GetIssues(page, _ int) ([]*base.Issue, bool, error) { } func (g *GogsDownloader) getIssues(page int, state string) ([]*base.Issue, bool, error) { - var allIssues = make([]*base.Issue, 0, 10) + allIssues := make([]*base.Issue, 0, 10) issues, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gogs.ListIssueOption{ Page: page, @@ -228,7 +227,7 @@ func (g *GogsDownloader) getIssues(page int, state string) ([]*base.Issue, bool, // GetComments returns comments according issueNumber func (g *GogsDownloader) GetComments(issueNumber int64) ([]*base.Comment, error) { - var allComments = make([]*base.Comment, 0, 100) + allComments := make([]*base.Comment, 0, 100) comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, issueNumber) if err != nil { @@ -279,7 +278,7 @@ func convertGogsIssue(issue *gogs.Issue) *base.Issue { if issue.Milestone != nil { milestone = issue.Milestone.Title } - var labels = make([]*base.Label, 0, len(issue.Labels)) + labels := make([]*base.Label, 0, len(issue.Labels)) for _, l := range issue.Labels { labels = append(labels, convertGogsLabel(l)) } diff --git a/modules/migrations/gogs_test.go b/modules/migrations/gogs_test.go index c240ae6432acc..69114ed9370c7 100644 --- a/modules/migrations/gogs_test.go +++ b/modules/migrations/gogs_test.go @@ -92,7 +92,7 @@ func TestGogsDownloadRepo(t *testing.T) { PosterName: "lunny", PosterEmail: "xiaolunwen@gmail.com", State: "open", - Created: time.Date(2019, 06, 11, 8, 16, 44, 0, time.UTC), + Created: time.Date(2019, 0o6, 11, 8, 16, 44, 0, time.UTC), Labels: []*base.Label{ { Name: "bug", @@ -110,8 +110,8 @@ func TestGogsDownloadRepo(t *testing.T) { { PosterName: "lunny", PosterEmail: "xiaolunwen@gmail.com", - Created: time.Date(2019, 06, 11, 8, 19, 50, 0, time.UTC), - Updated: time.Date(2019, 06, 11, 8, 19, 50, 0, time.UTC), + Created: time.Date(2019, 0o6, 11, 8, 19, 50, 0, time.UTC), + Updated: time.Date(2019, 0o6, 11, 8, 19, 50, 0, time.UTC), Content: `1111`, }, }, comments) diff --git a/modules/migrations/migrate.go b/modules/migrations/migrate.go index 75fee80a3992b..8ba4cab58df73 100644 --- a/modules/migrations/migrate.go +++ b/modules/migrations/migrate.go @@ -109,7 +109,7 @@ func MigrateRepository(ctx context.Context, doer *models.User, ownerName string, return nil, err } - var uploader = NewGiteaLocalUploader(ctx, doer, ownerName, opts.RepoName) + uploader := NewGiteaLocalUploader(ctx, doer, ownerName, opts.RepoName) uploader.gitServiceType = opts.GitServiceType if err := migrateRepository(downloader, uploader, opts); err != nil { @@ -279,7 +279,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts if opts.Issues { log.Trace("migrating issues and comments") - var issueBatchSize = uploader.MaxBatchInsertSize("issue") + issueBatchSize := uploader.MaxBatchInsertSize("issue") for i := 1; ; i++ { issues, isEnd, err := downloader.GetIssues(i, issueBatchSize) @@ -296,7 +296,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts } if opts.Comments { - var allComments = make([]*base.Comment, 0, commentBatchSize) + allComments := make([]*base.Comment, 0, commentBatchSize) for _, issue := range issues { log.Trace("migrating issue %d's comments", issue.Number) comments, err := downloader.GetComments(issue.Number) @@ -333,7 +333,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts if opts.PullRequests { log.Trace("migrating pull requests and comments") - var prBatchSize = uploader.MaxBatchInsertSize("pullrequest") + prBatchSize := uploader.MaxBatchInsertSize("pullrequest") for i := 1; ; i++ { prs, isEnd, err := downloader.GetPullRequests(i, prBatchSize) if err != nil { @@ -350,7 +350,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts if opts.Comments { // plain comments - var allComments = make([]*base.Comment, 0, commentBatchSize) + allComments := make([]*base.Comment, 0, commentBatchSize) for _, pr := range prs { log.Trace("migrating pull request %d's comments", pr.Number) comments, err := downloader.GetComments(pr.Number) @@ -377,7 +377,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts } // migrate reviews - var allReviews = make([]*base.Review, 0, reviewBatchSize) + allReviews := make([]*base.Review, 0, reviewBatchSize) for _, pr := range prs { number := pr.Number diff --git a/modules/migrations/restore.go b/modules/migrations/restore.go index 4e63df14292ad..ecfc09544279b 100644 --- a/modules/migrations/restore.go +++ b/modules/migrations/restore.go @@ -27,7 +27,7 @@ type RepositoryRestorer struct { } // NewRepositoryRestorer creates a repository restorer which could restore repository from a dumped folder -func NewRepositoryRestorer(ctx context.Context, baseDir string, owner, repoName string) (*RepositoryRestorer, error) { +func NewRepositoryRestorer(ctx context.Context, baseDir, owner, repoName string) (*RepositoryRestorer, error) { baseDir, err := filepath.Abs(baseDir) if err != nil { return nil, err @@ -60,7 +60,7 @@ func (r *RepositoryRestorer) getRepoOptions() (map[string]string, error) { return nil, err } - var opts = make(map[string]string) + opts := make(map[string]string) err = yaml.Unmarshal(bs, &opts) if err != nil { return nil, err @@ -92,7 +92,7 @@ func (r *RepositoryRestorer) GetRepoInfo() (*base.Repository, error) { func (r *RepositoryRestorer) GetTopics() ([]string, error) { p := filepath.Join(r.baseDir, "topic.yml") - var topics = struct { + topics := struct { Topics []string `yaml:"topics"` }{} @@ -110,7 +110,7 @@ func (r *RepositoryRestorer) GetTopics() ([]string, error) { // GetMilestones returns milestones func (r *RepositoryRestorer) GetMilestones() ([]*base.Milestone, error) { - var milestones = make([]*base.Milestone, 0, 10) + milestones := make([]*base.Milestone, 0, 10) p := filepath.Join(r.baseDir, "milestone.yml") _, err := os.Stat(p) if err != nil { @@ -134,7 +134,7 @@ func (r *RepositoryRestorer) GetMilestones() ([]*base.Milestone, error) { // GetReleases returns releases func (r *RepositoryRestorer) GetReleases() ([]*base.Release, error) { - var releases = make([]*base.Release, 0, 10) + releases := make([]*base.Release, 0, 10) p := filepath.Join(r.baseDir, "release.yml") _, err := os.Stat(p) if err != nil { @@ -163,7 +163,7 @@ func (r *RepositoryRestorer) GetReleases() ([]*base.Release, error) { // GetLabels returns labels func (r *RepositoryRestorer) GetLabels() ([]*base.Label, error) { - var labels = make([]*base.Label, 0, 10) + labels := make([]*base.Label, 0, 10) p := filepath.Join(r.baseDir, "label.yml") _, err := os.Stat(p) if err != nil { @@ -187,7 +187,7 @@ func (r *RepositoryRestorer) GetLabels() ([]*base.Label, error) { // GetIssues returns issues according start and limit func (r *RepositoryRestorer) GetIssues(page, perPage int) ([]*base.Issue, bool, error) { - var issues = make([]*base.Issue, 0, 10) + issues := make([]*base.Issue, 0, 10) p := filepath.Join(r.baseDir, "issue.yml") _, err := os.Stat(p) if err != nil { @@ -211,7 +211,7 @@ func (r *RepositoryRestorer) GetIssues(page, perPage int) ([]*base.Issue, bool, // GetComments returns comments according issueNumber func (r *RepositoryRestorer) GetComments(issueNumber int64) ([]*base.Comment, error) { - var comments = make([]*base.Comment, 0, 10) + comments := make([]*base.Comment, 0, 10) p := filepath.Join(r.commentDir(), fmt.Sprintf("%d.yml", issueNumber)) _, err := os.Stat(p) if err != nil { @@ -235,7 +235,7 @@ func (r *RepositoryRestorer) GetComments(issueNumber int64) ([]*base.Comment, er // GetPullRequests returns pull requests according page and perPage func (r *RepositoryRestorer) GetPullRequests(page, perPage int) ([]*base.PullRequest, bool, error) { - var pulls = make([]*base.PullRequest, 0, 10) + pulls := make([]*base.PullRequest, 0, 10) p := filepath.Join(r.baseDir, "pull_request.yml") _, err := os.Stat(p) if err != nil { @@ -262,7 +262,7 @@ func (r *RepositoryRestorer) GetPullRequests(page, perPage int) ([]*base.PullReq // GetReviews returns pull requests review func (r *RepositoryRestorer) GetReviews(pullRequestNumber int64) ([]*base.Review, error) { - var reviews = make([]*base.Review, 0, 10) + reviews := make([]*base.Review, 0, 10) p := filepath.Join(r.reviewDir(), fmt.Sprintf("%d.yml", pullRequestNumber)) _, err := os.Stat(p) if err != nil { diff --git a/modules/nosql/redis.go b/modules/nosql/redis.go index 528f5fc802c84..13795f3d7bc21 100644 --- a/modules/nosql/redis.go +++ b/modules/nosql/redis.go @@ -45,7 +45,6 @@ func ToRedisURI(connection string) *url.URL { if len(fields) == 1 { // It's a comma delimited string, then... fields = strings.Split(connection, ",") - } for _, f := range fields { items := strings.SplitN(f, "=", 2) diff --git a/modules/notification/action/action.go b/modules/notification/action/action.go index 3530e48b1cebd..4839d81a325de 100644 --- a/modules/notification/action/action.go +++ b/modules/notification/action/action.go @@ -20,9 +20,7 @@ type actionNotifier struct { base.NullNotifier } -var ( - _ base.Notifier = &actionNotifier{} -) +var _ base.Notifier = &actionNotifier{} // NewNotifier create a new actionNotifier notifier func NewNotifier() base.Notifier { @@ -177,7 +175,7 @@ func (a *actionNotifier) NotifyTransferRepository(doer *models.User, repo *model } } -func (a *actionNotifier) NotifyCreateRepository(doer *models.User, u *models.User, repo *models.Repository) { +func (a *actionNotifier) NotifyCreateRepository(doer, u *models.User, repo *models.Repository) { if err := models.NotifyWatchers(&models.Action{ ActUserID: doer.ID, ActUser: doer, @@ -213,7 +211,7 @@ func (a *actionNotifier) NotifyPullRequestReview(pr *models.PullRequest, review return } - var actions = make([]*models.Action, 0, 10) + actions := make([]*models.Action, 0, 10) for _, lines := range review.CodeComments { for _, comments := range lines { for _, comm := range comments { diff --git a/modules/notification/base/notifier.go b/modules/notification/base/notifier.go index 8f8aa659b45d9..d0699f65128e1 100644 --- a/modules/notification/base/notifier.go +++ b/modules/notification/base/notifier.go @@ -13,8 +13,8 @@ import ( type Notifier interface { Run() - NotifyCreateRepository(doer *models.User, u *models.User, repo *models.Repository) - NotifyMigrateRepository(doer *models.User, u *models.User, repo *models.Repository) + NotifyCreateRepository(doer, u *models.User, repo *models.Repository) + NotifyMigrateRepository(doer, u *models.User, repo *models.Repository) NotifyDeleteRepository(doer *models.User, repo *models.Repository) NotifyForkRepository(doer *models.User, oldRepo, repo *models.Repository) NotifyRenameRepository(doer *models.User, repo *models.Repository, oldRepoName string) @@ -30,7 +30,7 @@ type Notifier interface { NotifyIssueChangeTitle(doer *models.User, issue *models.Issue, oldTitle string) NotifyIssueChangeRef(doer *models.User, issue *models.Issue, oldRef string) NotifyIssueChangeLabels(doer *models.User, issue *models.Issue, - addedLabels []*models.Label, removedLabels []*models.Label) + addedLabels, removedLabels []*models.Label) NotifyNewPullRequest(pr *models.PullRequest, mentions []*models.User) NotifyMergePullRequest(*models.PullRequest, *models.User) diff --git a/modules/notification/base/null.go b/modules/notification/base/null.go index e61b37a943090..156f30db107c1 100644 --- a/modules/notification/base/null.go +++ b/modules/notification/base/null.go @@ -10,12 +10,9 @@ import ( ) // NullNotifier implements a blank notifier -type NullNotifier struct { -} +type NullNotifier struct{} -var ( - _ Notifier = &NullNotifier{} -) +var _ Notifier = &NullNotifier{} // Run places a place holder function func (*NullNotifier) Run() { @@ -116,11 +113,11 @@ func (*NullNotifier) NotifyIssueChangeRef(doer *models.User, issue *models.Issue // NotifyIssueChangeLabels places a place holder function func (*NullNotifier) NotifyIssueChangeLabels(doer *models.User, issue *models.Issue, - addedLabels []*models.Label, removedLabels []*models.Label) { + addedLabels, removedLabels []*models.Label) { } // NotifyCreateRepository places a place holder function -func (*NullNotifier) NotifyCreateRepository(doer *models.User, u *models.User, repo *models.Repository) { +func (*NullNotifier) NotifyCreateRepository(doer, u *models.User, repo *models.Repository) { } // NotifyDeleteRepository places a place holder function @@ -132,7 +129,7 @@ func (*NullNotifier) NotifyForkRepository(doer *models.User, oldRepo, repo *mode } // NotifyMigrateRepository places a place holder function -func (*NullNotifier) NotifyMigrateRepository(doer *models.User, u *models.User, repo *models.Repository) { +func (*NullNotifier) NotifyMigrateRepository(doer, u *models.User, repo *models.Repository) { } // NotifyPushCommits notifies commits pushed to notifiers diff --git a/modules/notification/indexer/indexer.go b/modules/notification/indexer/indexer.go index 205194ad3e261..fccd9dd766c25 100644 --- a/modules/notification/indexer/indexer.go +++ b/modules/notification/indexer/indexer.go @@ -20,9 +20,7 @@ type indexerNotifier struct { base.NullNotifier } -var ( - _ base.Notifier = &indexerNotifier{} -) +var _ base.Notifier = &indexerNotifier{} // NewNotifier create a new indexerNotifier notifier func NewNotifier() base.Notifier { @@ -113,7 +111,7 @@ func (r *indexerNotifier) NotifyDeleteRepository(doer *models.User, repo *models } } -func (r *indexerNotifier) NotifyMigrateRepository(doer *models.User, u *models.User, repo *models.Repository) { +func (r *indexerNotifier) NotifyMigrateRepository(doer, u *models.User, repo *models.Repository) { issue_indexer.UpdateRepoIndexer(repo) if setting.Indexer.RepoIndexerEnabled && !repo.IsEmpty { code_indexer.UpdateRepoIndexer(repo) diff --git a/modules/notification/mail/mail.go b/modules/notification/mail/mail.go index f7192f5a52eff..ef82de098683f 100644 --- a/modules/notification/mail/mail.go +++ b/modules/notification/mail/mail.go @@ -17,9 +17,7 @@ type mailNotifier struct { base.NullNotifier } -var ( - _ base.Notifier = &mailNotifier{} -) +var _ base.Notifier = &mailNotifier{} // NewNotifier create a new mailNotifier notifier func NewNotifier() base.Notifier { diff --git a/modules/notification/notification.go b/modules/notification/notification.go index b574f3ccda225..e8806333d3101 100644 --- a/modules/notification/notification.go +++ b/modules/notification/notification.go @@ -16,9 +16,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) -var ( - notifiers []base.Notifier -) +var notifiers []base.Notifier // RegisterNotifier providers method to receive notify messages func RegisterNotifier(notifier base.Notifier) { @@ -201,21 +199,21 @@ func NotifyIssueChangeRef(doer *models.User, issue *models.Issue, oldRef string) // NotifyIssueChangeLabels notifies change labels to notifiers func NotifyIssueChangeLabels(doer *models.User, issue *models.Issue, - addedLabels []*models.Label, removedLabels []*models.Label) { + addedLabels, removedLabels []*models.Label) { for _, notifier := range notifiers { notifier.NotifyIssueChangeLabels(doer, issue, addedLabels, removedLabels) } } // NotifyCreateRepository notifies create repository to notifiers -func NotifyCreateRepository(doer *models.User, u *models.User, repo *models.Repository) { +func NotifyCreateRepository(doer, u *models.User, repo *models.Repository) { for _, notifier := range notifiers { notifier.NotifyCreateRepository(doer, u, repo) } } // NotifyMigrateRepository notifies create repository to notifiers -func NotifyMigrateRepository(doer *models.User, u *models.User, repo *models.Repository) { +func NotifyMigrateRepository(doer, u *models.User, repo *models.Repository) { for _, notifier := range notifiers { notifier.NotifyMigrateRepository(doer, u, repo) } diff --git a/modules/notification/ui/ui.go b/modules/notification/ui/ui.go index b1374f5608fd4..5161cedee7fa8 100644 --- a/modules/notification/ui/ui.go +++ b/modules/notification/ui/ui.go @@ -26,9 +26,7 @@ type ( } ) -var ( - _ base.Notifier = ¬ificationService{} -) +var _ base.Notifier = ¬ificationService{} // NewNotifier create a new notificationService notifier func NewNotifier() base.Notifier { @@ -52,7 +50,7 @@ func (ns *notificationService) Run() { func (ns *notificationService) NotifyCreateIssueComment(doer *models.User, repo *models.Repository, issue *models.Issue, comment *models.Comment, mentions []*models.User) { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, } @@ -61,7 +59,7 @@ func (ns *notificationService) NotifyCreateIssueComment(doer *models.User, repo } _ = ns.issueQueue.Push(opts) for _, mention := range mentions { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: mention.ID, @@ -120,7 +118,7 @@ func (ns *notificationService) NotifyNewPullRequest(pr *models.PullRequest, ment } func (ns *notificationService) NotifyPullRequestReview(pr *models.PullRequest, r *models.Review, c *models.Comment, mentions []*models.User) { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: pr.Issue.ID, NotificationAuthorID: r.Reviewer.ID, } @@ -129,7 +127,7 @@ func (ns *notificationService) NotifyPullRequestReview(pr *models.PullRequest, r } _ = ns.issueQueue.Push(opts) for _, mention := range mentions { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: pr.Issue.ID, NotificationAuthorID: r.Reviewer.ID, ReceiverID: mention.ID, @@ -153,7 +151,7 @@ func (ns *notificationService) NotifyPullRequestCodeComment(pr *models.PullReque } func (ns *notificationService) NotifyPullRequestPushCommits(doer *models.User, pr *models.PullRequest, comment *models.Comment) { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: pr.IssueID, NotificationAuthorID: doer.ID, CommentID: comment.ID, @@ -162,7 +160,7 @@ func (ns *notificationService) NotifyPullRequestPushCommits(doer *models.User, p } func (ns *notificationService) NotifyPullRevieweDismiss(doer *models.User, review *models.Review, comment *models.Comment) { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: review.IssueID, NotificationAuthorID: doer.ID, CommentID: comment.ID, @@ -172,7 +170,7 @@ func (ns *notificationService) NotifyPullRevieweDismiss(doer *models.User, revie func (ns *notificationService) NotifyIssueChangeAssignee(doer *models.User, issue *models.Issue, assignee *models.User, removed bool, comment *models.Comment) { if !removed { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: assignee.ID, @@ -188,7 +186,7 @@ func (ns *notificationService) NotifyIssueChangeAssignee(doer *models.User, issu func (ns *notificationService) NotifyPullReviewRequest(doer *models.User, issue *models.Issue, reviewer *models.User, isRequest bool, comment *models.Comment) { if isRequest { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: reviewer.ID, diff --git a/modules/notification/webhook/webhook.go b/modules/notification/webhook/webhook.go index a7357a51cab73..2069b7dde524b 100644 --- a/modules/notification/webhook/webhook.go +++ b/modules/notification/webhook/webhook.go @@ -20,9 +20,7 @@ type webhookNotifier struct { base.NullNotifier } -var ( - _ base.Notifier = &webhookNotifier{} -) +var _ base.Notifier = &webhookNotifier{} // NewNotifier create a new webhookNotifier notifier func NewNotifier() base.Notifier { @@ -97,7 +95,7 @@ func (m *webhookNotifier) NotifyForkRepository(doer *models.User, oldRepo, repo } } -func (m *webhookNotifier) NotifyCreateRepository(doer *models.User, u *models.User, repo *models.Repository) { +func (m *webhookNotifier) NotifyCreateRepository(doer, u *models.User, repo *models.Repository) { // Add to hook queue for created repo after session commit. if err := webhook_services.PrepareWebhooks(repo, models.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, @@ -122,7 +120,7 @@ func (m *webhookNotifier) NotifyDeleteRepository(doer *models.User, repo *models } } -func (m *webhookNotifier) NotifyMigrateRepository(doer *models.User, u *models.User, repo *models.Repository) { +func (m *webhookNotifier) NotifyMigrateRepository(doer, u *models.User, repo *models.Repository) { // Add to hook queue for created repo after session commit. if err := webhook_services.PrepareWebhooks(repo, models.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, @@ -470,11 +468,10 @@ func (m *webhookNotifier) NotifyDeleteComment(doer *models.User, comment *models if err != nil { log.Error("PrepareWebhooks [comment_id: %d]: %v", comment.ID, err) } - } func (m *webhookNotifier) NotifyIssueChangeLabels(doer *models.User, issue *models.Issue, - addedLabels []*models.Label, removedLabels []*models.Label) { + addedLabels, removedLabels []*models.Label) { var err error if err = issue.LoadRepo(); err != nil { diff --git a/modules/options/dynamic.go b/modules/options/dynamic.go index ffb89df88274b..3db3ee05846a2 100644 --- a/modules/options/dynamic.go +++ b/modules/options/dynamic.go @@ -16,9 +16,7 @@ import ( "code.gitea.io/gitea/modules/util" ) -var ( - directories = make(directorySet) -) +var directories = make(directorySet) // Dir returns all files from static or custom directory. func Dir(name string) ([]string, error) { @@ -26,9 +24,7 @@ func Dir(name string) ([]string, error) { return directories.Get(name), nil } - var ( - result []string - ) + var result []string customDir := path.Join(setting.CustomPath, "options", name) @@ -38,7 +34,6 @@ func Dir(name string) ([]string, error) { } if isDir { files, err := util.StatDir(customDir, true) - if err != nil { return []string{}, fmt.Errorf("Failed to read custom directory. %v", err) } @@ -54,7 +49,6 @@ func Dir(name string) ([]string, error) { } if isDir { files, err := util.StatDir(staticDir, true) - if err != nil { return []string{}, fmt.Errorf("Failed to read static directory. %v", err) } diff --git a/modules/options/static.go b/modules/options/static.go index 5f4ffdda78e49..2652b96044724 100644 --- a/modules/options/static.go +++ b/modules/options/static.go @@ -16,9 +16,7 @@ import ( "code.gitea.io/gitea/modules/util" ) -var ( - directories = make(directorySet) -) +var directories = make(directorySet) // Dir returns all files from bindata or custom directory. func Dir(name string) ([]string, error) { @@ -26,9 +24,7 @@ func Dir(name string) ([]string, error) { return directories.Get(name), nil } - var ( - result []string - ) + var result []string customDir := path.Join(setting.CustomPath, "options", name) isDir, err := util.IsDir(customDir) @@ -37,7 +33,6 @@ func Dir(name string) ([]string, error) { } if isDir { files, err := util.StatDir(customDir, true) - if err != nil { return []string{}, fmt.Errorf("Failed to read custom directory. %v", err) } @@ -46,7 +41,6 @@ func Dir(name string) ([]string, error) { } files, err := AssetDir(name) - if err != nil { return []string{}, fmt.Errorf("Failed to read embedded directory. %v", err) } @@ -67,7 +61,7 @@ func AssetDir(dirName string) ([]string, error) { if err != nil { return nil, err } - var results = make([]string, 0, len(files)) + results := make([]string, 0, len(files)) for _, file := range files { results = append(results, file.Name()) } @@ -131,7 +125,7 @@ func Asset(name string) ([]byte, error) { func AssetNames() []string { realFS := Assets.(vfsgen۰FS) - var results = make([]string, 0, len(realFS)) + results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) } diff --git a/modules/private/mail.go b/modules/private/mail.go index 9c0912a6e3490..be438d811cc74 100644 --- a/modules/private/mail.go +++ b/modules/private/mail.go @@ -50,7 +50,7 @@ func SendEmail(subject, message string, to []string) (int, string) { return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error()) } - var users = fmt.Sprintf("%d", len(to)) + users := fmt.Sprintf("%d", len(to)) if len(to) == 0 { users = "all" } diff --git a/modules/private/manager.go b/modules/private/manager.go index 2bc6cec3b968a..49cf17c488b51 100644 --- a/modules/private/manager.go +++ b/modules/private/manager.go @@ -171,7 +171,6 @@ func AddLogger(group, name, mode string, config map[string]interface{}) (int, st } return http.StatusOK, "Added" - } // RemoveLogger removes a logger diff --git a/modules/private/serv.go b/modules/private/serv.go index e077b00ccc1c6..c289e7fce2062 100644 --- a/modules/private/serv.go +++ b/modules/private/serv.go @@ -105,5 +105,4 @@ func ServCommand(keyID int64, ownerName, repoName string, mode models.AccessMode return nil, err } return &results, nil - } diff --git a/modules/process/manager_test.go b/modules/process/manager_test.go index a515fc32cda71..c07d2844c834e 100644 --- a/modules/process/manager_test.go +++ b/modules/process/manager_test.go @@ -62,7 +62,6 @@ func TestManager_Remove(t *testing.T) { } func TestExecTimeoutNever(t *testing.T) { - // TODO Investigate how to improve the time elapsed per round. maxLoops := 10 for i := 1; i < maxLoops; i++ { @@ -74,7 +73,6 @@ func TestExecTimeoutNever(t *testing.T) { } func TestExecTimeoutAlways(t *testing.T) { - maxLoops := 100 for i := 1; i < maxLoops; i++ { _, stderr, err := GetManager().ExecTimeout(100*time.Microsecond, "ExecTimeout", "sleep", "5") diff --git a/modules/public/public.go b/modules/public/public.go index 6695944bd65a0..bd337afa8e38e 100644 --- a/modules/public/public.go +++ b/modules/public/public.go @@ -91,7 +91,7 @@ func (opts *Options) staticHandler(dir string) func(next http.Handler) http.Hand // parseAcceptEncoding parse Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5 as compress methods func parseAcceptEncoding(val string) map[string]bool { parts := strings.Split(val, ";") - var types = make(map[string]bool) + types := make(map[string]bool) for _, v := range strings.Split(parts[0], ",") { types[strings.TrimSpace(v)] = true } diff --git a/modules/public/public_test.go b/modules/public/public_test.go index cf8dced431146..430e7345646a2 100644 --- a/modules/public/public_test.go +++ b/modules/public/public_test.go @@ -11,7 +11,7 @@ import ( ) func TestParseAcceptEncoding(t *testing.T) { - var kases = []struct { + kases := []struct { Header string Expected map[string]bool }{ diff --git a/modules/public/static.go b/modules/public/static.go index 36cfdbe44f32e..fb0ca27598f06 100644 --- a/modules/public/static.go +++ b/modules/public/static.go @@ -39,7 +39,7 @@ func Asset(name string) ([]byte, error) { func AssetNames() []string { realFS := Assets.(vfsgen۰FS) - var results = make([]string, 0, len(realFS)) + results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) } diff --git a/modules/queue/manager.go b/modules/queue/manager.go index d44007a0f007e..a8fc8e02848de 100644 --- a/modules/queue/manager.go +++ b/modules/queue/manager.go @@ -109,7 +109,6 @@ func (m *Manager) Add(managed interface{}, t Type, configuration, exemplar interface{}) int64 { - json := jsoniter.ConfigCompatibleWithStandardLibrary cfg, _ := json.Marshal(configuration) mq := &ManagedQueue{ @@ -141,7 +140,6 @@ func (m *Manager) Remove(qid int64) { delete(m.Queues, qid) m.mutex.Unlock() log.Trace("Queue Manager removed: QID: %d", qid) - } // GetManagedQueue by qid @@ -206,7 +204,6 @@ func (m *Manager) FlushAll(baseCtx context.Context, timeout time.Duration) error wg.Wait() } return nil - } // ManagedQueues returns the managed queues diff --git a/modules/queue/queue.go b/modules/queue/queue.go index d08cba35a1ea5..5be97a64990d1 100644 --- a/modules/queue/queue.go +++ b/modules/queue/queue.go @@ -39,7 +39,7 @@ type Data interface{} type HandlerFunc func(...Data) // NewQueueFunc is a function that creates a queue -type NewQueueFunc func(handler HandlerFunc, config interface{}, exemplar interface{}) (Queue, error) +type NewQueueFunc func(handler HandlerFunc, config, exemplar interface{}) (Queue, error) // Shutdownable represents a queue that can be shutdown type Shutdownable interface { @@ -70,8 +70,7 @@ func NewDummyQueue(handler HandlerFunc, opts, exemplar interface{}) (Queue, erro } // DummyQueue represents an empty queue -type DummyQueue struct { -} +type DummyQueue struct{} // Run does nothing func (*DummyQueue) Run(_, _ func(context.Context, func())) {} diff --git a/modules/queue/queue_disk_channel_test.go b/modules/queue/queue_disk_channel_test.go index 93061bffc6586..9c28833d34e49 100644 --- a/modules/queue/queue_disk_channel_test.go +++ b/modules/queue/queue_disk_channel_test.go @@ -113,5 +113,4 @@ func TestPersistableChannelQueue(t *testing.T) { for _, callback := range queueTerminate { callback() } - } diff --git a/modules/queue/queue_wrapped.go b/modules/queue/queue_wrapped.go index 88d64e82464f4..f21b85e3a3ec6 100644 --- a/modules/queue/queue_wrapped.go +++ b/modules/queue/queue_wrapped.go @@ -57,7 +57,7 @@ func (q *delayedStarter) setInternal(atShutdown func(context.Context, func()), h for q.internal == nil { select { case <-ctx.Done(): - var cfg = q.cfg + cfg := q.cfg if s, ok := cfg.([]byte); ok { cfg = string(s) } diff --git a/modules/queue/workerpool.go b/modules/queue/workerpool.go index 45378e3dae145..632896cfceba8 100644 --- a/modules/queue/workerpool.go +++ b/modules/queue/workerpool.go @@ -213,7 +213,6 @@ func (p *WorkerPool) commonRegisterWorkers(number int, timeout time.Duration, is log.Trace("WorkerPool: %d (for %s) adding %d workers with group id: %d", p.qid, mq.Name, number, pid) } else { log.Trace("WorkerPool: %d adding %d workers (no group id)", p.qid, number) - } return ctx, cancel } @@ -316,7 +315,7 @@ func (p *WorkerPool) FlushWithContext(ctx context.Context) error { func (p *WorkerPool) doWork(ctx context.Context) { delay := time.Millisecond * 300 - var data = make([]Data, 0, p.batchLength) + data := make([]Data, 0, p.batchLength) for { select { case <-ctx.Done(): diff --git a/modules/references/references.go b/modules/references/references.go index c243f25f5d44a..d781bf4730fec 100644 --- a/modules/references/references.go +++ b/modules/references/references.go @@ -148,7 +148,7 @@ func newKeywords() { }) } -func doNewKeywords(close []string, reopen []string) { +func doNewKeywords(close, reopen []string) { issueCloseKeywordsPat = makeKeywordsPat(close) issueReopenKeywordsPat = makeKeywordsPat(reopen) } @@ -357,7 +357,6 @@ func FindRenderizableReferenceAlphanumeric(content string) (bool, *RenderizableR // FindAllIssueReferencesBytes returns a list of unvalidated references found in a byte slice. func findAllIssueReferencesBytes(content []byte, links []string) []*rawReference { - ret := make([]*rawReference, 0, 10) pos := 0 @@ -464,7 +463,7 @@ func findAllIssueReferencesBytes(content []byte, links []string) []*rawReference return ret } -func getCrossReference(content []byte, start, end int, fromLink bool, prOnly bool) *rawReference { +func getCrossReference(content []byte, start, end int, fromLink, prOnly bool) *rawReference { refid := string(content[start:end]) sep := strings.IndexAny(refid, "#!") if sep < 0 { @@ -535,7 +534,7 @@ func findActionKeywords(content []byte, start int) (XRefAction, *RefSpan) { } // IsXrefActionable returns true if the xref action is actionable (i.e. produces a result when resolved) -func IsXrefActionable(ref *RenderizableReference, extTracker bool, alphaNum bool) bool { +func IsXrefActionable(ref *RenderizableReference, extTracker, alphaNum bool) bool { if extTracker { // External issues cannot be automatically closed return false diff --git a/modules/references/references_test.go b/modules/references/references_test.go index d4f080490d1fa..e85ec3d3edddf 100644 --- a/modules/references/references_test.go +++ b/modules/references/references_test.go @@ -51,7 +51,6 @@ owner/repo!123456789 } func TestFindAllIssueReferences(t *testing.T) { - fixtures := []testFixture{ { "Simply closes: #29 yes", diff --git a/modules/repofiles/action.go b/modules/repofiles/action.go index 52cc89dbae1b5..8ba1f6a4fe61c 100644 --- a/modules/repofiles/action.go +++ b/modules/repofiles/action.go @@ -97,7 +97,6 @@ func issueAddTime(issue *models.Issue, doer *models.User, time time.Time, timeLo func changeIssueStatus(repo *models.Repository, issue *models.Issue, doer *models.User, closed bool) error { stopTimerIfAvailable := func(doer *models.User, issue *models.Issue) error { - if models.StopwatchExists(doer.ID, issue.ID) { if err := models.CreateOrStopIssueStopwatch(doer, issue); err != nil { return err diff --git a/modules/repofiles/temp_repo.go b/modules/repofiles/temp_repo.go index 820f5f25421e4..f527c50186e14 100644 --- a/modules/repofiles/temp_repo.go +++ b/modules/repofiles/temp_repo.go @@ -185,12 +185,12 @@ func (t *TemporaryUploadRepository) GetLastCommitByRef(ref string) (string, erro } // CommitTree creates a commit from a given tree for the user with provided message -func (t *TemporaryUploadRepository) CommitTree(author, committer *models.User, treeHash string, message string, signoff bool) (string, error) { +func (t *TemporaryUploadRepository) CommitTree(author, committer *models.User, treeHash, message string, signoff bool) (string, error) { return t.CommitTreeWithDate(author, committer, treeHash, message, signoff, time.Now(), time.Now()) } // CommitTreeWithDate creates a commit from a given tree for the user with provided message -func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *models.User, treeHash string, message string, signoff bool, authorDate, committerDate time.Time) (string, error) { +func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *models.User, treeHash, message string, signoff bool, authorDate, committerDate time.Time) (string, error) { authorSig := author.NewGitSig() committerSig := committer.NewGitSig() @@ -260,7 +260,7 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *models } // Push the provided commitHash to the repository branch by the provided user -func (t *TemporaryUploadRepository) Push(doer *models.User, commitHash string, branch string) error { +func (t *TemporaryUploadRepository) Push(doer *models.User, commitHash, branch string) error { // Because calls hooks we need to pass in the environment env := models.PushingEnvironment(doer, t.repo) if err := git.Push(t.basePath, git.PushOptions{ diff --git a/modules/repository/generate.go b/modules/repository/generate.go index 1ba457fb3a551..2f79341c65e30 100644 --- a/modules/repository/generate.go +++ b/modules/repository/generate.go @@ -60,7 +60,7 @@ func generateExpansion(src string, templateRepo, generateRepo *models.Repository {Name: "TEMPLATE_SSH_URL", Value: templateRepo.CloneLink().SSH, Transformers: nil}, } - var expansionMap = make(map[string]string) + expansionMap := make(map[string]string) for _, e := range expansions { expansionMap[e.Name] = e.Value for _, tr := range e.Transformers { @@ -157,7 +157,7 @@ func generateRepoCommit(repo, templateRepo, generateRepo *models.Repository, tmp if err := ioutil.WriteFile(path, []byte(generateExpansion(string(content), templateRepo, generateRepo)), - 0644); err != nil { + 0o644); err != nil { return err } break diff --git a/modules/repository/hooks.go b/modules/repository/hooks.go index aba5db6719b22..75a2ea5e22d9f 100644 --- a/modules/repository/hooks.go +++ b/modules/repository/hooks.go @@ -56,7 +56,7 @@ func createDelegateHooks(repoPath string) (err error) { if err = util.Remove(oldHookPath); err != nil && !os.IsNotExist(err) { return fmt.Errorf("unable to pre-remove old hook file '%s' prior to rewriting: %v ", oldHookPath, err) } - if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil { + if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0o777); err != nil { return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err) } @@ -67,7 +67,7 @@ func createDelegateHooks(repoPath string) (err error) { if err = util.Remove(newHookPath); err != nil && !os.IsNotExist(err) { return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %v", newHookPath, err) } - if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil { + if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0o777); err != nil { return fmt.Errorf("write new hook file '%s': %v", newHookPath, err) } @@ -84,7 +84,7 @@ func checkExecutable(filename string) bool { if err != nil { return false } - return (fileInfo.Mode() & 0100) > 0 + return (fileInfo.Mode() & 0o100) > 0 } func ensureExecutable(filename string) error { @@ -92,10 +92,10 @@ func ensureExecutable(filename string) error { if err != nil { return err } - if (fileInfo.Mode() & 0100) > 0 { + if (fileInfo.Mode() & 0o100) > 0 { return nil } - mode := fileInfo.Mode() | 0100 + mode := fileInfo.Mode() | 0o100 return os.Chmod(filename, mode) } diff --git a/modules/repository/init.go b/modules/repository/init.go index 50cde4c0b9d17..80f3cf9b825f1 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -59,7 +59,7 @@ func prepareRepoCommit(ctx models.DBContext, repo *models.Repository, tmpDir, re "OwnerName": repo.OwnerName, } if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"), - []byte(com.Expand(string(data), match)), 0644); err != nil { + []byte(com.Expand(string(data), match)), 0o644); err != nil { return fmt.Errorf("write README.md: %v", err) } @@ -78,7 +78,7 @@ func prepareRepoCommit(ctx models.DBContext, repo *models.Repository, tmpDir, re } if buf.Len() > 0 { - if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil { + if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0o644); err != nil { return fmt.Errorf("write .gitignore: %v", err) } } @@ -91,7 +91,7 @@ func prepareRepoCommit(ctx models.DBContext, repo *models.Repository, tmpDir, re return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err) } - if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil { + if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0o644); err != nil { return fmt.Errorf("write LICENSE: %v", err) } } diff --git a/modules/repository/repo.go b/modules/repository/repo.go index ede714673ab16..d2a1690b7f94f 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -270,7 +270,7 @@ func PushUpdateAddTag(repo *models.Repository, gitRepo *git.Repository, tagName } var author *models.User - var createdAt = time.Unix(1, 0) + createdAt := time.Unix(1, 0) if sig != nil { author, err = models.GetUserByEmail(sig.Email) @@ -285,7 +285,7 @@ func PushUpdateAddTag(repo *models.Repository, gitRepo *git.Repository, tagName return fmt.Errorf("CommitsCount: %v", err) } - var rel = models.Release{ + rel := models.Release{ RepoID: repo.ID, TagName: tagName, LowerTagName: strings.ToLower(tagName), diff --git a/modules/repository/update.go b/modules/repository/update.go index 975f577da8db6..3804a4755c020 100644 --- a/modules/repository/update.go +++ b/modules/repository/update.go @@ -66,7 +66,7 @@ func pushUpdateAddTags(ctx models.DBContext, repo *models.Repository, gitRepo *g sig = commit.Committer } var author *models.User - var createdAt = time.Unix(1, 0) + createdAt := time.Unix(1, 0) if sig != nil { var ok bool diff --git a/modules/secret/secret.go b/modules/secret/secret.go index 2b6e22cc6c7ff..51e8d3c20dbe0 100644 --- a/modules/secret/secret.go +++ b/modules/secret/secret.go @@ -76,7 +76,7 @@ func AesDecrypt(key, text []byte) ([]byte, error) { } // EncryptSecret encrypts a string with given key into a hex string -func EncryptSecret(key string, str string) (string, error) { +func EncryptSecret(key, str string) (string, error) { keyHash := sha256.Sum256([]byte(key)) plaintext := []byte(str) ciphertext, err := AesEncrypt(keyHash[:], plaintext) @@ -87,7 +87,7 @@ func EncryptSecret(key string, str string) (string, error) { } // DecryptSecret decrypts a previously encrypted hex string -func DecryptSecret(key string, cipherhex string) (string, error) { +func DecryptSecret(key, cipherhex string) (string, error) { keyHash := sha256.Sum256([]byte(key)) ciphertext, err := hex.DecodeString(cipherhex) if err != nil { diff --git a/modules/session/db.go b/modules/session/db.go index db8c01de95ff4..ee9989f56684b 100644 --- a/modules/session/db.go +++ b/modules/session/db.go @@ -135,7 +135,6 @@ func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err err s, err := models.RegenerateSession(oldsid, sid) if err != nil { return nil, err - } var kv map[interface{}]interface{} diff --git a/modules/setting/attachment.go b/modules/setting/attachment.go index 98c4be94e9cd1..6e8812fbcbf3c 100644 --- a/modules/setting/attachment.go +++ b/modules/setting/attachment.go @@ -4,24 +4,22 @@ package setting -var ( - // Attachment settings - Attachment = struct { - Storage - AllowedTypes string - MaxSize int64 - MaxFiles int - Enabled bool - }{ - Storage: Storage{ - ServeDirect: false, - }, - AllowedTypes: "image/jpeg,image/png,application/zip,application/gzip", - MaxSize: 4, - MaxFiles: 5, - Enabled: true, - } -) +// Attachment settings +var Attachment = struct { + Storage + AllowedTypes string + MaxSize int64 + MaxFiles int + Enabled bool +}{ + Storage: Storage{ + ServeDirect: false, + }, + AllowedTypes: "image/jpeg,image/png,application/zip,application/gzip", + MaxSize: 4, + MaxFiles: 5, + Enabled: true, +} func newAttachmentService() { sec := Cfg.Section("attachment") diff --git a/modules/setting/cache.go b/modules/setting/cache.go index 7bfea919618e4..1f3ba8e909c3f 100644 --- a/modules/setting/cache.go +++ b/modules/setting/cache.go @@ -20,34 +20,32 @@ type Cache struct { TTL time.Duration `ini:"ITEM_TTL"` } -var ( - // CacheService the global cache - CacheService = struct { - Cache `ini:"cache"` +// CacheService the global cache +var CacheService = struct { + Cache `ini:"cache"` - LastCommit struct { - Enabled bool - TTL time.Duration `ini:"ITEM_TTL"` - CommitsCount int64 - } `ini:"cache.last_commit"` + LastCommit struct { + Enabled bool + TTL time.Duration `ini:"ITEM_TTL"` + CommitsCount int64 + } `ini:"cache.last_commit"` +}{ + Cache: Cache{ + Enabled: true, + Adapter: "memory", + Interval: 60, + TTL: 16 * time.Hour, + }, + LastCommit: struct { + Enabled bool + TTL time.Duration `ini:"ITEM_TTL"` + CommitsCount int64 }{ - Cache: Cache{ - Enabled: true, - Adapter: "memory", - Interval: 60, - TTL: 16 * time.Hour, - }, - LastCommit: struct { - Enabled bool - TTL time.Duration `ini:"ITEM_TTL"` - CommitsCount int64 - }{ - Enabled: true, - TTL: 8760 * time.Hour, - CommitsCount: 1000, - }, - } -) + Enabled: true, + TTL: 8760 * time.Hour, + CommitsCount: 1000, + }, +} // MemcacheMaxTTL represents the maximum memcache TTL const MemcacheMaxTTL = 30 * 24 * time.Hour diff --git a/modules/setting/cors.go b/modules/setting/cors.go index d7856e8b23f80..342c3debbfd18 100644 --- a/modules/setting/cors.go +++ b/modules/setting/cors.go @@ -10,21 +10,19 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // CORSConfig defines CORS settings - CORSConfig = struct { - Enabled bool - Scheme string - AllowDomain []string - AllowSubdomain bool - Methods []string - MaxAge time.Duration - AllowCredentials bool - }{ - Enabled: false, - MaxAge: 10 * time.Minute, - } -) +// CORSConfig defines CORS settings +var CORSConfig = struct { + Enabled bool + Scheme string + AllowDomain []string + AllowSubdomain bool + Methods []string + MaxAge time.Duration + AllowCredentials bool +}{ + Enabled: false, + MaxAge: 10 * time.Minute, +} func newCORSService() { sec := Cfg.Section("cors") diff --git a/modules/setting/cron_test.go b/modules/setting/cron_test.go index 8670a92bac964..cb397d81c45d6 100644 --- a/modules/setting/cron_test.go +++ b/modules/setting/cron_test.go @@ -12,7 +12,6 @@ import ( ) func Test_GetCronSettings(t *testing.T) { - type BaseStruct struct { Base bool Second string @@ -43,5 +42,4 @@ Extend = true assert.True(t, extended.Base) assert.EqualValues(t, extended.Second, "white rabbit") assert.True(t, extended.Extend) - } diff --git a/modules/setting/database.go b/modules/setting/database.go index 3d13ee10c8460..89785dcb4e268 100644 --- a/modules/setting/database.go +++ b/modules/setting/database.go @@ -106,7 +106,7 @@ func InitDBConfig() { // DBConnStr returns database connection string func DBConnStr() (string, error) { connStr := "" - var Param = "?" + Param := "?" if strings.Contains(Database.Name, Param) { Param = "&" } diff --git a/modules/setting/git.go b/modules/setting/git.go index 308d94894ba72..ea93903f65b4c 100644 --- a/modules/setting/git.go +++ b/modules/setting/git.go @@ -11,58 +11,56 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // Git settings - Git = struct { - Path string - DisableDiffHighlight bool - MaxGitDiffLines int - MaxGitDiffLineCharacters int - MaxGitDiffFiles int - CommitsRangeSize int - BranchesRangeSize int - VerbosePush bool - VerbosePushDelay time.Duration - GCArgs []string `ini:"GC_ARGS" delim:" "` - EnableAutoGitWireProtocol bool - PullRequestPushMessage bool - Timeout struct { - Default int - Migrate int - Mirror int - Clone int - Pull int - GC int `ini:"GC"` - } `ini:"git.timeout"` +// Git settings +var Git = struct { + Path string + DisableDiffHighlight bool + MaxGitDiffLines int + MaxGitDiffLineCharacters int + MaxGitDiffFiles int + CommitsRangeSize int + BranchesRangeSize int + VerbosePush bool + VerbosePushDelay time.Duration + GCArgs []string `ini:"GC_ARGS" delim:" "` + EnableAutoGitWireProtocol bool + PullRequestPushMessage bool + Timeout struct { + Default int + Migrate int + Mirror int + Clone int + Pull int + GC int `ini:"GC"` + } `ini:"git.timeout"` +}{ + DisableDiffHighlight: false, + MaxGitDiffLines: 1000, + MaxGitDiffLineCharacters: 5000, + MaxGitDiffFiles: 100, + CommitsRangeSize: 50, + BranchesRangeSize: 20, + VerbosePush: true, + VerbosePushDelay: 5 * time.Second, + GCArgs: []string{}, + EnableAutoGitWireProtocol: true, + PullRequestPushMessage: true, + Timeout: struct { + Default int + Migrate int + Mirror int + Clone int + Pull int + GC int `ini:"GC"` }{ - DisableDiffHighlight: false, - MaxGitDiffLines: 1000, - MaxGitDiffLineCharacters: 5000, - MaxGitDiffFiles: 100, - CommitsRangeSize: 50, - BranchesRangeSize: 20, - VerbosePush: true, - VerbosePushDelay: 5 * time.Second, - GCArgs: []string{}, - EnableAutoGitWireProtocol: true, - PullRequestPushMessage: true, - Timeout: struct { - Default int - Migrate int - Mirror int - Clone int - Pull int - GC int `ini:"GC"` - }{ - Default: int(git.DefaultCommandExecutionTimeout / time.Second), - Migrate: 600, - Mirror: 300, - Clone: 300, - Pull: 300, - GC: 60, - }, - } -) + Default: int(git.DefaultCommandExecutionTimeout / time.Second), + Migrate: 600, + Mirror: 300, + Clone: 300, + Pull: 300, + GC: 60, + }, +} func newGit() { if err := Cfg.Section("git").MapTo(&Git); err != nil { @@ -86,8 +84,8 @@ func newGit() { git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "credential.helper=") } - var format = "Git Version: %s" - var args = []interface{}{version.Original()} + format := "Git Version: %s" + args := []interface{}{version.Original()} // Since git wire protocol has been released from git v2.18 if Git.EnableAutoGitWireProtocol && git.CheckGitVersionAtLeast("2.18") == nil { git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "protocol.version=2") diff --git a/modules/setting/indexer.go b/modules/setting/indexer.go index 842ef8ea41166..1f486d7365521 100644 --- a/modules/setting/indexer.go +++ b/modules/setting/indexer.go @@ -22,48 +22,46 @@ const ( RedisQueueType = "redis" ) -var ( - // Indexer settings - Indexer = struct { - IssueType string - IssuePath string - IssueConnStr string - IssueIndexerName string - IssueQueueType string - IssueQueueDir string - IssueQueueConnStr string - IssueQueueBatchNumber int - StartupTimeout time.Duration +// Indexer settings +var Indexer = struct { + IssueType string + IssuePath string + IssueConnStr string + IssueIndexerName string + IssueQueueType string + IssueQueueDir string + IssueQueueConnStr string + IssueQueueBatchNumber int + StartupTimeout time.Duration - RepoIndexerEnabled bool - RepoType string - RepoPath string - RepoConnStr string - RepoIndexerName string - UpdateQueueLength int - MaxIndexerFileSize int64 - IncludePatterns []glob.Glob - ExcludePatterns []glob.Glob - ExcludeVendored bool - }{ - IssueType: "bleve", - IssuePath: "indexers/issues.bleve", - IssueConnStr: "", - IssueIndexerName: "gitea_issues", - IssueQueueType: LevelQueueType, - IssueQueueDir: "indexers/issues.queue", - IssueQueueConnStr: "", - IssueQueueBatchNumber: 20, + RepoIndexerEnabled bool + RepoType string + RepoPath string + RepoConnStr string + RepoIndexerName string + UpdateQueueLength int + MaxIndexerFileSize int64 + IncludePatterns []glob.Glob + ExcludePatterns []glob.Glob + ExcludeVendored bool +}{ + IssueType: "bleve", + IssuePath: "indexers/issues.bleve", + IssueConnStr: "", + IssueIndexerName: "gitea_issues", + IssueQueueType: LevelQueueType, + IssueQueueDir: "indexers/issues.queue", + IssueQueueConnStr: "", + IssueQueueBatchNumber: 20, - RepoIndexerEnabled: false, - RepoType: "bleve", - RepoPath: "indexers/repos.bleve", - RepoConnStr: "", - RepoIndexerName: "gitea_codes", - MaxIndexerFileSize: 1024 * 1024, - ExcludeVendored: true, - } -) + RepoIndexerEnabled: false, + RepoType: "bleve", + RepoPath: "indexers/repos.bleve", + RepoConnStr: "", + RepoIndexerName: "gitea_codes", + MaxIndexerFileSize: 1024 * 1024, + ExcludeVendored: true, +} func newIndexerService() { sec := Cfg.Section("indexer") diff --git a/modules/setting/indexer_test.go b/modules/setting/indexer_test.go index ed631747dc707..0ff1d814abcfe 100644 --- a/modules/setting/indexer_test.go +++ b/modules/setting/indexer_test.go @@ -16,7 +16,6 @@ type indexerMatchList struct { } func Test_newIndexerGlobSettings(t *testing.T) { - checkGlobMatch(t, "", []indexerMatchList{}) checkGlobMatch(t, " ", []indexerMatchList{}) checkGlobMatch(t, "data, */data, */data/*, **/data/*, **/data/**", []indexerMatchList{ diff --git a/modules/setting/lfs.go b/modules/setting/lfs.go index ab475bbeb4b31..0bad7dd5c8efc 100644 --- a/modules/setting/lfs.go +++ b/modules/setting/lfs.go @@ -92,8 +92,8 @@ func newLFSService() { // CheckLFSVersion will check lfs version, if not satisfied, then disable it. func CheckLFSVersion() { if LFS.StartServer { - //Disable LFS client hooks if installed for the current OS user - //Needs at least git v2.1.2 + // Disable LFS client hooks if installed for the current OS user + // Needs at least git v2.1.2 err := git.LoadGitVersion() if err != nil { diff --git a/modules/setting/log.go b/modules/setting/log.go index 9bbeee27a22e9..0b4c724592554 100644 --- a/modules/setting/log.go +++ b/modules/setting/log.go @@ -21,8 +21,10 @@ import ( var filenameSuffix = "" -var descriptionLock = sync.RWMutex{} -var logDescriptions = make(map[string]*LogDescription) +var ( + descriptionLock = sync.RWMutex{} + logDescriptions = make(map[string]*LogDescription) +) // GetLogDescriptions returns a race safe set of descriptions func GetLogDescriptions() map[string]*LogDescription { @@ -68,7 +70,7 @@ func AddSubLogDescription(key string, subLogDescription SubLogDescription) bool } // RemoveSubLogDescription removes a sub log description -func RemoveSubLogDescription(key string, name string) bool { +func RemoveSubLogDescription(key, name string) bool { descriptionLock.Lock() defer descriptionLock.Unlock() desc, ok := logDescriptions[key] @@ -87,7 +89,7 @@ func RemoveSubLogDescription(key string, name string) bool { type defaultLogOptions struct { levelName string // LogLevel flags string - filename string //path.Join(LogRootPath, "gitea.log") + filename string // path.Join(LogRootPath, "gitea.log") bufferLength int64 disableConsole bool } @@ -115,12 +117,12 @@ type LogDescription struct { SubLogDescriptions []SubLogDescription } -func getLogLevel(section *ini.Section, key string, defaultValue string) string { +func getLogLevel(section *ini.Section, key, defaultValue string) string { value := section.Key(key).MustString("info") return log.FromString(value).String() } -func getStacktraceLogLevel(section *ini.Section, key string, defaultValue string) string { +func getStacktraceLogLevel(section *ini.Section, key, defaultValue string) string { value := section.Key(key).MustString("none") return log.FromString(value).String() } diff --git a/modules/setting/mailer.go b/modules/setting/mailer.go index a2228e938ba0d..c948a45748351 100644 --- a/modules/setting/mailer.go +++ b/modules/setting/mailer.go @@ -41,10 +41,8 @@ type Mailer struct { SendmailTimeout time.Duration } -var ( - // MailService the global mailer - MailService *Mailer -) +// MailService the global mailer +var MailService *Mailer func newMailService() { sec := Cfg.Section("mailer") diff --git a/modules/setting/markup.go b/modules/setting/markup.go index 1dd76243e6d6e..26c4fbb7097a7 100644 --- a/modules/setting/markup.go +++ b/modules/setting/markup.go @@ -103,7 +103,7 @@ func newMarkupRenderer(name string, sec *ini.Section) { extensionReg := regexp.MustCompile(`\.\w`) extensions := sec.Key("FILE_EXTENSIONS").Strings(",") - var exts = make([]string, 0, len(extensions)) + exts := make([]string, 0, len(extensions)) for _, extension := range extensions { if !extensionReg.MatchString(extension) { log.Warn(sec.Name() + " file extension " + extension + " is invalid. Extension ignored") diff --git a/modules/setting/migrations.go b/modules/setting/migrations.go index 7808df5280756..fffc38c99d7ac 100644 --- a/modules/setting/migrations.go +++ b/modules/setting/migrations.go @@ -8,19 +8,17 @@ import ( "strings" ) -var ( - // Migrations settings - Migrations = struct { - MaxAttempts int - RetryBackoff int - AllowedDomains []string - BlockedDomains []string - AllowLocalNetworks bool - }{ - MaxAttempts: 3, - RetryBackoff: 3, - } -) +// Migrations settings +var Migrations = struct { + MaxAttempts int + RetryBackoff int + AllowedDomains []string + BlockedDomains []string + AllowLocalNetworks bool +}{ + MaxAttempts: 3, + RetryBackoff: 3, +} func newMigrationsService() { sec := Cfg.Section("migrations") diff --git a/modules/setting/session.go b/modules/setting/session.go index 97666c5e53da1..16165a8928efc 100644 --- a/modules/setting/session.go +++ b/modules/setting/session.go @@ -14,33 +14,31 @@ import ( jsoniter "github.com/json-iterator/go" ) -var ( - // SessionConfig difines Session settings - SessionConfig = struct { - Provider string - // Provider configuration, it's corresponding to provider. - ProviderConfig string - // Cookie name to save session ID. Default is "MacaronSession". - CookieName string - // Cookie path to store. Default is "/". - CookiePath string - // GC interval time in seconds. Default is 3600. - Gclifetime int64 - // Max life time in seconds. Default is whatever GC interval time is. - Maxlifetime int64 - // Use HTTPS only. Default is false. - Secure bool - // Cookie domain name. Default is empty. - Domain string - // SameSite declares if your cookie should be restricted to a first-party or same-site context. Valid strings are "none", "lax", "strict". Default is "lax" - SameSite http.SameSite - }{ - CookieName: "i_like_gitea", - Gclifetime: 86400, - Maxlifetime: 86400, - SameSite: http.SameSiteLaxMode, - } -) +// SessionConfig difines Session settings +var SessionConfig = struct { + Provider string + // Provider configuration, it's corresponding to provider. + ProviderConfig string + // Cookie name to save session ID. Default is "MacaronSession". + CookieName string + // Cookie path to store. Default is "/". + CookiePath string + // GC interval time in seconds. Default is 3600. + Gclifetime int64 + // Max life time in seconds. Default is whatever GC interval time is. + Maxlifetime int64 + // Use HTTPS only. Default is false. + Secure bool + // Cookie domain name. Default is empty. + Domain string + // SameSite declares if your cookie should be restricted to a first-party or same-site context. Valid strings are "none", "lax", "strict". Default is "lax" + SameSite http.SameSite +}{ + CookieName: "i_like_gitea", + Gclifetime: 86400, + Maxlifetime: 86400, + SameSite: http.SameSiteLaxMode, +} func newSessionService() { sec := Cfg.Section("session") diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 9d27a5d743222..20a3852e18537 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -580,7 +580,7 @@ func NewContext() { Protocol = FCGIUnix UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666") UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32) - if err != nil || UnixSocketPermissionParsed > 0777 { + if err != nil || UnixSocketPermissionParsed > 0o777 { log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw) } UnixSocketPermission = uint32(UnixSocketPermissionParsed) @@ -588,7 +588,7 @@ func NewContext() { Protocol = UnixSocket UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666") UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32) - if err != nil || UnixSocketPermissionParsed > 0777 { + if err != nil || UnixSocketPermissionParsed > 0o777 { log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw) } UnixSocketPermission = uint32(UnixSocketPermissionParsed) @@ -736,16 +736,16 @@ func NewContext() { SSH.AuthorizedPrincipalsAllow, SSH.AuthorizedPrincipalsEnabled = parseAuthorizedPrincipalsAllow(sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").Strings(",")) if !SSH.Disabled && !SSH.StartBuiltinServer { - if err := os.MkdirAll(SSH.RootPath, 0700); err != nil { + if err := os.MkdirAll(SSH.RootPath, 0o700); err != nil { log.Fatal("Failed to create '%s': %v", SSH.RootPath, err) - } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil { + } else if err = os.MkdirAll(SSH.KeyTestPath, 0o644); err != nil { log.Fatal("Failed to create '%s': %v", SSH.KeyTestPath, err) } if len(trustedUserCaKeys) > 0 && SSH.AuthorizedPrincipalsEnabled { fname := sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem")) if err := ioutil.WriteFile(fname, - []byte(strings.Join(trustedUserCaKeys, "\n")), 0600); err != nil { + []byte(strings.Join(trustedUserCaKeys, "\n")), 0o600); err != nil { log.Fatal("Failed to create '%s': %v", fname, err) } } @@ -952,14 +952,17 @@ func NewContext() { Langs = []string{ "en-US", "zh-CN", "zh-HK", "zh-TW", "de-DE", "fr-FR", "nl-NL", "lv-LV", "ru-RU", "uk-UA", "ja-JP", "es-ES", "pt-BR", "pt-PT", "pl-PL", "bg-BG", - "it-IT", "fi-FI", "tr-TR", "cs-CZ", "sr-SP", "sv-SE", "ko-KR"} + "it-IT", "fi-FI", "tr-TR", "cs-CZ", "sr-SP", "sv-SE", "ko-KR", + } } Names = Cfg.Section("i18n").Key("NAMES").Strings(",") if len(Names) == 0 { - Names = []string{"English", "简体中文", "繁體中文(香港)", "繁體中文(台灣)", "Deutsch", + Names = []string{ + "English", "简体中文", "繁體中文(香港)", "繁體中文(台灣)", "Deutsch", "français", "Nederlands", "latviešu", "русский", "Українська", "日本語", "español", "português do Brasil", "Português de Portugal", "polski", "български", - "italiano", "suomi", "Türkçe", "čeština", "српски", "svenska", "한국어"} + "italiano", "suomi", "Türkçe", "čeština", "српски", "svenska", "한국어", + } } ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false) @@ -1031,7 +1034,7 @@ func loadInternalToken(sec *ini.Section) string { } switch tempURI.Scheme { case "file": - fp, err := os.OpenFile(tempURI.RequestURI(), os.O_RDWR, 0600) + fp, err := os.OpenFile(tempURI.RequestURI(), os.O_RDWR, 0o600) if err != nil { log.Fatal("Failed to open InternalTokenURI (%s): %v", uri, err) } @@ -1095,7 +1098,7 @@ func loadOrGenerateInternalToken(sec *ini.Section) string { } // MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash -func MakeAbsoluteAssetURL(appURL string, staticURLPrefix string) string { +func MakeAbsoluteAssetURL(appURL, staticURLPrefix string) string { parsedPrefix, err := url.Parse(strings.TrimSuffix(staticURLPrefix, "/")) if err != nil { log.Fatal("Unable to parse STATIC_URL_PREFIX: %v", err) @@ -1114,7 +1117,7 @@ func MakeAbsoluteAssetURL(appURL string, staticURLPrefix string) string { } // MakeManifestData generates web app manifest JSON -func MakeManifestData(appName string, appURL string, absoluteAssetURL string) []byte { +func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte { type manifestIcon struct { Src string `json:"src"` Type string `json:"type"` @@ -1146,7 +1149,6 @@ func MakeManifestData(appName string, appURL string, absoluteAssetURL string) [] }, }, }) - if err != nil { log.Error("unable to marshal manifest JSON. Error: %v", err) return make([]byte, 0) diff --git a/modules/setting/webhook.go b/modules/setting/webhook.go index 4a0c593c8d120..b913b0aa4ff52 100644 --- a/modules/setting/webhook.go +++ b/modules/setting/webhook.go @@ -10,26 +10,24 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // Webhook settings - Webhook = struct { - QueueLength int - DeliverTimeout int - SkipTLSVerify bool - Types []string - PagingNum int - ProxyURL string - ProxyURLFixed *url.URL - ProxyHosts []string - }{ - QueueLength: 1000, - DeliverTimeout: 5, - SkipTLSVerify: false, - PagingNum: 10, - ProxyURL: "", - ProxyHosts: []string{}, - } -) +// Webhook settings +var Webhook = struct { + QueueLength int + DeliverTimeout int + SkipTLSVerify bool + Types []string + PagingNum int + ProxyURL string + ProxyURLFixed *url.URL + ProxyHosts []string +}{ + QueueLength: 1000, + DeliverTimeout: 5, + SkipTLSVerify: false, + PagingNum: 10, + ProxyURL: "", + ProxyHosts: []string{}, +} func newWebhookService() { sec := Cfg.Section("webhook") diff --git a/modules/ssh/ssh.go b/modules/ssh/ssh.go index 22683b003be10..324a448d2a2c9 100644 --- a/modules/ssh/ssh.go +++ b/modules/ssh/ssh.go @@ -240,7 +240,7 @@ func publicKeyHandler(ctx ssh.Context, key ssh.PublicKey) bool { } // Listen starts a SSH server listens on given port. -func Listen(host string, port int, ciphers []string, keyExchanges []string, macs []string) { +func Listen(host string, port int, ciphers, keyExchanges, macs []string) { srv := ssh.Server{ Addr: fmt.Sprintf("%s:%d", host, port), PublicKeyHandler: publicKeyHandler, @@ -294,7 +294,6 @@ func Listen(host string, port int, ciphers []string, keyExchanges []string, macs } go listen(&srv) - } // GenKeyPair make a pair of public and private keys for SSH access. @@ -307,7 +306,7 @@ func GenKeyPair(keyPath string) error { } privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)} - f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err } @@ -328,7 +327,7 @@ func GenKeyPair(keyPath string) error { } public := gossh.MarshalAuthorizedKey(pub) - p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err } diff --git a/modules/ssh/ssh_graceful.go b/modules/ssh/ssh_graceful.go index c213aa7b88a99..1ea58b4a95293 100644 --- a/modules/ssh/ssh_graceful.go +++ b/modules/ssh/ssh_graceful.go @@ -24,7 +24,6 @@ func listen(server *ssh.Server) { } } log.Info("SSH Listener: %s Closed", server.Addr) - } // Unused informs our cleanup routine that we will not be using a ssh port diff --git a/modules/storage/local.go b/modules/storage/local.go index 982d2b88c6e79..144d477ad9724 100644 --- a/modules/storage/local.go +++ b/modules/storage/local.go @@ -16,9 +16,7 @@ import ( "code.gitea.io/gitea/modules/util" ) -var ( - _ ObjectStorage = &LocalStorage{} -) +var _ ObjectStorage = &LocalStorage{} // LocalStorageType is the type descriptor for local storage const LocalStorageType Type = "local" diff --git a/modules/storage/minio.go b/modules/storage/minio.go index 0e0cb3690da64..bd32b4fc719f1 100644 --- a/modules/storage/minio.go +++ b/modules/storage/minio.go @@ -122,7 +122,7 @@ func (m *MinioStorage) buildMinioPath(p string) string { // Open open a file func (m *MinioStorage) Open(path string) (Object, error) { - var opts = minio.GetObjectOptions{} + opts := minio.GetObjectOptions{} object, err := m.client.GetObject(m.ctx, m.bucket, m.buildMinioPath(path), opts) if err != nil { return nil, convertMinioErr(err) @@ -206,7 +206,7 @@ func (m *MinioStorage) URL(path, name string) (*url.URL, error) { // IterateObjects iterates across the objects in the miniostorage func (m *MinioStorage) IterateObjects(fn func(path string, obj Object) error) error { - var opts = minio.GetObjectOptions{} + opts := minio.GetObjectOptions{} lobjectCtx, cancel := context.WithCancel(m.ctx) defer cancel() for mObjInfo := range m.client.ListObjects(lobjectCtx, m.bucket, minio.ListObjectsOptions{ diff --git a/modules/structs/hook.go b/modules/structs/hook.go index 693820b57d3e9..047bfcdd00b07 100644 --- a/modules/structs/hook.go +++ b/modules/structs/hook.go @@ -13,10 +13,8 @@ import ( jsoniter "github.com/json-iterator/go" ) -var ( - // ErrInvalidReceiveHook FIXME - ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") -) +// ErrInvalidReceiveHook FIXME +var ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") // Hook a hook is a web hook when one repository changed type Hook struct { diff --git a/modules/structs/repo.go b/modules/structs/repo.go index c47700cd00934..df462bbf3721a 100644 --- a/modules/structs/repo.go +++ b/modules/structs/repo.go @@ -277,13 +277,11 @@ func (gt GitServiceType) TokenAuth() bool { return false } -var ( - // SupportedFullGitService represents all git services supported to migrate issues/labels/prs and etc. - // TODO: add to this list after new git service added - SupportedFullGitService = []GitServiceType{ - GithubService, - GitlabService, - GiteaService, - GogsService, - } -) +// SupportedFullGitService represents all git services supported to migrate issues/labels/prs and etc. +// TODO: add to this list after new git service added +var SupportedFullGitService = []GitServiceType{ + GithubService, + GitlabService, + GiteaService, + GogsService, +} diff --git a/modules/task/task.go b/modules/task/task.go index 0443517c01694..5bf5e601a1ebb 100644 --- a/modules/task/task.go +++ b/modules/task/task.go @@ -71,7 +71,7 @@ func CreateMigrateTask(doer, u *models.User, opts base.MigrateOptions) (*models. return nil, err } - var task = models.Task{ + task := models.Task{ DoerID: doer.ID, OwnerID: u.ID, Type: structs.TaskTypeMigrateRepo, diff --git a/modules/templates/base.go b/modules/templates/base.go index cb83143bd3424..04d77b9dd20cf 100644 --- a/modules/templates/base.go +++ b/modules/templates/base.go @@ -29,7 +29,7 @@ func (vars Vars) Merge(another map[string]interface{}) Vars { // BaseVars returns all basic vars func BaseVars() Vars { - var startTime = time.Now() + startTime := time.Now() return map[string]interface{}{ "IsLandingPageHome": setting.LandingPageURL == setting.LandingPageHome, "IsLandingPageExplore": setting.LandingPageURL == setting.LandingPageExplore, diff --git a/modules/templates/dynamic.go b/modules/templates/dynamic.go index 160e4e05f2501..7e5a793ec9c3b 100644 --- a/modules/templates/dynamic.go +++ b/modules/templates/dynamic.go @@ -71,7 +71,6 @@ func Mailer() (*texttmpl.Template, *template.Template) { } content, err := ioutil.ReadFile(path.Join(staticDir, filePath)) - if err != nil { log.Warn("Failed to read static %s template. %v", filePath, err) continue @@ -100,7 +99,6 @@ func Mailer() (*texttmpl.Template, *template.Template) { } content, err := ioutil.ReadFile(path.Join(customDir, filePath)) - if err != nil { log.Warn("Failed to read custom %s template. %v", filePath, err) continue diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 7e33f262094ee..f0629841b201d 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -214,7 +214,7 @@ func NewFuncMap() []template.FuncMap { } return path }, - "DiffStatsWidth": func(adds int, dels int) string { + "DiffStatsWidth": func(adds, dels int) string { return fmt.Sprintf("%f", float64(adds)/(float64(adds)+float64(dels))*100) }, "Json": func(in interface{}) string { @@ -288,7 +288,7 @@ func NewFuncMap() []template.FuncMap { return util.MergeInto(dict, values...) }, "percentage": func(n int, values ...int) float32 { - var sum = 0 + sum := 0 for i := 0; i < len(values); i++ { sum += values[i] } @@ -319,7 +319,7 @@ func NewFuncMap() []template.FuncMap { "EventSourceUpdateTime": int(setting.UI.Notification.EventSourceUpdateTime / time.Millisecond), } }, - "containGeneric": func(arr interface{}, v interface{}) bool { + "containGeneric": func(arr, v interface{}) bool { arrV := reflect.ValueOf(arr) if arrV.Kind() == reflect.String && reflect.ValueOf(v).Kind() == reflect.String { return strings.Contains(arr.(string), v.(string)) @@ -490,7 +490,7 @@ func NewTextFuncMap() []texttmpl.FuncMap { return dict, nil }, "percentage": func(n int, values ...int) float32 { - var sum = 0 + sum := 0 for i := 0; i < len(values); i++ { sum += values[i] } @@ -513,8 +513,10 @@ func NewTextFuncMap() []texttmpl.FuncMap { }} } -var widthRe = regexp.MustCompile(`width="[0-9]+?"`) -var heightRe = regexp.MustCompile(`height="[0-9]+?"`) +var ( + widthRe = regexp.MustCompile(`width="[0-9]+?"`) + heightRe = regexp.MustCompile(`height="[0-9]+?"`) +) func parseOthers(defaultSize int, defaultClass string, others ...interface{}) (int, string) { size := defaultSize @@ -535,7 +537,7 @@ func parseOthers(defaultSize int, defaultClass string, others ...interface{}) (i } // AvatarHTML creates the HTML for an avatar -func AvatarHTML(src string, size int, class string, name string) template.HTML { +func AvatarHTML(src string, size int, class, name string) template.HTML { sizeStr := fmt.Sprintf(`%d`, size) if name == "" { @@ -599,7 +601,7 @@ func RepoAvatar(repo *models.Repository, others ...interface{}) template.HTML { } // AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string) -func AvatarByEmail(email string, name string, others ...interface{}) template.HTML { +func AvatarByEmail(email, name string, others ...interface{}) template.HTML { size, class := parseOthers(models.DefaultAvatarPixelSize, "ui avatar image", others...) src := models.SizedAvatarLink(email, size*models.AvatarRenderedSizeFactor) @@ -742,7 +744,7 @@ func RenderEmoji(text string) template.HTML { return template.HTML(renderedText) } -//ReactionToEmoji renders emoji for use in reactions +// ReactionToEmoji renders emoji for use in reactions func ReactionToEmoji(reaction string) template.HTML { val := emoji.FromCode(reaction) if val != nil { diff --git a/modules/templates/static.go b/modules/templates/static.go index 7f95d77ad3242..ce8fd332396fe 100644 --- a/modules/templates/static.go +++ b/modules/templates/static.go @@ -39,7 +39,7 @@ func GetAsset(name string) ([]byte, error) { // GetAssetNames only for chi func GetAssetNames() []string { realFS := Assets.(vfsgen۰FS) - var tmpls = make([]string, 0, len(realFS)) + tmpls := make([]string, 0, len(realFS)) for k := range realFS { tmpls = append(tmpls, "templates/"+k[1:]) } @@ -68,7 +68,6 @@ func Mailer() (*texttmpl.Template, *template.Template) { } content, err := Asset(assetPath) - if err != nil { log.Warn("Failed to read embedded %s template. %v", assetPath, err) continue @@ -103,7 +102,6 @@ func Mailer() (*texttmpl.Template, *template.Template) { } content, err := ioutil.ReadFile(path.Join(customDir, filePath)) - if err != nil { log.Warn("Failed to read custom %s template. %v", filePath, err) continue @@ -134,7 +132,7 @@ func Asset(name string) ([]byte, error) { func AssetNames() []string { realFS := Assets.(vfsgen۰FS) - var results = make([]string, 0, len(realFS)) + results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) } diff --git a/modules/test/context_tests.go b/modules/test/context_tests.go index a15c74d82800b..8da7f0b79bfc9 100644 --- a/modules/test/context_tests.go +++ b/modules/test/context_tests.go @@ -25,8 +25,8 @@ import ( // MockContext mock context for unit tests func MockContext(t *testing.T, path string) *context.Context { - var resp = &mockResponseWriter{} - var ctx = context.Context{ + resp := &mockResponseWriter{} + ctx := context.Context{ Render: &mockRender{}, Data: make(map[string]interface{}), Flash: &middleware.Flash{ @@ -38,7 +38,7 @@ func MockContext(t *testing.T, path string) *context.Context { requestURL, err := url.Parse(path) assert.NoError(t, err) - var req = &http.Request{ + req := &http.Request{ URL: requestURL, Form: url.Values{}, } @@ -125,8 +125,7 @@ func (rw *mockResponseWriter) Push(target string, opts *http.PushOptions) error return nil } -type mockRender struct { -} +type mockRender struct{} func (tr *mockRender) TemplateLookup(tmpl string) *template.Template { return nil diff --git a/modules/timeutil/language.go b/modules/timeutil/language.go index 121b50f2779d4..d0380cac3d8d7 100644 --- a/modules/timeutil/language.go +++ b/modules/timeutil/language.go @@ -10,13 +10,11 @@ import ( "code.gitea.io/gitea/modules/setting" ) -var ( - langTimeFormats = map[string]string{ - "zh-CN": "2006年01月02日 15时04分05秒", - "en-US": time.RFC1123, - "lv-LV": "02.01.2006. 15:04:05", - } -) +var langTimeFormats = map[string]string{ + "zh-CN": "2006年01月02日 15时04分05秒", + "en-US": time.RFC1123, + "lv-LV": "02.01.2006. 15:04:05", +} // GetLangTimeFormat represents the default time format for the language func GetLangTimeFormat(lang string) string { diff --git a/modules/upload/upload.go b/modules/upload/upload.go index e430a5d8b3c22..892e0a5f90bf0 100644 --- a/modules/upload/upload.go +++ b/modules/upload/upload.go @@ -30,11 +30,13 @@ func (err ErrFileTypeForbidden) Error() string { return "This file extension or type is not allowed to be uploaded." } -var mimeTypeSuffixRe = regexp.MustCompile(`;.*$`) -var wildcardTypeRe = regexp.MustCompile(`^[a-z]+/\*$`) +var ( + mimeTypeSuffixRe = regexp.MustCompile(`;.*$`) + wildcardTypeRe = regexp.MustCompile(`^[a-z]+/\*$`) +) // Verify validates whether a file is allowed to be uploaded. -func Verify(buf []byte, fileName string, allowedTypesStr string) error { +func Verify(buf []byte, fileName, allowedTypesStr string) error { allowedTypesStr = strings.ReplaceAll(allowedTypesStr, "|", ",") // compat for old config format allowedTypes := []string{} diff --git a/modules/util/compare.go b/modules/util/compare.go index cd9ba0d91ce8f..49891ef02496e 100644 --- a/modules/util/compare.go +++ b/modules/util/compare.go @@ -71,7 +71,7 @@ func IsInt64InSlice(target int64, slice []int64) bool { } // IsEqualSlice returns true if slices are equal. -func IsEqualSlice(target []string, source []string) bool { +func IsEqualSlice(target, source []string) bool { if len(target) != len(source) { return false } diff --git a/modules/util/paginate_test.go b/modules/util/paginate_test.go index d962e04c1603b..3657efc919ede 100644 --- a/modules/util/paginate_test.go +++ b/modules/util/paginate_test.go @@ -36,7 +36,7 @@ func TestPaginateSlice(t *testing.T) { Val int } - var testVar = []*Test{{Val: 2}, {Val: 3}, {Val: 4}} + testVar := []*Test{{Val: 2}, {Val: 3}, {Val: 4}} testVar, ok = PaginateSlice(testVar, 1, 50).([]*Test) assert.True(t, ok) assert.EqualValues(t, []*Test{{Val: 2}, {Val: 3}, {Val: 4}}, testVar) diff --git a/modules/util/path.go b/modules/util/path.go index aa3d009899273..4c421fe17f829 100644 --- a/modules/util/path.go +++ b/modules/util/path.go @@ -14,7 +14,7 @@ import ( // EnsureAbsolutePath ensure that a path is absolute, making it // relative to absoluteBase if necessary -func EnsureAbsolutePath(path string, absoluteBase string) string { +func EnsureAbsolutePath(path, absoluteBase string) string { if filepath.IsAbs(path) { return path } diff --git a/modules/util/sanitize_test.go b/modules/util/sanitize_test.go index 4f07100675b02..5473aea953864 100644 --- a/modules/util/sanitize_test.go +++ b/modules/util/sanitize_test.go @@ -11,7 +11,7 @@ import ( ) func TestSanitizeURLCredentials(t *testing.T) { - var kases = map[string]string{ + kases := map[string]string{ "https://github.com/go-gitea/test_repo.git": "https://github.com/go-gitea/test_repo.git", "https://mytoken@github.com/go-gitea/test_repo.git": "https://github.com/go-gitea/test_repo.git", "http://github.com/go-gitea/test_repo.git": "http://github.com/go-gitea/test_repo.git", diff --git a/modules/util/shellquote.go b/modules/util/shellquote.go index bde24a151772a..5a12c2e2618da 100644 --- a/modules/util/shellquote.go +++ b/modules/util/shellquote.go @@ -41,9 +41,11 @@ const ( needsSingleQuote = "!\n" ) -var doubleQuoteEscaper = strings.NewReplacer(`$`, `\$`, "`", "\\`", `"`, `\"`, `\`, `\\`) -var singleQuoteEscaper = strings.NewReplacer(`'`, `'\''`) -var singleQuoteCoalescer = strings.NewReplacer(`''\'`, `\'`, `\'''`, `\'`) +var ( + doubleQuoteEscaper = strings.NewReplacer(`$`, `\$`, "`", "\\`", `"`, `\"`, `\`, `\\`) + singleQuoteEscaper = strings.NewReplacer(`'`, `'\''`) + singleQuoteCoalescer = strings.NewReplacer(`''\'`, `\'`, `\'''`, `\'`) +) // ShellEscape will escape the provided string. // We can't just use go-shellquote here because our preferences for escaping differ from those in that we want: diff --git a/modules/util/util_test.go b/modules/util/util_test.go index 1d4f23de9043f..7eb8290ab3fc5 100644 --- a/modules/util/util_test.go +++ b/modules/util/util_test.go @@ -45,7 +45,6 @@ func TestURLJoin(t *testing.T) { } func TestIsEmptyString(t *testing.T) { - cases := []struct { s string expected bool diff --git a/modules/validation/binding.go b/modules/validation/binding.go index 5cfd994d2daeb..4d03de53da962 100644 --- a/modules/validation/binding.go +++ b/modules/validation/binding.go @@ -21,16 +21,13 @@ const ( ErrGlobPattern = "GlobPattern" ) -var ( - // GitRefNamePatternInvalid is regular expression with unallowed characters in git reference name - // They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon : anywhere. - // They cannot have question-mark ?, asterisk *, or open bracket [ anywhere - GitRefNamePatternInvalid = regexp.MustCompile(`[\000-\037\177 \\~^:?*[]+`) -) +// GitRefNamePatternInvalid is regular expression with unallowed characters in git reference name +// They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon : anywhere. +// They cannot have question-mark ?, asterisk *, or open bracket [ anywhere +var GitRefNamePatternInvalid = regexp.MustCompile(`[\000-\037\177 \\~^:?*[]+`) // CheckGitRefAdditionalRulesValid check name is valid on additional rules func CheckGitRefAdditionalRulesValid(name string) bool { - // Additional rules as described at https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html if strings.HasPrefix(name, "/") || strings.HasSuffix(name, "/") || strings.HasSuffix(name, ".") || strings.Contains(name, "..") || diff --git a/modules/web/middleware/cookie.go b/modules/web/middleware/cookie.go index cfcc2bbac787e..a40281e0807cf 100644 --- a/modules/web/middleware/cookie.go +++ b/modules/web/middleware/cookie.go @@ -119,7 +119,7 @@ func DeleteCSRFCookie(resp http.ResponseWriter) { // SetCookie set the cookies // TODO: Copied from gitea.com/macaron/macaron and should be improved after macaron removed. -func SetCookie(resp http.ResponseWriter, name string, value string, others ...interface{}) { +func SetCookie(resp http.ResponseWriter, name, value string, others ...interface{}) { cookie := http.Cookie{} cookie.Name = name cookie.Value = url.QueryEscape(value) diff --git a/modules/web/middleware/flash.go b/modules/web/middleware/flash.go index cd9b089b94d83..d1d4a864e364c 100644 --- a/modules/web/middleware/flash.go +++ b/modules/web/middleware/flash.go @@ -14,10 +14,8 @@ const ( InfoFlash = "InfoMsg" ) -var ( - // FlashNow FIXME: - FlashNow bool -) +// FlashNow FIXME: +var FlashNow bool // Flash represents a one time data transfer between two requests. type Flash struct { diff --git a/modules/web/middleware/locale.go b/modules/web/middleware/locale.go index a08e5aaeec7a1..d7826f368c61f 100644 --- a/modules/web/middleware/locale.go +++ b/modules/web/middleware/locale.go @@ -18,7 +18,7 @@ import ( func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { // 1. Check URL arguments. lang := req.URL.Query().Get("lang") - var changeLang = lang != "" + changeLang := lang != "" // 2. Get language information from cookies. if len(lang) == 0 { diff --git a/modules/web/route.go b/modules/web/route.go index 59e22c5be15f7..2016443eb4729 100644 --- a/modules/web/route.go +++ b/modules/web/route.go @@ -67,7 +67,7 @@ func Wrap(handlers ...interface{}) http.HandlerFunc { return } case func(http.Handler) http.Handler: - var next = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) + next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) t(next).ServeHTTP(resp, req) if r, ok := resp.(context.ResponseWriter); ok && r.Status() > 0 { return @@ -109,7 +109,7 @@ func MiddleAPI(f func(ctx *context.APIContext)) func(netx http.Handler) http.Han // Bind binding an obj to a handler func Bind(obj interface{}) http.HandlerFunc { - var tp = reflect.TypeOf(obj) + tp := reflect.TypeOf(obj) if tp.Kind() == reflect.Ptr { tp = tp.Elem() } @@ -117,7 +117,7 @@ func Bind(obj interface{}) http.HandlerFunc { panic("Only structs are allowed to bind") } return Wrap(func(ctx *context.Context) { - var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly + theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly binding.Bind(ctx.Req, theObj) SetForm(ctx, theObj) middleware.AssignForm(theObj, ctx.Data) @@ -173,8 +173,8 @@ func (r *Route) Use(middlewares ...interface{}) { // Group mounts a sub-Router along a `pattern` string. func (r *Route) Group(pattern string, fn func(), middlewares ...interface{}) { - var previousGroupPrefix = r.curGroupPrefix - var previousMiddlewares = r.curMiddlewares + previousGroupPrefix := r.curGroupPrefix + previousMiddlewares := r.curMiddlewares r.curGroupPrefix += pattern r.curMiddlewares = append(r.curMiddlewares, middlewares...) @@ -197,7 +197,7 @@ func (r *Route) getPattern(pattern string) string { // Mount attaches another Route along ./pattern/* func (r *Route) Mount(pattern string, subR *Route) { - var middlewares = make([]interface{}, len(r.curMiddlewares)) + middlewares := make([]interface{}, len(r.curMiddlewares)) copy(middlewares, r.curMiddlewares) subR.Use(middlewares...) r.R.Mount(r.getPattern(pattern), subR.R) @@ -205,15 +205,15 @@ func (r *Route) Mount(pattern string, subR *Route) { // Any delegate requests for all methods func (r *Route) Any(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.HandleFunc(r.getPattern(pattern), Wrap(middlewares...)) } // Route delegate special methods -func (r *Route) Route(pattern string, methods string, h ...interface{}) { +func (r *Route) Route(pattern, methods string, h ...interface{}) { p := r.getPattern(pattern) ms := strings.Split(methods, ",") - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) for _, method := range ms { r.R.MethodFunc(strings.TrimSpace(method), p, Wrap(middlewares...)) } @@ -221,12 +221,12 @@ func (r *Route) Route(pattern string, methods string, h ...interface{}) { // Delete delegate delete method func (r *Route) Delete(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Delete(r.getPattern(pattern), Wrap(middlewares...)) } func (r *Route) getMiddlewares(h []interface{}) []interface{} { - var middlewares = make([]interface{}, len(r.curMiddlewares), len(r.curMiddlewares)+len(h)) + middlewares := make([]interface{}, len(r.curMiddlewares), len(r.curMiddlewares)+len(h)) copy(middlewares, r.curMiddlewares) middlewares = append(middlewares, h...) return middlewares @@ -234,31 +234,31 @@ func (r *Route) getMiddlewares(h []interface{}) []interface{} { // Get delegate get method func (r *Route) Get(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Get(r.getPattern(pattern), Wrap(middlewares...)) } // Head delegate head method func (r *Route) Head(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Head(r.getPattern(pattern), Wrap(middlewares...)) } // Post delegate post method func (r *Route) Post(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Post(r.getPattern(pattern), Wrap(middlewares...)) } // Put delegate put method func (r *Route) Put(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Put(r.getPattern(pattern), Wrap(middlewares...)) } // Patch delegate patch method func (r *Route) Patch(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Patch(r.getPattern(pattern), Wrap(middlewares...)) } diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 49f6a394a6ef2..085d6ec93c4dc 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -205,7 +205,7 @@ func shadowPassword(provider, cfgItem string) string { case "redis": return shadowPasswordKV(cfgItem, ",") case "mysql": - //root:@tcp(localhost:3306)/macaron?charset=utf8 + // root:@tcp(localhost:3306)/macaron?charset=utf8 atIdx := strings.Index(cfgItem, "@") if atIdx > 0 { colonIdx := strings.Index(cfgItem[:atIdx], ":") diff --git a/routers/admin/admin_test.go b/routers/admin/admin_test.go index da404e50d7381..1bc43998b25af 100644 --- a/routers/admin/admin_test.go +++ b/routers/admin/admin_test.go @@ -11,7 +11,7 @@ import ( ) func TestShadowPassword(t *testing.T) { - var kases = []struct { + kases := []struct { Provider string CfgItem string Result string diff --git a/routers/admin/emails.go b/routers/admin/emails.go index 4cc7253ca96f5..2dda22a0cc741 100644 --- a/routers/admin/emails.go +++ b/routers/admin/emails.go @@ -99,9 +99,7 @@ func Emails(ctx *context.Context) { ctx.HTML(200, tplEmails) } -var ( - nullByte = []byte{0x00} -) +var nullByte = []byte{0x00} func isKeywordValid(keyword string) bool { return !bytes.Contains([]byte(keyword), nullByte) @@ -109,7 +107,6 @@ func isKeywordValid(keyword string) bool { // ActivateEmail serves a POST request for activating/deactivating a user's email func ActivateEmail(ctx *context.Context) { - truefalse := map[string]bool{"1": true, "0": false} uid := ctx.QueryInt64("uid") diff --git a/routers/admin/users_test.go b/routers/admin/users_test.go index bd00bb2bf1893..7912ce7f4dbfe 100644 --- a/routers/admin/users_test.go +++ b/routers/admin/users_test.go @@ -16,7 +16,6 @@ import ( ) func TestNewUserPost_MustChangePassword(t *testing.T) { - models.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new") @@ -54,7 +53,6 @@ func TestNewUserPost_MustChangePassword(t *testing.T) { } func TestNewUserPost_MustChangePasswordFalse(t *testing.T) { - models.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new") @@ -92,7 +90,6 @@ func TestNewUserPost_MustChangePasswordFalse(t *testing.T) { } func TestNewUserPost_InvalidEmail(t *testing.T) { - models.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new") diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go index 1356276f07f4f..45433d0910b2d 100644 --- a/routers/api/v1/admin/org.go +++ b/routers/api/v1/admin/org.go @@ -81,7 +81,7 @@ func CreateOrg(ctx *context.APIContext) { ctx.JSON(http.StatusCreated, convert.ToOrganization(org)) } -//GetAllOrgs API for getting information of all the organizations +// GetAllOrgs API for getting information of all the organizations func GetAllOrgs(ctx *context.APIContext) { // swagger:operation GET /admin/orgs admin adminGetAllOrgs // --- diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 116c622048d65..a47d3033c4c02 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -367,7 +367,7 @@ func DeleteUserPublicKey(ctx *context.APIContext) { ctx.Status(http.StatusNoContent) } -//GetAllUsers API for getting information of all the users +// GetAllUsers API for getting information of all the users func GetAllUsers(ctx *context.APIContext) { // swagger:operation GET /admin/users admin adminGetAllUsers // --- diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 60c4f6d790d5f..6b991697fa8cf 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -325,7 +325,7 @@ func reqTeamMembership() func(ctx *context.APIContext) { return } - var orgID = ctx.Org.Team.OrgID + orgID := ctx.Org.Team.OrgID isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err) @@ -530,12 +530,12 @@ func mustNotBeArchived(ctx *context.APIContext) { // bind binding an obj to a func(ctx *context.APIContext) func bind(obj interface{}) http.HandlerFunc { - var tp = reflect.TypeOf(obj) + tp := reflect.TypeOf(obj) for tp.Kind() == reflect.Ptr { tp = tp.Elem() } return web.Wrap(func(ctx *context.APIContext) { - var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly + theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly errs := binding.Bind(ctx.Req, theObj) if len(errs) > 0 { ctx.Error(422, "validationError", errs[0].Error()) @@ -547,7 +547,7 @@ func bind(obj interface{}) http.HandlerFunc { // Routes registers all v1 APIs routes to web application. func Routes() *web.Route { - var m = web.NewRoute() + m := web.NewRoute() m.Use(session.Sessioner(session.Options{ Provider: setting.SessionConfig.Provider, @@ -562,9 +562,9 @@ func Routes() *web.Route { m.Use(securityHeaders()) if setting.CORSConfig.Enabled { m.Use(cors.Handler(cors.Options{ - //Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option + // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option AllowedOrigins: setting.CORSConfig.AllowDomain, - //setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option + // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option AllowedMethods: setting.CORSConfig.Methods, AllowCredentials: setting.CORSConfig.AllowCredentials, MaxAge: int(setting.CORSConfig.MaxAge.Seconds()), diff --git a/routers/api/v1/misc/markdown_test.go b/routers/api/v1/misc/markdown_test.go index 3ae3165fd3734..13b45baa1bea1 100644 --- a/routers/api/v1/misc/markdown_test.go +++ b/routers/api/v1/misc/markdown_test.go @@ -22,12 +22,14 @@ import ( "github.com/stretchr/testify/assert" ) -const AppURL = "http://localhost:3000/" -const Repo = "gogits/gogs" -const AppSubURL = AppURL + Repo + "/" +const ( + AppURL = "http://localhost:3000/" + Repo = "gogits/gogs" + AppSubURL = AppURL + Repo + "/" +) func createContext(req *http.Request) (*context.Context, *httptest.ResponseRecorder) { - var rnd = templates.HTMLRenderer() + rnd := templates.HTMLRenderer() resp := httptest.NewRecorder() c := &context.Context{ Req: req, diff --git a/routers/api/v1/notify/repo.go b/routers/api/v1/notify/repo.go index 0a75fcd30a1df..d8123d0595b61 100644 --- a/routers/api/v1/notify/repo.go +++ b/routers/api/v1/notify/repo.go @@ -29,7 +29,7 @@ func statusStringToNotificationStatus(status string) models.NotificationStatus { } } -func statusStringsToNotificationStatuses(statuses []string, defaultStatuses []string) []models.NotificationStatus { +func statusStringsToNotificationStatuses(statuses, defaultStatuses []string) []models.NotificationStatus { if len(statuses) == 0 { statuses = defaultStatuses } diff --git a/routers/api/v1/org/hook.go b/routers/api/v1/org/hook.go index ed827c48d43f6..dba403511b61b 100644 --- a/routers/api/v1/org/hook.go +++ b/routers/api/v1/org/hook.go @@ -110,7 +110,7 @@ func CreateHook(ctx *context.APIContext) { // "$ref": "#/responses/Hook" form := web.GetForm(ctx).(*api.CreateHookOption) - //TODO in body params + // TODO in body params if !utils.CheckCreateHookOption(ctx, form) { return } @@ -148,7 +148,7 @@ func EditHook(ctx *context.APIContext) { form := web.GetForm(ctx).(*api.EditHookOption) - //TODO in body params + // TODO in body params hookID := ctx.ParamsInt64(":id") utils.EditOrgHook(ctx, form, hookID) } diff --git a/routers/api/v1/org/org.go b/routers/api/v1/org/org.go index e0f36aa1e657d..5d0491425ac66 100644 --- a/routers/api/v1/org/org.go +++ b/routers/api/v1/org/org.go @@ -20,7 +20,6 @@ import ( ) func listUserOrgs(ctx *context.APIContext, u *models.User) { - listOptions := utils.GetListOptions(ctx) showPrivate := ctx.IsSigned && (ctx.User.IsAdmin || ctx.User.ID == u.ID) @@ -272,7 +271,7 @@ func Edit(ctx *context.APIContext) { ctx.JSON(http.StatusOK, convert.ToOrganization(org)) } -//Delete an organization +// Delete an organization func Delete(ctx *context.APIContext) { // swagger:operation DELETE /orgs/{org} organization orgDelete // --- diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index c749751ac4dbf..f48f3c2803bb7 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -168,7 +168,7 @@ func CreateTeam(ctx *context.APIContext) { unitTypes := models.FindUnitTypes(form.Units...) if team.Authorize < models.AccessModeOwner { - var units = make([]*models.TeamUnit, 0, len(form.Units)) + units := make([]*models.TeamUnit, 0, len(form.Units)) for _, tp := range unitTypes { units = append(units, &models.TeamUnit{ OrgID: ctx.Org.Organization.ID, @@ -252,7 +252,7 @@ func EditTeam(ctx *context.APIContext) { if team.Authorize < models.AccessModeOwner { if len(form.Units) > 0 { - var units = make([]*models.TeamUnit, 0, len(form.Units)) + units := make([]*models.TeamUnit, 0, len(form.Units)) unitTypes := models.FindUnitTypes(form.Units...) for _, tp := range unitTypes { units = append(units, &models.TeamUnit{ @@ -694,5 +694,4 @@ func SearchTeam(ctx *context.APIContext) { "ok": true, "data": apiTeams, }) - } diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 451fdcf516f04..7d95b73e54918 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -219,23 +219,18 @@ func CreateBranch(ctx *context.APIContext) { } err := repo_module.CreateNewBranch(ctx.User, ctx.Repo.Repository, opt.OldBranchName, opt.BranchName) - if err != nil { if models.IsErrBranchDoesNotExist(err) { ctx.Error(http.StatusNotFound, "", "The old branch does not exist") } if models.IsErrTagAlreadyExists(err) { ctx.Error(http.StatusConflict, "", "The branch with the same tag already exists.") - } else if models.IsErrBranchAlreadyExists(err) || git.IsErrPushOutOfDate(err) { ctx.Error(http.StatusConflict, "", "The branch already exists.") - } else if models.IsErrBranchNameConflict(err) { ctx.Error(http.StatusConflict, "", "The branch with the same name already exists.") - } else { ctx.Error(http.StatusInternalServerError, "CreateRepoBranch", err) - } return } @@ -574,7 +569,6 @@ func CreateBranchProtection(ctx *context.APIContext) { } ctx.JSON(http.StatusCreated, convert.ToBranchProtection(bp)) - } // EditBranchProtection edits a branch protection for a repo diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index 55fcefaccc382..9ee68283307bc 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -127,6 +127,6 @@ func CreateFork(ctx *context.APIContext) { return } - //TODO change back to 201 + // TODO change back to 201 ctx.JSON(http.StatusAccepted, convert.ToRepo(fork, models.AccessModeOwner)) } diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 17dad97945330..6b45a3938652c 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -498,7 +498,7 @@ func CreateIssue(ctx *context.APIContext) { DeadlineUnix: deadlineUnix, } - var assigneeIDs = make([]int64, 0) + assigneeIDs := make([]int64, 0) var err error if ctx.Repo.CanWrite(models.UnitTypeIssues) { issue.MilestoneID = form.Milestone diff --git a/routers/api/v1/repo/issue_reaction.go b/routers/api/v1/repo/issue_reaction.go index 3994c6b941349..03a855d39ab0e 100644 --- a/routers/api/v1/repo/issue_reaction.go +++ b/routers/api/v1/repo/issue_reaction.go @@ -225,7 +225,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp ctx.Error(http.StatusInternalServerError, "DeleteCommentReaction", err) return } - //ToDo respond 204 + // ToDo respond 204 ctx.Status(http.StatusOK) } } @@ -434,7 +434,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i ctx.Error(http.StatusInternalServerError, "DeleteIssueReaction", err) return } - //ToDo respond 204 + // ToDo respond 204 ctx.Status(http.StatusOK) } } diff --git a/routers/api/v1/repo/issue_subscription.go b/routers/api/v1/repo/issue_subscription.go index 2bbd72299ab59..f7c76ec270200 100644 --- a/routers/api/v1/repo/issue_subscription.go +++ b/routers/api/v1/repo/issue_subscription.go @@ -125,7 +125,7 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) { return } - //only admin and user for itself can change subscription + // only admin and user for itself can change subscription if user.ID != ctx.User.ID && !ctx.User.IsAdmin { ctx.Error(http.StatusForbidden, "User", nil) return @@ -267,7 +267,7 @@ func GetIssueSubscribers(ctx *context.APIContext) { return } - var userIDs = make([]int64, 0, len(iwl)) + userIDs := make([]int64, 0, len(iwl)) for _, iw := range iwl { userIDs = append(userIDs, iw.UserID) } diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go index 642704800b5c8..e698fa887c6a7 100644 --- a/routers/api/v1/repo/issue_tracked_time.go +++ b/routers/api/v1/repo/issue_tracked_time.go @@ -192,7 +192,7 @@ func AddTime(ctx *context.APIContext) { user := ctx.User if form.User != "" { if (ctx.IsUserRepoAdmin() && ctx.User.Name != form.User) || ctx.User.IsAdmin { - //allow only RepoAdmin, Admin and User to add time + // allow only RepoAdmin, Admin and User to add time user, err = models.GetUserByName(form.User) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserByName", err) @@ -356,7 +356,7 @@ func DeleteTime(ctx *context.APIContext) { } if !ctx.User.IsAdmin && time.UserID != ctx.User.ID { - //Only Admin and User itself can delete their time + // Only Admin and User itself can delete their time ctx.Status(http.StatusForbidden) return } diff --git a/routers/api/v1/repo/migrate.go b/routers/api/v1/repo/migrate.go index 1eefa78d570aa..1f2821ba99f9e 100644 --- a/routers/api/v1/repo/migrate.go +++ b/routers/api/v1/repo/migrate.go @@ -51,7 +51,7 @@ func Migrate(ctx *context.APIContext) { form := web.GetForm(ctx).(*api.MigrateRepoOptions) - //get repoOwner + // get repoOwner var ( repoOwner *models.User err error @@ -137,7 +137,7 @@ func Migrate(ctx *context.APIContext) { return } - var opts = migrations.MigrateOptions{ + opts := migrations.MigrateOptions{ CloneAddr: remoteAddr, RepoName: form.RepoName, Description: form.Description, diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go index fc8b4efdbb243..0d1046ab8cc66 100644 --- a/routers/api/v1/repo/milestone.go +++ b/routers/api/v1/repo/milestone.go @@ -211,7 +211,7 @@ func EditMilestone(ctx *context.APIContext) { milestone.DeadlineUnix = timeutil.TimeStamp(form.Deadline.Unix()) } - var oldIsClosed = milestone.IsClosed + oldIsClosed := milestone.IsClosed if form.State != nil { milestone.IsClosed = *form.State == string(api.StateClosed) } diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index e3be5b4af497d..b14e51863769e 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -87,7 +87,6 @@ func ListPullRequests(ctx *context.APIContext) { Labels: ctx.QueryStrings("labels"), MilestoneID: ctx.QueryInt64("milestone"), }) - if err != nil { ctx.Error(http.StatusInternalServerError, "PullRequests", err) return diff --git a/routers/api/v1/repo/pull_review.go b/routers/api/v1/repo/pull_review.go index 63179aa9907db..16643e47fa18d 100644 --- a/routers/api/v1/repo/pull_review.go +++ b/routers/api/v1/repo/pull_review.go @@ -83,7 +83,6 @@ func ListPullReviews(ctx *context.APIContext) { Type: models.ReviewTypeUnknown, IssueID: pr.IssueID, }) - if err != nil { ctx.Error(http.StatusInternalServerError, "FindReviews", err) return diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go index 0a6425cddc536..208f8c39b09a2 100644 --- a/routers/api/v1/repo/release_attachment.go +++ b/routers/api/v1/repo/release_attachment.go @@ -189,7 +189,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) { return } - var filename = header.Filename + filename := header.Filename if query := ctx.Query("name"); query != "" { filename = query } diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index b7ed2951ad663..7799b343124fe 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -155,7 +155,7 @@ func Search(ctx *context.APIContext) { opts.Collaborate = util.OptionalBoolFalse } - var mode = ctx.Query("mode") + mode := ctx.Query("mode") switch mode { case "source": opts.Fork = util.OptionalBoolFalse @@ -181,9 +181,9 @@ func Search(ctx *context.APIContext) { opts.IsPrivate = util.OptionalBoolOf(ctx.QueryBool("is_private")) } - var sortMode = ctx.Query("sort") + sortMode := ctx.Query("sort") if len(sortMode) > 0 { - var sortOrder = ctx.Query("order") + sortOrder := ctx.Query("order") if len(sortOrder) == 0 { sortOrder = "asc" } diff --git a/routers/api/v1/repo/repo_test.go b/routers/api/v1/repo/repo_test.go index a1bd3e85d75a5..22be4a3761392 100644 --- a/routers/api/v1/repo/repo_test.go +++ b/routers/api/v1/repo/repo_test.go @@ -54,7 +54,7 @@ func TestRepoEdit(t *testing.T) { Archived: &archived, } - var apiCtx = &context.APIContext{Context: ctx, Org: nil} + apiCtx := &context.APIContext{Context: ctx, Org: nil} web.SetForm(apiCtx, &opts) Edit(apiCtx) @@ -76,7 +76,7 @@ func TestRepoEditNameChange(t *testing.T) { Name: &name, } - var apiCtx = &context.APIContext{Context: ctx, Org: nil} + apiCtx := &context.APIContext{Context: ctx, Org: nil} web.SetForm(apiCtx, &opts) Edit(apiCtx) assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) diff --git a/routers/api/v1/repo/status.go b/routers/api/v1/repo/status.go index 7ab399b572752..ee05e7bd307b5 100644 --- a/routers/api/v1/repo/status.go +++ b/routers/api/v1/repo/status.go @@ -177,7 +177,7 @@ func GetCommitStatusesByRef(ctx *context.APIContext) { return } - for _, reftype := range []string{"heads", "tags"} { //Search branches and tags + for _, reftype := range []string{"heads", "tags"} { // Search branches and tags refSHA, lastMethodName, err := searchRefCommitByType(ctx, reftype, filter) if err != nil { ctx.Error(http.StatusInternalServerError, lastMethodName, err) @@ -190,16 +190,16 @@ func GetCommitStatusesByRef(ctx *context.APIContext) { } - getCommitStatuses(ctx, filter) //By default filter is maybe the raw SHA + getCommitStatuses(ctx, filter) // By default filter is maybe the raw SHA } func searchRefCommitByType(ctx *context.APIContext, refType, filter string) (string, string, error) { - refs, lastMethodName, err := getGitRefs(ctx, refType+"/"+filter) //Search by type + refs, lastMethodName, err := getGitRefs(ctx, refType+"/"+filter) // Search by type if err != nil { return "", lastMethodName, err } if len(refs) > 0 { - return refs[0].Object.String(), "", nil //Return found SHA + return refs[0].Object.String(), "", nil // Return found SHA } return "", "", nil } diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go index 51bcaeacc6c4a..c46a2a0bfde2c 100644 --- a/routers/api/v1/user/gpg_key.go +++ b/routers/api/v1/user/gpg_key.go @@ -30,7 +30,7 @@ func listGPGKeys(ctx *context.APIContext, uid int64, listOptions models.ListOpti ctx.JSON(http.StatusOK, &apiKeys) } -//ListGPGKeys get the GPG key list of a user +// ListGPGKeys get the GPG key list of a user func ListGPGKeys(ctx *context.APIContext) { // swagger:operation GET /users/{username}/gpg_keys user userListGPGKeys // --- @@ -62,7 +62,7 @@ func ListGPGKeys(ctx *context.APIContext) { listGPGKeys(ctx, user.ID, utils.GetListOptions(ctx)) } -//ListMyGPGKeys get the GPG key list of the authenticated user +// ListMyGPGKeys get the GPG key list of the authenticated user func ListMyGPGKeys(ctx *context.APIContext) { // swagger:operation GET /user/gpg_keys user userCurrentListGPGKeys // --- @@ -85,7 +85,7 @@ func ListMyGPGKeys(ctx *context.APIContext) { listGPGKeys(ctx, ctx.User.ID, utils.GetListOptions(ctx)) } -//GetGPGKey get the GPG key based on a id +// GetGPGKey get the GPG key based on a id func GetGPGKey(ctx *context.APIContext) { // swagger:operation GET /user/gpg_keys/{id} user userCurrentGetGPGKey // --- @@ -133,7 +133,7 @@ type swaggerUserCurrentPostGPGKey struct { Form api.CreateGPGKeyOption } -//CreateGPGKey create a GPG key belonging to the authenticated user +// CreateGPGKey create a GPG key belonging to the authenticated user func CreateGPGKey(ctx *context.APIContext) { // swagger:operation POST /user/gpg_keys user userCurrentPostGPGKey // --- @@ -154,7 +154,7 @@ func CreateGPGKey(ctx *context.APIContext) { CreateUserGPGKey(ctx, *form, ctx.User.ID) } -//DeleteGPGKey remove a GPG key belonging to the authenticated user +// DeleteGPGKey remove a GPG key belonging to the authenticated user func DeleteGPGKey(ctx *context.APIContext) { // swagger:operation DELETE /user/gpg_keys/{id} user userCurrentDeleteGPGKey // --- diff --git a/routers/api/v1/user/watch.go b/routers/api/v1/user/watch.go index ab656f3229ffb..e12da13595427 100644 --- a/routers/api/v1/user/watch.go +++ b/routers/api/v1/user/watch.go @@ -164,7 +164,6 @@ func Watch(ctx *context.APIContext) { URL: subscriptionURL(ctx.Repo.Repository), RepositoryURL: ctx.Repo.Repository.APIURL(), }) - } // Unwatch the repo specified in ctx, as the authenticated user diff --git a/routers/home.go b/routers/home.go index 9f54c7aa64151..85622cb9bc135 100644 --- a/routers/home.go +++ b/routers/home.go @@ -80,9 +80,7 @@ type RepoSearchOptions struct { TplName base.TplName } -var ( - nullByte = []byte{0x00} -) +var nullByte = []byte{0x00} func isKeywordValid(keyword string) bool { return !bytes.Contains([]byte(keyword), nullByte) @@ -342,7 +340,7 @@ func ExploreCode(ctx *context.Context) { return } - var rightRepoMap = make(map[int64]*models.Repository, len(repoMaps)) + rightRepoMap := make(map[int64]*models.Repository, len(repoMaps)) repoIDs = make([]int64, 0, len(repoMaps)) for id, repo := range repoMaps { if repo.CheckUnitUser(ctx.User, models.UnitTypeCode) { @@ -366,7 +364,7 @@ func ExploreCode(ctx *context.Context) { return } - var loadRepoIDs = make([]int64, 0, len(searchResults)) + loadRepoIDs := make([]int64, 0, len(searchResults)) for _, result := range searchResults { var find bool for _, id := range loadRepoIDs { diff --git a/routers/install.go b/routers/install.go index 7f01738efef6c..caec36a5eb9ab 100644 --- a/routers/install.go +++ b/routers/install.go @@ -39,7 +39,7 @@ const ( // InstallInit prepare for rendering installation page func InstallInit(next http.Handler) http.Handler { - var rnd = templates.HTMLRenderer() + rnd := templates.HTMLRenderer() return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { if setting.InstallLock { @@ -47,9 +47,9 @@ func InstallInit(next http.Handler) http.Handler { _ = rnd.HTML(resp, 200, string(tplPostInstall), nil) return } - var locale = middleware.Locale(resp, req) - var startTime = time.Now() - var ctx = context.Context{ + locale := middleware.Locale(resp, req) + startTime := time.Now() + ctx := context.Context{ Resp: context.NewResponse(resp), Flash: &middleware.Flash{}, Locale: locale, @@ -87,7 +87,7 @@ func Install(ctx *context.Context) { form.DbSchema = setting.Database.Schema form.Charset = setting.Database.Charset - var curDBOption = "MySQL" + curDBOption := "MySQL" switch setting.Database.Type { case "postgres": curDBOption = "PostgreSQL" diff --git a/routers/org/home.go b/routers/org/home.go index ff3e1e3e72eb5..615bfd0e524bb 100644 --- a/routers/org/home.go +++ b/routers/org/home.go @@ -97,7 +97,7 @@ func Home(ctx *context.Context) { return } - var opts = models.FindOrgMembersOpts{ + opts := models.FindOrgMembersOpts{ OrgID: org.ID, PublicOnly: true, ListOptions: models.ListOptions{Page: 1, PageSize: 25}, diff --git a/routers/org/members.go b/routers/org/members.go index 00ca381ad0cad..f02c4d8dfb43a 100644 --- a/routers/org/members.go +++ b/routers/org/members.go @@ -29,7 +29,7 @@ func Members(ctx *context.Context) { page = 1 } - var opts = models.FindOrgMembersOpts{ + opts := models.FindOrgMembersOpts{ OrgID: org.ID, PublicOnly: true, } diff --git a/routers/org/teams.go b/routers/org/teams.go index cfa49d4e97f0a..3be3027810a00 100644 --- a/routers/org/teams.go +++ b/routers/org/teams.go @@ -193,7 +193,7 @@ func NewTeamPost(ctx *context.Context) { ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeamsNew"] = true ctx.Data["Units"] = models.Units - var includesAllRepositories = (form.RepoAccess == "all") + includesAllRepositories := (form.RepoAccess == "all") t := &models.Team{ OrgID: ctx.Org.Organization.ID, @@ -205,7 +205,7 @@ func NewTeamPost(ctx *context.Context) { } if t.Authorize < models.AccessModeOwner { - var units = make([]*models.TeamUnit, 0, len(form.Units)) + units := make([]*models.TeamUnit, 0, len(form.Units)) for _, tp := range form.Units { units = append(units, &models.TeamUnit{ OrgID: ctx.Org.Organization.ID, @@ -286,7 +286,7 @@ func EditTeamPost(ctx *context.Context) { isAuthChanged := false isIncludeAllChanged := false - var includesAllRepositories = (form.RepoAccess == "all") + includesAllRepositories := (form.RepoAccess == "all") if !t.IsOwnerTeam() { // Validate permission level. auth := models.ParseAccessMode(form.Permission) @@ -304,7 +304,7 @@ func EditTeamPost(ctx *context.Context) { } t.Description = form.Description if t.Authorize < models.AccessModeOwner { - var units = make([]models.TeamUnit, 0, len(form.Units)) + units := make([]models.TeamUnit, 0, len(form.Units)) for _, tp := range form.Units { units = append(units, models.TeamUnit{ OrgID: t.OrgID, diff --git a/routers/private/internal.go b/routers/private/internal.go index e541591a3840b..37e75497ae769 100644 --- a/routers/private/internal.go +++ b/routers/private/internal.go @@ -35,12 +35,12 @@ func CheckInternalToken(next http.Handler) http.Handler { // bind binding an obj to a handler func bind(obj interface{}) http.HandlerFunc { - var tp = reflect.TypeOf(obj) + tp := reflect.TypeOf(obj) for tp.Kind() == reflect.Ptr { tp = tp.Elem() } return web.Wrap(func(ctx *context.PrivateContext) { - var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly + theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly binding.Bind(ctx.Req, theObj) web.SetForm(ctx, theObj) }) @@ -49,7 +49,7 @@ func bind(obj interface{}) http.HandlerFunc { // Routes registers all internal APIs routes to web application. // These APIs will be invoked by internal commands for example `gitea serv` and etc. func Routes() *web.Route { - var r = web.NewRoute() + r := web.NewRoute() r.Use(context.PrivateContexter()) r.Use(CheckInternalToken) diff --git a/routers/private/manager_unix.go b/routers/private/manager_unix.go index 60ae9b68e82ca..63cca1cd2b4c3 100644 --- a/routers/private/manager_unix.go +++ b/routers/private/manager_unix.go @@ -17,7 +17,6 @@ import ( func Restart(ctx *context.PrivateContext) { graceful.GetManager().DoGracefulRestart() ctx.PlainText(http.StatusOK, []byte("success")) - } // Shutdown causes the server to perform a graceful shutdown diff --git a/routers/repo/attachment.go b/routers/repo/attachment.go index 5df9cdbf12a62..7c752f6934594 100644 --- a/routers/repo/attachment.go +++ b/routers/repo/attachment.go @@ -107,12 +107,12 @@ func GetAttachment(ctx *context.Context) { return } - if repository == nil { //If not linked - if !(ctx.IsSigned && attach.UploaderID == ctx.User.ID) { //We block if not the uploader + if repository == nil { // If not linked + if !(ctx.IsSigned && attach.UploaderID == ctx.User.ID) { // We block if not the uploader ctx.Error(http.StatusNotFound) return } - } else { //If we have the repository we check access + } else { // If we have the repository we check access perm, err := models.GetUserRepoPermission(repository, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err.Error()) @@ -125,7 +125,7 @@ func GetAttachment(ctx *context.Context) { } if setting.Attachment.ServeDirect { - //If we have a signed url (S3, object storage), redirect to this directly. + // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.Attachments.URL(attach.RelativePath(), attach.Name) if u != nil && err == nil { @@ -139,7 +139,7 @@ func GetAttachment(ctx *context.Context) { } } - //If we have matched and access to release or issue + // If we have matched and access to release or issue fr, err := storage.Attachments.Open(attach.RelativePath()) if err != nil { ctx.ServerError("Open", err) diff --git a/routers/repo/blame.go b/routers/repo/blame.go index 9be1ea05af9b4..b0fde182a6939 100644 --- a/routers/repo/blame.go +++ b/routers/repo/blame.go @@ -190,19 +190,19 @@ func RefBlame(ctx *context.Context) { func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames map[string]models.UserCommit) { repoLink := ctx.Repo.RepoLink - var lines = make([]string, 0) + lines := make([]string, 0) var commitInfo bytes.Buffer var lineNumbers bytes.Buffer var codeLines bytes.Buffer - var i = 0 + i := 0 for pi, part := range blameParts { for index, line := range part.Lines { i++ lines = append(lines, line) - var attr = "" + attr := "" if len(part.Lines)-1 == index && len(blameParts)-1 != pi { attr = " bottom-line" } @@ -223,7 +223,7 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m commitInfo.WriteString(fmt.Sprintf(`
`, attr)) } - //Line number + // Line number if len(part.Lines)-1 == index && len(blameParts)-1 != pi { lineNumbers.WriteString(fmt.Sprintf(``, i, i)) } else { diff --git a/routers/repo/branch.go b/routers/repo/branch.go index ac6b7a1bed080..a3d6329bafeea 100644 --- a/routers/repo/branch.go +++ b/routers/repo/branch.go @@ -239,7 +239,7 @@ func loadBranches(ctx *context.Context, skip, limit int) ([]*Branch, int) { continue } - var branch = loadOneBranch(ctx, rawBranches[i], protectedBranches, repoIDToRepo, repoIDToGitRepo) + branch := loadOneBranch(ctx, rawBranches[i], protectedBranches, repoIDToRepo, repoIDToGitRepo) if branch == nil { return nil, 0 } diff --git a/routers/repo/compare.go b/routers/repo/compare.go index a8f4f8add8d67..a76d5f8e08627 100644 --- a/routers/repo/compare.go +++ b/routers/repo/compare.go @@ -27,7 +27,7 @@ const ( ) // setPathsCompareContext sets context data for source and raw paths -func setPathsCompareContext(ctx *context.Context, base *git.Commit, head *git.Commit, headTarget string) { +func setPathsCompareContext(ctx *context.Context, base, head *git.Commit, headTarget string) { sourcePath := setting.AppSubURL + "/%s/src/commit/%s" rawPath := setting.AppSubURL + "/%s/raw/commit/%s" @@ -41,7 +41,7 @@ func setPathsCompareContext(ctx *context.Context, base *git.Commit, head *git.Co } // setImageCompareContext sets context data that is required by image compare template -func setImageCompareContext(ctx *context.Context, base *git.Commit, head *git.Commit) { +func setImageCompareContext(ctx *context.Context, base, head *git.Commit) { ctx.Data["IsImageFileInHead"] = head.IsImageFile ctx.Data["IsImageFileInBase"] = base.IsImageFile ctx.Data["ImageInfoBase"] = func(name string) *git.ImageMetaData { @@ -413,7 +413,6 @@ func PrepareCompareDiff( compareInfo *git.CompareInfo, baseBranch, headBranch string, whitespaceBehavior string) bool { - var ( repo = ctx.Repo.Repository err error @@ -638,7 +637,8 @@ func ExcerptBlob(ctx *context.Context) { RightIdx: idxRight, LeftHunkSize: leftHunkSize, RightHunkSize: rightHunkSize, - }} + }, + } if direction == "up" { section.Lines = append([]*gitdiff.DiffLine{lineSection}, section.Lines...) } else if direction == "down" { @@ -652,7 +652,7 @@ func ExcerptBlob(ctx *context.Context) { ctx.HTML(200, tplBlobExcerpt) } -func getExcerptLines(commit *git.Commit, filePath string, idxLeft int, idxRight int, chunkSize int) ([]*gitdiff.DiffLine, error) { +func getExcerptLines(commit *git.Commit, filePath string, idxLeft, idxRight, chunkSize int) ([]*gitdiff.DiffLine, error) { blob, err := commit.Tree.GetBlobByPath(filePath) if err != nil { return nil, err diff --git a/routers/repo/editor.go b/routers/repo/editor.go index 14a75556d2b27..00568064e31f4 100644 --- a/routers/repo/editor.go +++ b/routers/repo/editor.go @@ -49,7 +49,7 @@ func renderCommitRights(ctx *context.Context) bool { // getParentTreeFields returns list of parent tree names and corresponding tree paths // based on given tree path. -func getParentTreeFields(treePath string) (treeNames []string, treePaths []string) { +func getParentTreeFields(treePath string) (treeNames, treePaths []string) { if len(treePath) == 0 { return treeNames, treePaths } diff --git a/routers/repo/editor_test.go b/routers/repo/editor_test.go index ec7aee1e77ff9..9360767708934 100644 --- a/routers/repo/editor_test.go +++ b/routers/repo/editor_test.go @@ -17,7 +17,7 @@ import ( func TestCleanUploadName(t *testing.T) { models.PrepareTestEnv(t) - var kases = map[string]string{ + kases := map[string]string{ ".git/refs/master": "", "/root/abc": "root/abc", "./../../abc": "abc", diff --git a/routers/repo/http.go b/routers/repo/http.go index 0377979e8bb5c..6d7258065049e 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -102,7 +102,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) { } isWiki := false - var unitType = models.UnitTypeCode + unitType := models.UnitTypeCode if strings.HasSuffix(reponame, ".wiki") { isWiki = true unitType = models.UnitTypeWiki @@ -499,7 +499,6 @@ func serviceRPC(h serviceHandler, service string) { if err := h.r.Body.Close(); err != nil { log.Error("serviceRPC: Close: %v", err) } - }() if !hasAccess(service, h, true) { @@ -510,7 +509,7 @@ func serviceRPC(h serviceHandler, service string) { h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service)) var err error - var reqBody = h.r.Body + reqBody := h.r.Body // Handle GZIP. if h.r.Header.Get("Content-Encoding") == "gzip" { diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 15459cd0e6d3b..dd5b50502310c 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -247,7 +247,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti return } - var commitStatus = make(map[int64]*models.CommitStatus, len(issues)) + commitStatus := make(map[int64]*models.CommitStatus, len(issues)) // Get posters. for i := range issues { @@ -265,7 +265,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti return } - var statuses, _ = pull_service.GetLastCommitStatus(issues[i].PullRequest) + statuses, _ := pull_service.GetLastCommitStatus(issues[i].PullRequest) commitStatus[issues[i].PullRequest.ID] = models.CalcCommitStatus(statuses) } } @@ -429,7 +429,6 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repos } func retrieveProjects(ctx *context.Context, repo *models.Repository) { - var err error ctx.Data["OpenProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{ @@ -721,7 +720,7 @@ func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (str return string(bytes), true } -func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleDirs []string, possibleFiles []string) { +func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleDirs, possibleFiles []string) { templateCandidates := make([]string, 0, len(possibleFiles)) if ctx.Query("template") != "" { for _, dirName := range possibleDirs { @@ -2399,7 +2398,7 @@ func filterXRefComments(ctx *context.Context, issue *models.Issue) error { // GetIssueAttachments returns attachments for the issue func GetIssueAttachments(ctx *context.Context) { issue := GetActionIssue(ctx) - var attachments = make([]*api.Attachment, len(issue.Attachments)) + attachments := make([]*api.Attachment, len(issue.Attachments)) for i := 0; i < len(issue.Attachments); i++ { attachments[i] = convert.ToReleaseAttachment(issue.Attachments[i]) } @@ -2413,7 +2412,7 @@ func GetCommentAttachments(ctx *context.Context) { ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err) return } - var attachments = make([]*api.Attachment, 0) + attachments := make([]*api.Attachment, 0) if comment.Type == models.CommentTypeComment { if err := comment.LoadAttachments(); err != nil { ctx.ServerError("LoadAttachments", err) diff --git a/routers/repo/issue_lock.go b/routers/repo/issue_lock.go index f8131e46aaff6..ef6b152e9efc4 100644 --- a/routers/repo/issue_lock.go +++ b/routers/repo/issue_lock.go @@ -48,7 +48,6 @@ func LockIssue(ctx *context.Context) { // UnlockIssue unlocks a previously locked issue. func UnlockIssue(ctx *context.Context) { - issue := GetActionIssue(ctx) if ctx.Written() { return diff --git a/routers/repo/issue_test.go b/routers/repo/issue_test.go index 7fb837fa124e2..cef82ff2bea9c 100644 --- a/routers/repo/issue_test.go +++ b/routers/repo/issue_test.go @@ -12,7 +12,7 @@ import ( ) func TestCombineLabelComments(t *testing.T) { - var kases = []struct { + kases := []struct { name string beforeCombined []*models.Comment afterCombined []*models.Comment @@ -314,7 +314,7 @@ func TestCombineLabelComments(t *testing.T) { for _, kase := range kases { t.Run(kase.name, func(t *testing.T) { - var issue = models.Issue{ + issue := models.Issue{ Comments: kase.beforeCombined, } combineLabelComments(&issue) diff --git a/routers/repo/lfs.go b/routers/repo/lfs.go index fb0e3b10eae9a..f8434fd96f08c 100644 --- a/routers/repo/lfs.go +++ b/routers/repo/lfs.go @@ -311,7 +311,7 @@ func LFSFileGet(ctx *context.Context) { var output bytes.Buffer lines := strings.Split(fileContent, "\n") - //Remove blank line at the end of file + // Remove blank line at the end of file if len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } @@ -594,7 +594,7 @@ func LFSAutoAssociate(ctx *context.Context) { return } metas[i].Oid = oid[:idx] - //metas[i].RepositoryID = ctx.Repo.Repository.ID + // metas[i].RepositoryID = ctx.Repo.Repository.ID } if err := models.LFSAutoAssociate(metas, ctx.User, ctx.Repo.Repository.ID); err != nil { ctx.ServerError("LFSAutoAssociate", err) diff --git a/routers/repo/migrate.go b/routers/repo/migrate.go index 6b4e7852ae288..f5f638e5b7219 100644 --- a/routers/repo/migrate.go +++ b/routers/repo/migrate.go @@ -173,7 +173,7 @@ func MigratePost(ctx *context.Context) { return } - var opts = migrations.MigrateOptions{ + opts := migrations.MigrateOptions{ OriginalURL: form.CloneAddr, GitServiceType: serviceType, CloneAddr: remoteAddr, diff --git a/routers/repo/projects.go b/routers/repo/projects.go index 4aa03e9efcb26..43a0a6c1d41e0 100644 --- a/routers/repo/projects.go +++ b/routers/repo/projects.go @@ -258,7 +258,6 @@ func EditProjectPost(ctx *context.Context) { // ViewProject renders the project board for a project func ViewProject(ctx *context.Context) { - project, err := models.GetProjectByID(ctx.ParamsInt64(":id")) if err != nil { if models.IsErrProjectNotExist(err) { @@ -509,7 +508,6 @@ func EditProjectBoard(ctx *context.Context) { // SetDefaultProjectBoard set default board for uncategorized issues/pulls func SetDefaultProjectBoard(ctx *context.Context) { - project, board := checkProjectBoardChangePermissions(ctx) if ctx.Written() { return @@ -527,7 +525,6 @@ func SetDefaultProjectBoard(ctx *context.Context) { // MoveIssueAcrossBoards move a card from one board to another in a project func MoveIssueAcrossBoards(ctx *context.Context) { - if ctx.User == nil { ctx.JSON(403, map[string]string{ "message": "Only signed in users are allowed to perform this action.", @@ -559,13 +556,11 @@ func MoveIssueAcrossBoards(ctx *context.Context) { var board *models.ProjectBoard if ctx.ParamsInt64(":boardID") == 0 { - board = &models.ProjectBoard{ ID: 0, ProjectID: 0, Title: ctx.Tr("repo.projects.type.uncategorized"), } - } else { board, err = models.GetProjectBoard(ctx.ParamsInt64(":boardID")) if err != nil { @@ -614,7 +609,6 @@ func CreateProject(ctx *context.Context) { // CreateProjectPost creates an individual and/or organization project func CreateProjectPost(ctx *context.Context, form auth.UserCreateProjectForm) { - user := checkContextUser(ctx, form.UID) if ctx.Written() { return @@ -628,7 +622,7 @@ func CreateProjectPost(ctx *context.Context, form auth.UserCreateProjectForm) { return } - var projectType = models.ProjectTypeIndividual + projectType := models.ProjectTypeIndividual if user.IsOrganization() { projectType = models.ProjectTypeOrganization } diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 2ed47605f8eda..a79d22ddc75d7 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -45,16 +45,14 @@ const ( pullRequestTemplateKey = "PullRequestTemplate" ) -var ( - pullRequestTemplateCandidates = []string{ - "PULL_REQUEST_TEMPLATE.md", - "pull_request_template.md", - ".gitea/PULL_REQUEST_TEMPLATE.md", - ".gitea/pull_request_template.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/pull_request_template.md", - } -) +var pullRequestTemplateCandidates = []string{ + "PULL_REQUEST_TEMPLATE.md", + "pull_request_template.md", + ".gitea/PULL_REQUEST_TEMPLATE.md", + ".gitea/pull_request_template.md", + ".github/PULL_REQUEST_TEMPLATE.md", + ".github/pull_request_template.md", +} func getRepository(ctx *context.Context, repoID int64) *models.Repository { repo, err := models.GetRepositoryByID(repoID) @@ -122,7 +120,7 @@ func getForkRepository(ctx *context.Context) *models.Repository { } } - var traverseParentRepo = forkRepo + traverseParentRepo := forkRepo var err error for { if ctx.User.ID == traverseParentRepo.OwnerID { @@ -193,7 +191,7 @@ func ForkPost(ctx *context.Context) { } var err error - var traverseParentRepo = forkRepo + traverseParentRepo := forkRepo for { if ctxUser.ID == traverseParentRepo.OwnerID { ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form) @@ -965,7 +963,6 @@ func MergePullRequest(ctx *context.Context) { } func stopTimerIfAvailable(user *models.User, issue *models.Issue) error { - if models.StopwatchExists(user.ID, issue.ID) { if err := models.CreateOrStopIssueStopwatch(user, issue); err != nil { return err diff --git a/routers/repo/settings_test.go b/routers/repo/settings_test.go index 85515121c7836..84afbb68fe176 100644 --- a/routers/repo/settings_test.go +++ b/routers/repo/settings_test.go @@ -95,7 +95,6 @@ func TestAddReadWriteOnlyDeployKey(t *testing.T) { } func TestCollaborationPost(t *testing.T) { - models.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) @@ -131,7 +130,6 @@ func TestCollaborationPost(t *testing.T) { } func TestCollaborationPost_InactiveUser(t *testing.T) { - models.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) @@ -155,7 +153,6 @@ func TestCollaborationPost_InactiveUser(t *testing.T) { } func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) { - models.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) @@ -197,7 +194,6 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) { } func TestCollaborationPost_NonExistentUser(t *testing.T) { - models.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) @@ -297,7 +293,6 @@ func TestAddTeamPost_NotAllowed(t *testing.T) { assert.False(t, team.HasRepository(re.ID)) assert.EqualValues(t, http.StatusFound, ctx.Resp.Status()) assert.NotEmpty(t, ctx.Flash.ErrorMsg) - } func TestAddTeamPost_AddTeamTwice(t *testing.T) { diff --git a/routers/repo/topic.go b/routers/repo/topic.go index b23023ceba0a1..1dadd83a34a08 100644 --- a/routers/repo/topic.go +++ b/routers/repo/topic.go @@ -21,8 +21,8 @@ func TopicsPost(ctx *context.Context) { return } - var topics = make([]string, 0) - var topicsStr = strings.TrimSpace(ctx.Query("topics")) + topics := make([]string, 0) + topicsStr := strings.TrimSpace(ctx.Query("topics")) if len(topicsStr) > 0 { topics = strings.Split(topicsStr, ",") } diff --git a/routers/repo/view.go b/routers/repo/view.go index 39f16d183c3b1..92ea8ddfc3310 100644 --- a/routers/repo/view.go +++ b/routers/repo/view.go @@ -66,7 +66,7 @@ func getReadmeFileFromPath(commit *git.Commit, treePath string) (*namedBlob, err } var readmeFiles [4]*namedBlob - var exts = []string{".md", ".txt", ""} // sorted by priority + exts := []string{".md", ".txt", ""} // sorted by priority for _, entry := range entries { if entry.IsDir() { continue @@ -155,7 +155,7 @@ func renderDirectory(ctx *context.Context, treeLink string) { // strictly match an extension var readmeFiles [4]*namedBlob var docsEntries [3]*git.TreeEntry - var exts = []string{".md", ".txt", ""} // sorted by priority + exts := []string{".md", ".txt", ""} // sorted by priority for _, entry := range entries { if entry.IsDir() { lowerName := strings.ToLower(entry.Name()) @@ -397,7 +397,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st isDisplayingSource := ctx.Query("display") == "source" isDisplayingRendered := !isDisplayingSource - //Check for LFS meta file + // Check for LFS meta file if isTextFile && setting.LFS.StartServer { meta := lfs.IsPointerFile(&buf) if meta != nil { diff --git a/routers/repo/wiki.go b/routers/repo/wiki.go index c4521a3071a30..9b1ea7a7aad38 100644 --- a/routers/repo/wiki.go +++ b/routers/repo/wiki.go @@ -182,7 +182,7 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) { ctx.Data["title"] = pageName ctx.Data["RequireHighlightJS"] = true - //lookup filename in wiki - get filecontent, gitTree entry , real filename + // lookup filename in wiki - get filecontent, gitTree entry , real filename data, entry, pageFilename, noEntry := wikiContentsByName(ctx, commit, pageName) if noEntry { ctx.Redirect(ctx.Repo.RepoLink + "/wiki/_pages") @@ -249,7 +249,7 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name - //lookup filename in wiki - get filecontent, gitTree entry , real filename + // lookup filename in wiki - get filecontent, gitTree entry , real filename data, entry, pageFilename, noEntry := wikiContentsByName(ctx, commit, pageName) if noEntry { ctx.Redirect(ctx.Repo.RepoLink + "/wiki/_pages") @@ -326,7 +326,7 @@ func renderEditPage(ctx *context.Context) { ctx.Data["title"] = pageName ctx.Data["RequireHighlightJS"] = true - //lookup filename in wiki - get filecontent, gitTree entry , real filename + // lookup filename in wiki - get filecontent, gitTree entry , real filename data, entry, _, noEntry := wikiContentsByName(ctx, commit, pageName) if noEntry { ctx.Redirect(ctx.Repo.RepoLink + "/wiki/_pages") diff --git a/routers/repo/wiki_test.go b/routers/repo/wiki_test.go index badd07f080761..0c4a99f6b9e3a 100644 --- a/routers/repo/wiki_test.go +++ b/routers/repo/wiki_test.go @@ -19,8 +19,10 @@ import ( "github.com/stretchr/testify/assert" ) -const content = "Wiki contents for unit tests" -const message = "Wiki commit message for unit tests" +const ( + content = "Wiki contents for unit tests" + message = "Wiki commit message for unit tests" +) func wikiEntry(t *testing.T, repo *models.Repository, wikiName string) *git.TreeEntry { wikiRepo, err := git.OpenRepository(repo.WikiPath()) diff --git a/routers/routes/base.go b/routers/routes/base.go index 12a35936b10e4..a728ee82235ab 100644 --- a/routers/routes/base.go +++ b/routers/routes/base.go @@ -100,7 +100,7 @@ func storageHandler(storageSetting setting.Storage, prefix string, objStore stor return } - //If we have matched and access to release or issue + // If we have matched and access to release or issue fr, err := objStore.Open(rPath) if err != nil { if os.IsNotExist(err) || errors.Is(err, os.ErrNotExist) { @@ -135,7 +135,7 @@ func (d *dataStore) GetData() map[string]interface{} { // Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so. // This error will be created with the gitea 500 page. func Recovery() func(next http.Handler) http.Handler { - var rnd = templates.HTMLRenderer() + rnd := templates.HTMLRenderer() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { defer func() { @@ -153,8 +153,8 @@ func Recovery() func(next http.Handler) http.Handler { return } - var lc = middleware.Locale(w, req) - var store = dataStore{ + lc := middleware.Locale(w, req) + store := dataStore{ Data: templates.Vars{ "Language": lc.Language(), "CurrentURL": setting.AppSubURL + req.URL.RequestURI(), diff --git a/routers/routes/install.go b/routers/routes/install.go index fea396bc26c47..347c53667f9bc 100644 --- a/routers/routes/install.go +++ b/routers/routes/install.go @@ -22,7 +22,7 @@ import ( ) func installRecovery() func(next http.Handler) http.Handler { - var rnd = templates.HTMLRenderer() + rnd := templates.HTMLRenderer() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { defer func() { @@ -47,7 +47,7 @@ func installRecovery() func(next http.Handler) http.Handler { log.Error("%v", combinedErr) lc := middleware.Locale(w, req) - var store = dataStore{ + store := dataStore{ Data: templates.Vars{ "Language": lc.Language(), "CurrentURL": setting.AppSubURL + req.URL.RequestURI(), diff --git a/routers/routes/web.go b/routers/routes/web.go index 166b4286a87bc..27d12f6827eb0 100644 --- a/routers/routes/web.go +++ b/routers/routes/web.go @@ -60,7 +60,7 @@ const ( ) func commonMiddlewares() []func(http.Handler) http.Handler { - var handlers = []func(http.Handler) http.Handler{ + handlers := []func(http.Handler) http.Handler{ func(next http.Handler) http.Handler { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { next.ServeHTTP(context.NewResponse(resp), req) @@ -307,7 +307,7 @@ func RegisterRoutes(m *web.Route) { ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true}) reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true}) - //bindIgnErr := binding.BindIgnErr + // bindIgnErr := binding.BindIgnErr bindIgnErr := web.Bind validation.AddBindingRules() @@ -396,7 +396,6 @@ func RegisterRoutes(m *web.Route) { m.Get("", user.U2F) m.Get("/challenge", user.U2FChallenge) m.Post("/sign", bindIgnErr(u2f.SignResponse{}), user.U2FSign) - }) }, reqSignOut) @@ -410,9 +409,9 @@ func RegisterRoutes(m *web.Route) { }, ignSignInAndCsrf, reqSignIn) if setting.CORSConfig.Enabled { m.Post("/login/oauth/access_token", cors.Handler(cors.Options{ - //Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option + // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option AllowedOrigins: setting.CORSConfig.AllowDomain, - //setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option + // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option AllowedMethods: setting.CORSConfig.Methods, AllowCredentials: setting.CORSConfig.AllowCredentials, MaxAge: int(setting.CORSConfig.MaxAge.Seconds()), @@ -775,7 +774,6 @@ func RegisterRoutes(m *web.Route) { m.Post("/{lid}/unlock", repo.LFSUnlock) }) }) - }, func(ctx *context.Context) { ctx.Data["PageIsSettings"] = true ctx.Data["LFSStartServer"] = setting.LFS.StartServer @@ -898,7 +896,6 @@ func RegisterRoutes(m *web.Route) { m.Post("/delete", repo.DeleteBranchPost) m.Post("/restore", repo.RestoreBranchPost) }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty) - }, reqSignIn, context.RepoAssignment(), context.UnitTypes()) // Releases diff --git a/routers/user/auth.go b/routers/user/auth.go index 37181c68e7a24..ec2922d98cb99 100644 --- a/routers/user/auth.go +++ b/routers/user/auth.go @@ -495,7 +495,7 @@ func handleSignIn(ctx *context.Context, u *models.User, remember bool) { handleSignInFull(ctx, u, remember, true) } -func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyRedirect bool) string { +func handleSignInFull(ctx *context.Context, u *models.User, remember, obeyRedirect bool) string { if remember { days := 86400 * setting.LogInRememberDays ctx.SetCookie(setting.CookieUserName, u.Name, days) @@ -699,7 +699,6 @@ func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context // login the user func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) { gothUser, err := oauth2.ProviderCallback(loginSource.Name, request, response) - if err != nil { if err.Error() == "securecookie: the value is too long" { log.Error("OAuth2 Provider %s returned too long a token. Current max: %d. Either increase the [OAuth2] MAX_TOKEN_LENGTH or reduce the information returned from the OAuth2 provider", loginSource.Name, setting.OAuth2.MaxTokenLength) @@ -739,7 +738,6 @@ func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Requ // no user found to login return nil, gothUser, nil - } // LinkAccount shows the page where the user can decide to login or create a new account @@ -1081,7 +1079,7 @@ func SignUp(ctx *context.Context) { ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey ctx.Data["PageIsSignUp"] = true - //Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true + // Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration ctx.HTML(200, tplSignUp) @@ -1102,7 +1100,7 @@ func SignUpPost(ctx *context.Context) { ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey ctx.Data["PageIsSignUp"] = true - //Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true + // Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true if setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration { ctx.Error(403) return diff --git a/routers/user/auth_openid.go b/routers/user/auth_openid.go index 967e8aad2d436..fe00abdfa0794 100644 --- a/routers/user/auth_openid.go +++ b/routers/user/auth_openid.go @@ -66,7 +66,6 @@ func SignInOpenID(ctx *context.Context) { // Check if the given OpenID URI is allowed by blacklist/whitelist func allowedOpenIDURI(uri string) (err error) { - // In case a Whitelist is present, URI must be in it // in order to be accepted if len(setting.Service.OpenIDWhitelist) != 0 { @@ -143,13 +142,12 @@ func SignInOpenIDPost(ctx *context.Context) { // signInOpenIDVerify handles response from OpenID provider func signInOpenIDVerify(ctx *context.Context) { - log.Trace("Incoming call to: " + ctx.Req.URL.String()) fullURL := setting.AppURL + ctx.Req.URL.String()[1:] log.Trace("Full URL: " + fullURL) - var id, err = openid.Verify(fullURL) + id, err := openid.Verify(fullURL) if err != nil { ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{ Openid: id, diff --git a/routers/user/home.go b/routers/user/home.go index 24aaf00ba829e..47aefd0579f0e 100644 --- a/routers/user/home.go +++ b/routers/user/home.go @@ -211,7 +211,7 @@ func Milestones(ctx *context.Context) { if issueReposQueryPattern.MatchString(reposQuery) { // remove "[" and "]" from string reposQuery = reposQuery[1 : len(reposQuery)-1] - //for each ID (delimiter ",") add to int to repoIDs + // for each ID (delimiter ",") add to int to repoIDs for _, rID := range strings.Split(reposQuery, ",") { // Ensure nonempty string entries @@ -353,7 +353,6 @@ func Issues(ctx *context.Context) { var issueReposQueryPattern = regexp.MustCompile(`^\[\d+(,\d+)*,?\]$`) func buildIssueOverview(ctx *context.Context, unitType models.UnitType) { - // ---------------------------------------------------- // Determine user; can be either user or organization. // Return with NotFound or ServerError if unsuccessful. @@ -546,12 +545,12 @@ func buildIssueOverview(ctx *context.Context, unitType models.UnitType) { } // maps pull request IDs to their CommitStatus. Will be posted to ctx.Data. - var commitStatus = make(map[int64]*models.CommitStatus, len(issues)) + commitStatus := make(map[int64]*models.CommitStatus, len(issues)) for _, issue := range issues { issue.Repo = showReposMap[issue.RepoID] if isPullList { - var statuses, _ = pull_service.GetLastCommitStatus(issue.PullRequest) + statuses, _ := pull_service.GetLastCommitStatus(issue.PullRequest) commitStatus[issue.PullRequest.ID] = models.CalcCommitStatus(statuses) } } @@ -720,7 +719,7 @@ func getRepoIDs(reposQuery string) []int64 { var repoIDs []int64 // remove "[" and "]" from string reposQuery = reposQuery[1 : len(reposQuery)-1] - //for each ID (delimiter ",") add to int to repoIDs + // for each ID (delimiter ",") add to int to repoIDs for _, rID := range strings.Split(reposQuery, ",") { // Ensure nonempty string entries if rID != "" && rID != "0" { @@ -863,7 +862,7 @@ func ShowGPGKeys(ctx *context.Context, uid int64) { if err != nil { if models.IsErrGPGKeyImportNotExist(err) { failedEntitiesID = append(failedEntitiesID, k.KeyID) - continue //Skip previous import without backup of imported armored key + continue // Skip previous import without backup of imported armored key } ctx.ServerError("ShowGPGKeys", err) return @@ -873,12 +872,12 @@ func ShowGPGKeys(ctx *context.Context, uid int64) { var buf bytes.Buffer headers := make(map[string]string) - if len(failedEntitiesID) > 0 { //If some key need re-import to be exported + if len(failedEntitiesID) > 0 { // If some key need re-import to be exported headers["Note"] = fmt.Sprintf("The keys with the following IDs couldn't be exported and need to be reuploaded %s", strings.Join(failedEntitiesID, ", ")) } writer, _ := armor.Encode(&buf, "PGP PUBLIC KEY BLOCK", headers) for _, e := range entities { - err = e.Serialize(writer) //TODO find why key are exported with a different cipherTypeByte as original (should not be blocking but strange) + err = e.Serialize(writer) // TODO find why key are exported with a different cipherTypeByte as original (should not be blocking but strange) if err != nil { ctx.ServerError("ShowGPGKeys", err) return diff --git a/routers/user/oauth.go b/routers/user/oauth.go index d943ec4200b6d..32c2b03b84005 100644 --- a/routers/user/oauth.go +++ b/routers/user/oauth.go @@ -533,7 +533,7 @@ func handleAccessTokenError(ctx *context.Context, acErr AccessTokenError) { ctx.JSON(400, acErr) } -func handleServerError(ctx *context.Context, state string, redirectURI string) { +func handleServerError(ctx *context.Context, state, redirectURI string) { handleAuthorizeError(ctx, AuthorizeError{ ErrorCode: ErrorCodeServerError, ErrorDescription: "A server error occurred", diff --git a/routers/user/profile.go b/routers/user/profile.go index ea4a1e8893466..3074cf62946cd 100644 --- a/routers/user/profile.go +++ b/routers/user/profile.go @@ -195,7 +195,8 @@ func Profile(ctx *context.Context) { total = ctxUser.NumFollowing case "activity": - retrieveFeeds(ctx, models.GetFeedsOptions{RequestedUser: ctxUser, + retrieveFeeds(ctx, models.GetFeedsOptions{ + RequestedUser: ctxUser, Actor: ctx.User, IncludePrivate: showPrivate, OnlyPerformedBy: true, diff --git a/routers/user/setting/account_test.go b/routers/user/setting/account_test.go index 0e7e147b8bc72..849d2821177a2 100644 --- a/routers/user/setting/account_test.go +++ b/routers/user/setting/account_test.go @@ -20,9 +20,9 @@ import ( func TestChangePassword(t *testing.T) { oldPassword := "password" setting.MinPasswordLength = 6 - var pcALL = []string{"lower", "upper", "digit", "spec"} - var pcLUN = []string{"lower", "upper", "digit"} - var pcLU = []string{"lower", "upper"} + pcALL := []string{"lower", "upper", "digit", "spec"} + pcLUN := []string{"lower", "upper", "digit"} + pcLU := []string{"lower", "upper"} for _, req := range []struct { OldPassword string diff --git a/routers/user/setting/keys.go b/routers/user/setting/keys.go index a52ffd667bdcb..4e83478cf262f 100644 --- a/routers/user/setting/keys.go +++ b/routers/user/setting/keys.go @@ -148,12 +148,10 @@ func KeysPost(ctx *context.Context) { ctx.Flash.Warning("Function not implemented") ctx.Redirect(setting.AppSubURL + "/user/settings/keys") } - } // DeleteKey response for delete user's SSH/GPG key func DeleteKey(ctx *context.Context) { - switch ctx.Query("type") { case "gpg": if err := models.DeleteGPGKey(ctx.User, ctx.QueryInt64("id")); err != nil { diff --git a/services/archiver/archiver.go b/services/archiver/archiver.go index 359fc8b627d91..c9e5a140412f1 100644 --- a/services/archiver/archiver.go +++ b/services/archiver/archiver.go @@ -41,8 +41,10 @@ type ArchiveRequest struct { cchan chan struct{} } -var archiveInProgress []*ArchiveRequest -var archiveMutex sync.Mutex +var ( + archiveInProgress []*ArchiveRequest + archiveMutex sync.Mutex +) // SHA1 hashes will only go up to 40 characters, but SHA256 hashes will go all // the way to 64. @@ -50,9 +52,11 @@ var shaRegex = regexp.MustCompile(`^[0-9a-f]{4,64}$`) // These facilitate testing, by allowing the unit tests to control (to some extent) // the goroutine used for processing the queue. -var archiveQueueMutex *sync.Mutex -var archiveQueueStartCond *sync.Cond -var archiveQueueReleaseCond *sync.Cond +var ( + archiveQueueMutex *sync.Mutex + archiveQueueStartCond *sync.Cond + archiveQueueReleaseCond *sync.Cond +) // GetArchivePath returns the path from which we can serve this archive. func (aReq *ArchiveRequest) GetArchivePath() string { diff --git a/services/gitdiff/gitdiff.go b/services/gitdiff/gitdiff.go index 9f038c8744eef..c220c8782e752 100644 --- a/services/gitdiff/gitdiff.go +++ b/services/gitdiff/gitdiff.go @@ -183,9 +183,11 @@ var ( codeTagSuffix = []byte(``) ) -var unfinishedtagRegex = regexp.MustCompile(`<[^>]*$`) -var trailingSpanRegex = regexp.MustCompile(`]?$`) -var entityRegex = regexp.MustCompile(`&[#]*?[0-9[:alpha:]]*$`) +var ( + unfinishedtagRegex = regexp.MustCompile(`<[^>]*$`) + trailingSpanRegex = regexp.MustCompile(`]?$`) + entityRegex = regexp.MustCompile(`&[#]*?[0-9[:alpha:]]*$`) +) // shouldWriteInline represents combinations where we manually write inline changes func shouldWriteInline(diff diffmatchpatch.Diff, lineType DiffLineType) bool { @@ -199,7 +201,6 @@ func shouldWriteInline(diff diffmatchpatch.Diff, lineType DiffLineType) bool { } func fixupBrokenSpans(diffs []diffmatchpatch.Diff) []diffmatchpatch.Diff { - // Create a new array to store our fixed up blocks fixedup := make([]diffmatchpatch.Diff, 0, len(diffs)) @@ -624,10 +625,10 @@ func (diffFile *DiffFile) GetTailSection(gitRepo *git.Repository, leftCommitID, LastRightIdx: lastLine.RightIdx, LeftIdx: leftLineCount, RightIdx: rightLineCount, - }} + }, + } tailSection := &DiffSection{FileName: diffFile.Name, Lines: []*DiffLine{tailDiffLine}} return tailSection - } func getCommitFileLineCount(commit *git.Commit, filePath string) int { @@ -1301,7 +1302,8 @@ func GetWhitespaceFlag(whiteSpaceBehavior string) string { "ignore-all": "-w", "ignore-change": "-b", "ignore-eol": "--ignore-space-at-eol", - "": ""} + "": "", + } return whitespaceFlags[whiteSpaceBehavior] } diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go index f8c25a3912d51..6612e3c3a9dfa 100644 --- a/services/gitdiff/gitdiff_test.go +++ b/services/gitdiff/gitdiff_test.go @@ -329,7 +329,7 @@ index 6961180..9ba1a00 100644 // Test max lines diffBuilder := &strings.Builder{} - var diff = `diff --git a/newfile2 b/newfile2 + diff := `diff --git a/newfile2 b/newfile2 new file mode 100644 index 0000000..6bb8f39 --- /dev/null @@ -419,7 +419,7 @@ index 0000000..6bb8f39 } println(result) - var diff2 = `diff --git "a/A \\ B" "b/A \\ B" + diff2 := `diff --git "a/A \\ B" "b/A \\ B" --- "a/A \\ B" +++ "b/A \\ B" @@ -1,3 +1,6 @@ @@ -436,7 +436,7 @@ index 0000000..6bb8f39 } println(result) - var diff2a = `diff --git "a/A \\ B" b/A/B + diff2a := `diff --git "a/A \\ B" b/A/B --- "a/A \\ B" +++ b/A/B @@ -1,3 +1,6 @@ @@ -453,7 +453,7 @@ index 0000000..6bb8f39 } println(result) - var diff3 = `diff --git a/README.md b/README.md + diff3 := `diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ @@ -490,6 +490,7 @@ func setupDefaultDiff() *Diff { }, } } + func TestDiff_LoadComments(t *testing.T) { assert.NoError(t, models.PrepareTestDatabase()) diff --git a/services/issue/assignee.go b/services/issue/assignee.go index f24a242f6b7d1..7fe5428e0ac84 100644 --- a/services/issue/assignee.go +++ b/services/issue/assignee.go @@ -54,7 +54,7 @@ func ToggleAssignee(issue *models.Issue, doer *models.User, assigneeID int64) (r } // ReviewRequest add or remove a review request from a user for this PR, and make comment for it. -func ReviewRequest(issue *models.Issue, doer *models.User, reviewer *models.User, isAdd bool) (comment *models.Comment, err error) { +func ReviewRequest(issue *models.Issue, doer, reviewer *models.User, isAdd bool) (comment *models.Comment, err error) { if isAdd { comment, err = models.AddReviewRequest(issue, reviewer, doer) } else { diff --git a/services/issue/issue.go b/services/issue/issue.go index 90f689a55cc3e..fd2e715c04e4d 100644 --- a/services/issue/issue.go +++ b/services/issue/issue.go @@ -159,8 +159,8 @@ func AddAssigneeIfNotAssigned(issue *models.Issue, doer *models.User, assigneeID // GetRefEndNamesAndURLs retrieves the ref end names (e.g. refs/heads/branch-name -> branch-name) // and their respective URLs. func GetRefEndNamesAndURLs(issues []*models.Issue, repoLink string) (map[int64]string, map[int64]string) { - var issueRefEndNames = make(map[int64]string, len(issues)) - var issueRefURLs = make(map[int64]string, len(issues)) + issueRefEndNames := make(map[int64]string, len(issues)) + issueRefURLs := make(map[int64]string, len(issues)) for _, issue := range issues { if issue.Ref != "" { issueRefEndNames[issue.ID] = git.RefEndName(issue.Ref) diff --git a/services/issue/label_test.go b/services/issue/label_test.go index 065202894320a..ffb13b2de2b16 100644 --- a/services/issue/label_test.go +++ b/services/issue/label_test.go @@ -12,7 +12,7 @@ import ( ) func TestIssue_AddLabels(t *testing.T) { - var tests = []struct { + tests := []struct { issueID int64 labelIDs []int64 doerID int64 @@ -38,7 +38,7 @@ func TestIssue_AddLabels(t *testing.T) { } func TestIssue_AddLabel(t *testing.T) { - var tests = []struct { + tests := []struct { issueID int64 labelID int64 doerID int64 diff --git a/services/mailer/mail.go b/services/mailer/mail.go index 7d6214c742a5c..8d0d8fd9c7c51 100644 --- a/services/mailer/mail.go +++ b/services/mailer/mail.go @@ -167,7 +167,6 @@ func SendCollaboratorMail(u, doer *models.User, repo *models.Repository) { } func composeIssueCommentMessages(ctx *mailCommentContext, tos []string, fromMention bool, info string) []*Message { - var ( subject string link string diff --git a/services/mailer/mail_issue.go b/services/mailer/mail_issue.go index b600060a67f5e..f8665ce3eed54 100644 --- a/services/mailer/mail_issue.go +++ b/services/mailer/mail_issue.go @@ -28,7 +28,6 @@ type mailCommentContext struct { // 1. Repository watchers and users who are participated in comments. // 2. Users who are not in 1. but get mentioned in current issue/comment. func mailIssueCommentToParticipants(ctx *mailCommentContext, mentions []int64) error { - // Required by the mail composer; make sure to load these before calling the async function if err := ctx.Issue.LoadRepo(); err != nil { return fmt.Errorf("LoadRepo(): %v", err) diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go index d7d02d9dee822..a068984521ad3 100644 --- a/services/mailer/mail_test.go +++ b/services/mailer/mail_test.go @@ -41,7 +41,7 @@ const bodyTpl = ` func TestComposeIssueCommentMessage(t *testing.T) { assert.NoError(t, models.PrepareTestDatabase()) - var mailService = setting.Mailer{ + mailService := setting.Mailer{ From: "test@gitea.com", } @@ -58,8 +58,10 @@ func TestComposeIssueCommentMessage(t *testing.T) { InitMailRender(stpl, btpl) tos := []string{"test@gitea.com", "test2@gitea.com"} - msgs := composeIssueCommentMessages(&mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, - Content: "test body", Comment: comment}, tos, false, "issue comment") + msgs := composeIssueCommentMessages(&mailCommentContext{ + Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, + Content: "test body", Comment: comment, + }, tos, false, "issue comment") assert.Len(t, msgs, 2) gomailMsg := msgs[0].ToMessage() mailto := gomailMsg.GetHeader("To") @@ -76,7 +78,7 @@ func TestComposeIssueCommentMessage(t *testing.T) { func TestComposeIssueMessage(t *testing.T) { assert.NoError(t, models.PrepareTestDatabase()) - var mailService = setting.Mailer{ + mailService := setting.Mailer{ From: "test@gitea.com", } @@ -92,8 +94,10 @@ func TestComposeIssueMessage(t *testing.T) { InitMailRender(stpl, btpl) tos := []string{"test@gitea.com", "test2@gitea.com"} - msgs := composeIssueCommentMessages(&mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, - Content: "test body"}, tos, false, "issue create") + msgs := composeIssueCommentMessages(&mailCommentContext{ + Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, + Content: "test body", + }, tos, false, "issue create") assert.Len(t, msgs, 2) gomailMsg := msgs[0].ToMessage() @@ -110,7 +114,7 @@ func TestComposeIssueMessage(t *testing.T) { func TestTemplateSelection(t *testing.T) { assert.NoError(t, models.PrepareTestDatabase()) - var mailService = setting.Mailer{ + mailService := setting.Mailer{ From: "test@gitea.com", } @@ -143,29 +147,37 @@ func TestTemplateSelection(t *testing.T) { assert.Contains(t, wholemsg, expBody) } - msg := testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, - Content: "test body"}, tos, false, "TestTemplateSelection") + msg := testComposeIssueCommentMessage(t, &mailCommentContext{ + Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, + Content: "test body", + }, tos, false, "TestTemplateSelection") expect(t, msg, "issue/new/subject", "issue/new/body") comment := models.AssertExistsAndLoadBean(t, &models.Comment{ID: 2, Issue: issue}).(*models.Comment) - msg = testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, - Content: "test body", Comment: comment}, tos, false, "TestTemplateSelection") + msg = testComposeIssueCommentMessage(t, &mailCommentContext{ + Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, + Content: "test body", Comment: comment, + }, tos, false, "TestTemplateSelection") expect(t, msg, "issue/default/subject", "issue/default/body") pull := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 2, Repo: repo, Poster: doer}).(*models.Issue) comment = models.AssertExistsAndLoadBean(t, &models.Comment{ID: 4, Issue: pull}).(*models.Comment) - msg = testComposeIssueCommentMessage(t, &mailCommentContext{Issue: pull, Doer: doer, ActionType: models.ActionCommentPull, - Content: "test body", Comment: comment}, tos, false, "TestTemplateSelection") + msg = testComposeIssueCommentMessage(t, &mailCommentContext{ + Issue: pull, Doer: doer, ActionType: models.ActionCommentPull, + Content: "test body", Comment: comment, + }, tos, false, "TestTemplateSelection") expect(t, msg, "pull/comment/subject", "pull/comment/body") - msg = testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCloseIssue, - Content: "test body", Comment: comment}, tos, false, "TestTemplateSelection") + msg = testComposeIssueCommentMessage(t, &mailCommentContext{ + Issue: issue, Doer: doer, ActionType: models.ActionCloseIssue, + Content: "test body", Comment: comment, + }, tos, false, "TestTemplateSelection") expect(t, msg, "Re: [user2/repo1] issue1 (#1)", "issue/close/body") } func TestTemplateServices(t *testing.T) { assert.NoError(t, models.PrepareTestDatabase()) - var mailService = setting.Mailer{ + mailService := setting.Mailer{ From: "test@gitea.com", } @@ -180,14 +192,15 @@ func TestTemplateServices(t *testing.T) { expect := func(t *testing.T, issue *models.Issue, comment *models.Comment, doer *models.User, actionType models.ActionType, fromMention bool, tplSubject, tplBody, expSubject, expBody string) { - stpl := texttmpl.Must(texttmpl.New("issue/default").Parse(tplSubject)) btpl := template.Must(template.New("issue/default").Parse(tplBody)) InitMailRender(stpl, btpl) tos := []string{"test@gitea.com"} - msg := testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: actionType, - Content: "test body", Comment: comment}, tos, fromMention, "TestTemplateServices") + msg := testComposeIssueCommentMessage(t, &mailCommentContext{ + Issue: issue, Doer: doer, ActionType: actionType, + Content: "test body", Comment: comment, + }, tos, fromMention, "TestTemplateServices") subject := msg.ToMessage().GetHeader("Subject") msgbuf := new(bytes.Buffer) diff --git a/services/mailer/mailer.go b/services/mailer/mailer.go index 2e7beffa151ab..7c1ff439bec81 100644 --- a/services/mailer/mailer.go +++ b/services/mailer/mailer.go @@ -126,8 +126,7 @@ func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) { } // Sender SMTP mail sender -type smtpSender struct { -} +type smtpSender struct{} // Send send email func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error { @@ -233,8 +232,7 @@ func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error { } // Sender sendmail mail sender -type sendmailSender struct { -} +type sendmailSender struct{} // Send send email func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error { @@ -255,7 +253,6 @@ func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error { cmd := exec.CommandContext(ctx, setting.MailService.SendmailPath, args...) pipe, err := cmd.StdinPipe() - if err != nil { return err } @@ -283,8 +280,7 @@ func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error { } // Sender sendmail mail sender -type dummySender struct { -} +type dummySender struct{} // Send send email func (s *dummySender) Send(from string, to []string, msg io.WriterTo) error { diff --git a/services/pull/commit_status.go b/services/pull/commit_status.go index b8fb109440be4..f28e2e623a331 100644 --- a/services/pull/commit_status.go +++ b/services/pull/commit_status.go @@ -23,7 +23,7 @@ func MergeRequiredContextsCommitStatus(commitStatuses []*models.CommitStatus, re return structs.CommitStatusSuccess } - var returnedStatus = structs.CommitStatusSuccess + returnedStatus := structs.CommitStatusSuccess for _, ctx := range requiredContexts { var targetStatus structs.CommitStatusState for _, commitStatus := range commitStatuses { diff --git a/services/pull/merge.go b/services/pull/merge.go index bbe631f68c997..dfe259e7021d4 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -143,13 +143,13 @@ func rawMerge(pr *models.PullRequest, doer *models.User, mergeStyle models.Merge } infoPath := filepath.Join(tmpBasePath, ".git", "info") - if err := os.MkdirAll(infoPath, 0700); err != nil { + if err := os.MkdirAll(infoPath, 0o700); err != nil { log.Error("Unable to create .git/info in %s: %v", tmpBasePath, err) return "", fmt.Errorf("Unable to create .git/info in tmpBasePath: %v", err) } sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout") - if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil { + if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0o600); err != nil { log.Error("Unable to write .git/info/sparse-checkout file in %s: %v", tmpBasePath, err) return "", fmt.Errorf("Unable to write .git/info/sparse-checkout file in tmpBasePath: %v", err) } diff --git a/services/pull/review.go b/services/pull/review.go index 4b647722fcb2b..9598d975addfa 100644 --- a/services/pull/review.go +++ b/services/pull/review.go @@ -19,8 +19,7 @@ import ( ) // CreateCodeComment creates a comment on the code line -func CreateCodeComment(doer *models.User, gitRepo *git.Repository, issue *models.Issue, line int64, content string, treePath string, isReview bool, replyReviewID int64, latestCommitID string) (*models.Comment, error) { - +func CreateCodeComment(doer *models.User, gitRepo *git.Repository, issue *models.Issue, line int64, content, treePath string, isReview bool, replyReviewID int64, latestCommitID string) (*models.Comment, error) { var ( existsReview bool err error diff --git a/services/pull/temp_repo.go b/services/pull/temp_repo.go index 45cd10b65bbe4..dddd8b608d1f5 100644 --- a/services/pull/temp_repo.go +++ b/services/pull/temp_repo.go @@ -67,7 +67,7 @@ func createTemporaryRepo(pr *models.PullRequest) (string, error) { // Add head repo remote. addCacheRepo := func(staging, cache string) error { p := filepath.Join(staging, ".git", "objects", "info", "alternates") - f, err := os.OpenFile(p, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) + f, err := os.OpenFile(p, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err != nil { log.Error("Could not create .git/objects/info/alternates file in %s: %v", staging, err) return err diff --git a/services/pull/update.go b/services/pull/update.go index f4f7859a49ec1..edae1dceac5ba 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -14,7 +14,7 @@ import ( // Update updates pull request with base branch. func Update(pull *models.PullRequest, doer *models.User, message string) error { - //use merge functions but switch repo's and branch's + // use merge functions but switch repo's and branch's pr := &models.PullRequest{ HeadRepoID: pull.BaseRepoID, BaseRepoID: pull.HeadRepoID, diff --git a/services/repository/push.go b/services/repository/push.go index bed5c575fe81d..4f9fdcbeebe92 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -95,7 +95,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { if opts.IsNewRef() && opts.IsDelRef() { return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA) } - var commits = &repo_module.PushCommits{} + commits := &repo_module.PushCommits{} if opts.IsTag() { // If is tag reference if pusher == nil || pusher.ID != opts.PusherID { var err error diff --git a/services/webhook/deliver.go b/services/webhook/deliver.go index 8ac7d8c192467..1ea8de139d6a0 100644 --- a/services/webhook/deliver.go +++ b/services/webhook/deliver.go @@ -53,13 +53,12 @@ func Deliver(t *models.HookTask) error { req.Header.Set("Content-Type", "application/json") case models.ContentTypeForm: - var forms = url.Values{ + forms := url.Values{ "payload": []string{t.PayloadContent}, } req, err = http.NewRequest("POST", t.URL, strings.NewReader(forms.Encode())) if err != nil { - return err } @@ -228,7 +227,6 @@ func DeliverHooks(ctx context.Context) { } } } - } var ( diff --git a/services/webhook/deliver_test.go b/services/webhook/deliver_test.go index cfc99d796a536..83ff98b4fe19f 100644 --- a/services/webhook/deliver_test.go +++ b/services/webhook/deliver_test.go @@ -18,7 +18,7 @@ func TestWebhookProxy(t *testing.T) { setting.Webhook.ProxyURLFixed, _ = url.Parse(setting.Webhook.ProxyURL) setting.Webhook.ProxyHosts = []string{"*.discordapp.com", "discordapp.com"} - var kases = map[string]string{ + kases := map[string]string{ "https://discordapp.com/api/webhooks/xxxxxxxxx/xxxxxxxxxxxxxxxxxxx": "http://localhost:8080", "http://s.discordapp.com/assets/xxxxxx": "http://localhost:8080", "http://github.com/a/b": "", diff --git a/services/webhook/dingtalk.go b/services/webhook/dingtalk.go index 0401464a448a6..7cecb09d3f475 100644 --- a/services/webhook/dingtalk.go +++ b/services/webhook/dingtalk.go @@ -21,9 +21,7 @@ type ( DingtalkPayload dingtalk.Payload ) -var ( - _ PayloadConvertor = &DingtalkPayload{} -) +var _ PayloadConvertor = &DingtalkPayload{} // SetSecret sets the dingtalk secret func (d *DingtalkPayload) SetSecret(_ string) {} @@ -148,7 +146,7 @@ func (d *DingtalkPayload) Issue(p *api.IssuePayload) (api.Payloader, error) { MsgType: "actionCard", ActionCard: dingtalk.ActionCard{ Text: text + "\r\n\r\n" + attachmentText, - //Markdown: "# " + title + "\n" + text, + // Markdown: "# " + title + "\n" + text, Title: issueTitle, HideAvatar: "0", SingleTitle: "view issue", @@ -181,7 +179,7 @@ func (d *DingtalkPayload) PullRequest(p *api.PullRequestPayload) (api.Payloader, MsgType: "actionCard", ActionCard: dingtalk.ActionCard{ Text: text + "\r\n\r\n" + attachmentText, - //Markdown: "# " + title + "\n" + text, + // Markdown: "# " + title + "\n" + text, Title: issueTitle, HideAvatar: "0", SingleTitle: "view pull request", @@ -202,7 +200,6 @@ func (d *DingtalkPayload) Review(p *api.PullRequestPayload, event models.HookEve title = fmt.Sprintf("[%s] Pull request review %s : #%d %s", p.Repository.FullName, action, p.Index, p.PullRequest.Title) text = p.Review.Content - } return &DingtalkPayload{ diff --git a/services/webhook/discord.go b/services/webhook/discord.go index d28904715f618..4790c8ef413e0 100644 --- a/services/webhook/discord.go +++ b/services/webhook/discord.go @@ -110,9 +110,7 @@ func (d *DiscordPayload) JSONPayload() ([]byte, error) { return data, nil } -var ( - _ PayloadConvertor = &DiscordPayload{} -) +var _ PayloadConvertor = &DiscordPayload{} // Create implements PayloadConvertor Create method func (d *DiscordPayload) Create(p *api.CreatePayload) (api.Payloader, error) { diff --git a/services/webhook/feishu.go b/services/webhook/feishu.go index 847a991f366c3..da4000a49c8eb 100644 --- a/services/webhook/feishu.go +++ b/services/webhook/feishu.go @@ -48,9 +48,7 @@ func (f *FeishuPayload) JSONPayload() ([]byte, error) { return data, nil } -var ( - _ PayloadConvertor = &FeishuPayload{} -) +var _ PayloadConvertor = &FeishuPayload{} // Create implements PayloadConvertor Create method func (f *FeishuPayload) Create(p *api.CreatePayload) (api.Payloader, error) { @@ -84,7 +82,7 @@ func (f *FeishuPayload) Push(p *api.PushPayload) (api.Payloader, error) { commitDesc string ) - var text = fmt.Sprintf("[%s:%s] %s\n", p.Repo.FullName, branchName, commitDesc) + text := fmt.Sprintf("[%s:%s] %s\n", p.Repo.FullName, branchName, commitDesc) // for each commit, generate attachment text for i, commit := range p.Commits { var authorName string @@ -135,7 +133,6 @@ func (f *FeishuPayload) Review(p *api.PullRequestPayload, event models.HookEvent title = fmt.Sprintf("[%s] Pull request review %s : #%d %s", p.Repository.FullName, action, p.Index, p.PullRequest.Title) text = p.Review.Content - } return newFeishuTextPayload(title + "\r\n\r\n" + text), nil diff --git a/services/webhook/general.go b/services/webhook/general.go index ec247a24109be..373d44f9fffb3 100644 --- a/services/webhook/general.go +++ b/services/webhook/general.go @@ -16,12 +16,12 @@ import ( type linkFormatter = func(string, string) string // noneLinkFormatter does not create a link but just returns the text -func noneLinkFormatter(url string, text string) string { +func noneLinkFormatter(url, text string) string { return text } // htmlLinkFormatter creates a HTML link -func htmlLinkFormatter(url string, text string) string { +func htmlLinkFormatter(url, text string) string { return fmt.Sprintf(`%s`, url, html.EscapeString(text)) } diff --git a/services/webhook/matrix.go b/services/webhook/matrix.go index 1658dd4b44e97..c235cf8cf13db 100644 --- a/services/webhook/matrix.go +++ b/services/webhook/matrix.go @@ -52,9 +52,7 @@ type MatrixPayloadUnsafe struct { AccessToken string `json:"access_token"` } -var ( - _ PayloadConvertor = &MatrixPayloadUnsafe{} -) +var _ PayloadConvertor = &MatrixPayloadUnsafe{} // safePayload "converts" a unsafe payload to a safe payload func (m *MatrixPayloadUnsafe) safePayload() *MatrixPayloadSafe { @@ -90,7 +88,7 @@ func (m *MatrixPayloadUnsafe) JSONPayload() ([]byte, error) { } // MatrixLinkFormatter creates a link compatible with Matrix -func MatrixLinkFormatter(url string, text string) string { +func MatrixLinkFormatter(url, text string) string { return fmt.Sprintf(`%s`, html.EscapeString(url), html.EscapeString(text)) } diff --git a/services/webhook/msteams.go b/services/webhook/msteams.go index dc83a47c8d801..714ebe64d2dba 100644 --- a/services/webhook/msteams.go +++ b/services/webhook/msteams.go @@ -68,9 +68,7 @@ func (m *MSTeamsPayload) JSONPayload() ([]byte, error) { return data, nil } -var ( - _ PayloadConvertor = &MSTeamsPayload{} -) +var _ PayloadConvertor = &MSTeamsPayload{} // Create implements PayloadConvertor Create method func (m *MSTeamsPayload) Create(p *api.CreatePayload) (api.Payloader, error) { diff --git a/services/webhook/slack.go b/services/webhook/slack.go index f5c857f2a9614..5bfde6d93b3a4 100644 --- a/services/webhook/slack.go +++ b/services/webhook/slack.go @@ -90,7 +90,7 @@ func SlackShortTextFormatter(s string) string { } // SlackLinkFormatter creates a link compatible with slack -func SlackLinkFormatter(url string, text string) string { +func SlackLinkFormatter(url, text string) string { return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text)) } @@ -101,9 +101,7 @@ func SlackLinkToRef(repoURL, ref string) string { return SlackLinkFormatter(url, refName) } -var ( - _ PayloadConvertor = &SlackPayload{} -) +var _ PayloadConvertor = &SlackPayload{} // Create implements PayloadConvertor Create method func (s *SlackPayload) Create(p *api.CreatePayload) (api.Payloader, error) { diff --git a/services/webhook/telegram.go b/services/webhook/telegram.go index 5b78b46f8ec02..bc42aee3aa754 100644 --- a/services/webhook/telegram.go +++ b/services/webhook/telegram.go @@ -41,9 +41,7 @@ func GetTelegramHook(w *models.Webhook) *TelegramMeta { return s } -var ( - _ PayloadConvertor = &TelegramPayload{} -) +var _ PayloadConvertor = &TelegramPayload{} // SetSecret sets the telegram secret func (t *TelegramPayload) SetSecret(_ string) {} @@ -173,7 +171,6 @@ func (t *TelegramPayload) Review(p *api.PullRequestPayload, event models.HookEve text = fmt.Sprintf("[%s] Pull request review %s: #%d %s", p.Repository.FullName, action, p.Index, p.PullRequest.Title) attachmentText = p.Review.Content - } return &TelegramPayload{ diff --git a/services/webhook/webhook.go b/services/webhook/webhook.go index cc79ec15d1d7a..087823d020d99 100644 --- a/services/webhook/webhook.go +++ b/services/webhook/webhook.go @@ -25,38 +25,36 @@ type webhook struct { payloadCreator func(p api.Payloader, event models.HookEventType, meta string) (api.Payloader, error) } -var ( - webhooks = map[models.HookTaskType]*webhook{ - models.SLACK: { - name: models.SLACK, - payloadCreator: GetSlackPayload, - }, - models.DISCORD: { - name: models.DISCORD, - payloadCreator: GetDiscordPayload, - }, - models.DINGTALK: { - name: models.DINGTALK, - payloadCreator: GetDingtalkPayload, - }, - models.TELEGRAM: { - name: models.TELEGRAM, - payloadCreator: GetTelegramPayload, - }, - models.MSTEAMS: { - name: models.MSTEAMS, - payloadCreator: GetMSTeamsPayload, - }, - models.FEISHU: { - name: models.FEISHU, - payloadCreator: GetFeishuPayload, - }, - models.MATRIX: { - name: models.MATRIX, - payloadCreator: GetMatrixPayload, - }, - } -) +var webhooks = map[models.HookTaskType]*webhook{ + models.SLACK: { + name: models.SLACK, + payloadCreator: GetSlackPayload, + }, + models.DISCORD: { + name: models.DISCORD, + payloadCreator: GetDiscordPayload, + }, + models.DINGTALK: { + name: models.DINGTALK, + payloadCreator: GetDingtalkPayload, + }, + models.TELEGRAM: { + name: models.TELEGRAM, + payloadCreator: GetTelegramPayload, + }, + models.MSTEAMS: { + name: models.MSTEAMS, + payloadCreator: GetMSTeamsPayload, + }, + models.FEISHU: { + name: models.FEISHU, + payloadCreator: GetFeishuPayload, + }, + models.MATRIX: { + name: models.MATRIX, + payloadCreator: GetMatrixPayload, + }, +} // RegisterWebhook registers a webhook func RegisterWebhook(name string, webhook *webhook) { diff --git a/tools/fuzz.go b/tools/fuzz.go index 6ed1b40003d8c..7325d185079c8 100644 --- a/tools/fuzz.go +++ b/tools/fuzz.go @@ -24,7 +24,7 @@ func FuzzMarkdownRenderRaw(data []byte) int { } func FuzzMarkupPostProcess(data []byte) int { - var localMetas = map[string]string{ + localMetas := map[string]string{ "user": "go-gitea", "repo": "gitea", } From 460f7d13b6bf12ffe4a23af16f3b52e55cfe489d Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Sat, 20 Mar 2021 10:59:10 +0800 Subject: [PATCH 2/2] fix: make lint-backend error --- services/repository/push.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/repository/push.go b/services/repository/push.go index 4f9fdcbeebe92..922d1802d27e2 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -95,7 +95,6 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { if opts.IsNewRef() && opts.IsDelRef() { return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA) } - commits := &repo_module.PushCommits{} if opts.IsTag() { // If is tag reference if pusher == nil || pusher.ID != opts.PusherID { var err error @@ -192,7 +191,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { } } - commits = repo_module.ListToPushCommits(l) + commits := repo_module.ListToPushCommits(l) if len(commits.Commits) > setting.UI.FeedMaxCommitNum { commits.Commits = commits.Commits[:setting.UI.FeedMaxCommitNum] }