summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.golangci.yml4
-rw-r--r--Makefile6
-rw-r--r--build/code-batch-process.go2
-rw-r--r--build/codeformat/formatimports.go16
-rw-r--r--build/generate-bindata.go5
-rw-r--r--build/generate-emoji.go12
-rw-r--r--build/generate-gitignores.go5
-rw-r--r--build/generate-licenses.go3
-rw-r--r--build/gocovmerge.go2
-rw-r--r--cmd/admin.go10
-rw-r--r--cmd/admin_auth_ldap_test.go17
-rw-r--r--cmd/cert.go2
-rw-r--r--cmd/doctor.go1
-rw-r--r--cmd/dump.go2
-rw-r--r--cmd/dump_repo.go2
-rw-r--r--cmd/embedded.go13
-rw-r--r--cmd/manager.go3
-rw-r--r--cmd/serv.go2
-rw-r--r--cmd/web.go3
-rw-r--r--cmd/web_letsencrypt.go3
-rw-r--r--contrib/fixtures/fixture_generation.go2
-rw-r--r--contrib/pr/checkout.go35
-rw-r--r--integrations/api_admin_org_test.go6
-rw-r--r--integrations/api_branch_test.go1
-rw-r--r--integrations/api_comment_test.go6
-rw-r--r--integrations/api_gpg_keys_test.go30
-rw-r--r--integrations/api_issue_label_test.go18
-rw-r--r--integrations/api_issue_reaction_test.go20
-rw-r--r--integrations/api_issue_subscription_test.go1
-rw-r--r--integrations/api_issue_test.go2
-rw-r--r--integrations/api_issue_tracked_time_test.go10
-rw-r--r--integrations/api_notification_test.go6
-rw-r--r--integrations/api_org_test.go8
-rw-r--r--integrations/api_private_serv_test.go2
-rw-r--r--integrations/api_pull_review_test.go56
-rw-r--r--integrations/api_repo_edit_test.go6
-rw-r--r--integrations/api_repo_git_commits_test.go1
-rw-r--r--integrations/api_repo_lfs_locks_test.go14
-rw-r--r--integrations/api_repo_test.go113
-rw-r--r--integrations/api_repo_topic_test.go1
-rw-r--r--integrations/api_user_heatmap_test.go2
-rw-r--r--integrations/api_user_orgs_test.go2
-rw-r--r--integrations/attachment_test.go8
-rw-r--r--integrations/benchmarks_test.go2
-rw-r--r--integrations/cmd_keys_test.go7
-rw-r--r--integrations/dump_restore_test.go6
-rw-r--r--integrations/editor_test.go1
-rw-r--r--integrations/eventsource_test.go2
-rw-r--r--integrations/git_helper_for_declarative_test.go11
-rw-r--r--integrations/git_smart_http_test.go2
-rw-r--r--integrations/git_test.go23
-rw-r--r--integrations/gpg_git_test.go4
-rw-r--r--integrations/integration_test.go18
-rw-r--r--integrations/issue_test.go20
-rw-r--r--integrations/lfs_local_endpoint_test.go4
-rw-r--r--integrations/links_test.go10
-rw-r--r--integrations/migration-test/migration_test.go9
-rw-r--r--integrations/nonascii_branches_test.go1
-rw-r--r--integrations/privateactivity_test.go6
-rw-r--r--integrations/pull_merge_test.go8
-rw-r--r--integrations/pull_update_test.go18
-rw-r--r--integrations/repo_activity_test.go1
-rw-r--r--integrations/repo_commits_test.go4
-rw-r--r--integrations/repofiles_update_test.go2
-rw-r--r--integrations/setting_test.go1
-rw-r--r--integrations/ssh_key_test.go4
-rw-r--r--integrations/testlogger.go2
-rw-r--r--integrations/timetracking_test.go5
-rw-r--r--integrations/user_avatar_test.go2
-rw-r--r--integrations/user_test.go10
-rw-r--r--main.go2
-rw-r--r--models/auth/webauthn.go14
-rw-r--r--models/avatars/avatar.go4
-rw-r--r--models/consistency.go1
-rwxr-xr-xmodels/db/engine.go2
-rw-r--r--models/issue_test.go1
-rw-r--r--models/issues/content_history.go1
-rw-r--r--models/lfs.go2
-rw-r--r--models/migrate_test.go6
-rw-r--r--models/migrations/migrations_test.go8
-rw-r--r--models/migrations/testlogger_test.go2
-rw-r--r--models/migrations/v176_test.go1
-rw-r--r--models/migrations/v177_test.go1
-rw-r--r--models/migrations/v181_test.go2
-rw-r--r--models/migrations/v182_test.go4
-rw-r--r--models/migrations/v189_test.go2
-rw-r--r--models/migrations/v191.go1
-rw-r--r--models/migrations/v195_test.go4
-rw-r--r--models/migrations/v207.go1
-rw-r--r--models/migrations/v208.go1
-rw-r--r--models/repo.go8
-rw-r--r--models/repo/archiver.go4
-rw-r--r--models/repo/attachment.go2
-rw-r--r--models/repo/mirror.go6
-rw-r--r--models/repo/pushmirror.go6
-rw-r--r--models/review_test.go1
-rw-r--r--models/unittest/testdb.go16
-rw-r--r--models/user/email_address.go6
-rw-r--r--modules/activitypub/keypair_test.go1
-rw-r--r--modules/appstate/db.go3
-rw-r--r--modules/auth/openid/discovery_cache_test.go4
-rw-r--r--modules/auth/openid/openid.go6
-rw-r--r--modules/auth/pam/pam.go1
-rw-r--r--modules/auth/webauthn/webauthn.go14
-rw-r--r--modules/avatar/avatar_test.go1
-rw-r--r--modules/base/tool.go2
-rw-r--r--modules/cache/cache.go4
-rw-r--r--modules/cache/cache_test.go1
-rw-r--r--modules/charset/charset.go2
-rw-r--r--modules/charset/charset_test.go96
-rw-r--r--modules/context/api.go21
-rw-r--r--modules/context/api_test.go2
-rw-r--r--modules/context/captcha.go6
-rw-r--r--modules/context/context.go14
-rw-r--r--modules/context/csrf.go4
-rw-r--r--modules/context/private.go4
-rw-r--r--modules/context/repo.go1
-rw-r--r--modules/context/response.go4
-rw-r--r--modules/convert/notification.go6
-rw-r--r--modules/convert/pull_test.go4
-rw-r--r--modules/convert/repository.go2
-rw-r--r--modules/convert/status.go1
-rw-r--r--modules/csv/csv.go8
-rw-r--r--modules/csv/csv_test.go12
-rw-r--r--modules/doctor/fix16961.go1
-rw-r--r--modules/doctor/misc.go1
-rw-r--r--modules/doctor/paths.go2
-rw-r--r--modules/emoji/emoji.go3
-rw-r--r--modules/git/command_test.go2
-rw-r--r--modules/git/commit.go2
-rw-r--r--modules/git/commit_info_gogit.go2
-rw-r--r--modules/git/commit_info_nogogit.go2
-rw-r--r--modules/git/commit_info_test.go6
-rw-r--r--modules/git/commit_test.go1
-rw-r--r--modules/git/git.go4
-rw-r--r--modules/git/hook.go8
-rw-r--r--modules/git/last_commit_cache_gogit.go1
-rw-r--r--modules/git/lfs.go4
-rw-r--r--modules/git/parse_nogogit_test.go1
-rw-r--r--modules/git/repo.go4
-rw-r--r--modules/git/repo_attribute.go2
-rw-r--r--modules/git/repo_attribute_test.go4
-rw-r--r--modules/git/repo_commit.go1
-rw-r--r--modules/git/repo_commit_test.go6
-rw-r--r--modules/git/repo_language_stats.go6
-rw-r--r--modules/git/repo_object.go1
-rw-r--r--modules/git/repo_tag.go2
-rw-r--r--modules/git/submodule_test.go2
-rw-r--r--modules/git/tag.go6
-rw-r--r--modules/git/tree_blob_gogit.go2
-rw-r--r--modules/git/tree_entry_mode.go10
-rw-r--r--modules/gitgraph/graph_test.go2
-rw-r--r--modules/gitgraph/parser.go1
-rw-r--r--modules/graceful/manager.go1
-rw-r--r--modules/highlight/highlight.go6
-rw-r--r--modules/httpcache/httpcache_test.go3
-rw-r--r--modules/indexer/code/bleve.go12
-rw-r--r--modules/indexer/code/elastic_search.go10
-rw-r--r--modules/indexer/code/git.go2
-rw-r--r--modules/indexer/code/indexer.go4
-rw-r--r--modules/indexer/code/indexer_test.go78
-rw-r--r--modules/indexer/code/wrapped.go5
-rw-r--r--modules/indexer/issues/bleve.go6
-rw-r--r--modules/indexer/issues/bleve_test.go62
-rw-r--r--modules/indexer/issues/db.go5
-rw-r--r--modules/indexer/issues/elastic_search.go8
-rw-r--r--modules/indexer/issues/indexer_test.go1
-rw-r--r--modules/indexer/stats/db.go3
-rw-r--r--modules/lfs/endpoint_test.go2
-rw-r--r--modules/lfs/http_client_test.go7
-rw-r--r--modules/lfs/pointer_scanner_gogit.go1
-rw-r--r--modules/log/colors.go11
-rw-r--r--modules/log/conn_test.go3
-rw-r--r--modules/log/file.go7
-rw-r--r--modules/log/file_test.go15
-rw-r--r--modules/log/log_test.go1
-rw-r--r--modules/log/logger.go1
-rw-r--r--modules/log/stack.go4
-rw-r--r--modules/log/writer.go2
-rw-r--r--modules/markup/common/footnote.go11
-rw-r--r--modules/markup/common/html.go14
-rw-r--r--modules/markup/common/linkify.go18
-rw-r--r--modules/markup/csv/csv.go5
-rw-r--r--modules/markup/csv/csv_test.go2
-rw-r--r--modules/markup/html.go10
-rw-r--r--modules/markup/html_internal_test.go8
-rw-r--r--modules/markup/html_test.go32
-rw-r--r--modules/markup/markdown/goldmark.go2
-rw-r--r--modules/markup/markdown/markdown.go21
-rw-r--r--modules/markup/markdown/markdown_test.go9
-rw-r--r--modules/markup/mdstripper/mdstripper.go6
-rw-r--r--modules/markup/mdstripper/mdstripper_test.go3
-rw-r--r--modules/markup/orgmode/orgmode.go3
-rw-r--r--modules/markup/orgmode/orgmode_test.go8
-rw-r--r--modules/markup/sanitizer.go3
-rw-r--r--modules/markup/sanitizer_test.go1
-rwxr-xr-xmodules/metrics/collector.go1
-rw-r--r--modules/migration/null_downloader.go7
-rw-r--r--modules/migration/retry_downloader.go4
-rw-r--r--modules/nosql/redis.go1
-rw-r--r--modules/notification/action/action.go6
-rw-r--r--modules/notification/base/notifier.go14
-rw-r--r--modules/notification/base/null.go9
-rw-r--r--modules/notification/indexer/indexer.go4
-rw-r--r--modules/notification/mail/mail.go4
-rw-r--r--modules/notification/notification.go6
-rw-r--r--modules/notification/ui/ui.go20
-rw-r--r--modules/notification/webhook/webhook.go7
-rw-r--r--modules/options/dynamic.go10
-rw-r--r--modules/options/static.go14
-rw-r--r--modules/private/mail.go2
-rw-r--r--modules/private/manager.go1
-rw-r--r--modules/private/restore_repo.go2
-rw-r--r--modules/private/serv.go1
-rw-r--r--modules/process/manager.go1
-rw-r--r--modules/process/manager_test.go2
-rw-r--r--modules/public/public.go4
-rw-r--r--modules/public/public_test.go2
-rw-r--r--modules/public/static.go2
-rw-r--r--modules/queue/manager.go6
-rw-r--r--modules/queue/queue.go5
-rw-r--r--modules/queue/queue_bytefifo.go8
-rw-r--r--modules/queue/queue_disk_channel.go1
-rw-r--r--modules/queue/queue_disk_channel_test.go1
-rw-r--r--modules/queue/queue_wrapped.go2
-rw-r--r--modules/queue/unique_queue_disk_channel.go1
-rw-r--r--modules/queue/workerpool.go2
-rw-r--r--modules/references/references.go1
-rw-r--r--modules/references/references_test.go1
-rw-r--r--modules/repository/generate.go4
-rw-r--r--modules/repository/hooks.go10
-rw-r--r--modules/repository/init.go6
-rw-r--r--modules/repository/repo.go4
-rw-r--r--modules/session/db.go1
-rw-r--r--modules/setting/attachment.go34
-rw-r--r--modules/setting/cache.go50
-rw-r--r--modules/setting/cors.go32
-rw-r--r--modules/setting/cron_test.go2
-rw-r--r--modules/setting/database.go2
-rw-r--r--modules/setting/git.go110
-rw-r--r--modules/setting/indexer.go60
-rw-r--r--modules/setting/indexer_test.go1
-rw-r--r--modules/setting/lfs.go2
-rw-r--r--modules/setting/log.go10
-rw-r--r--modules/setting/mailer.go6
-rw-r--r--modules/setting/markup.go2
-rw-r--r--modules/setting/migrations.go26
-rw-r--r--modules/setting/mime_type_map.go18
-rw-r--r--modules/setting/mirror.go30
-rw-r--r--modules/setting/proxy.go24
-rw-r--r--modules/setting/session.go52
-rw-r--r--modules/setting/setting.go11
-rw-r--r--modules/setting/webhook.go40
-rw-r--r--modules/ssh/ssh.go5
-rw-r--r--modules/ssh/ssh_graceful.go1
-rw-r--r--modules/storage/local.go4
-rw-r--r--modules/storage/minio.go4
-rw-r--r--modules/storage/storage.go6
-rw-r--r--modules/structs/hook.go6
-rw-r--r--modules/structs/repo.go24
-rw-r--r--modules/templates/base.go2
-rw-r--r--modules/templates/dynamic.go2
-rw-r--r--modules/templates/helper.go16
-rw-r--r--modules/templates/static.go6
-rw-r--r--modules/test/context_tests.go9
-rw-r--r--modules/timeutil/executable.go6
-rw-r--r--modules/timeutil/language.go12
-rw-r--r--modules/typesniffer/typesniffer.go6
-rw-r--r--modules/updatechecker/update_checker.go1
-rw-r--r--modules/util/paginate_test.go2
-rw-r--r--modules/util/path_test.go2
-rw-r--r--modules/util/sanitize.go6
-rw-r--r--modules/util/sanitize_test.go6
-rw-r--r--modules/util/shellquote.go8
-rw-r--r--modules/util/truncate.go6
-rw-r--r--modules/util/util_test.go1
-rw-r--r--modules/validation/binding.go11
-rw-r--r--modules/web/middleware/flash.go6
-rw-r--r--modules/web/middleware/locale.go2
-rw-r--r--modules/web/route.go34
-rw-r--r--modules/web/routing/context.go5
-rw-r--r--modules/web/routing/funcinfo.go8
-rw-r--r--modules/web/routing/logger_manager.go6
-rw-r--r--modules/web/wrap_convert.go2
-rw-r--r--routers/api/v1/admin/org.go2
-rw-r--r--routers/api/v1/admin/user.go2
-rw-r--r--routers/api/v1/api.go12
-rw-r--r--routers/api/v1/misc/markdown_test.go10
-rw-r--r--routers/api/v1/org/hook.go4
-rw-r--r--routers/api/v1/org/org.go4
-rw-r--r--routers/api/v1/repo/branch.go6
-rw-r--r--routers/api/v1/repo/fork.go2
-rw-r--r--routers/api/v1/repo/issue.go2
-rw-r--r--routers/api/v1/repo/issue_reaction.go4
-rw-r--r--routers/api/v1/repo/issue_subscription.go4
-rw-r--r--routers/api/v1/repo/issue_tracked_time.go4
-rw-r--r--routers/api/v1/repo/migrate.go4
-rw-r--r--routers/api/v1/repo/milestone.go2
-rw-r--r--routers/api/v1/repo/pull.go1
-rw-r--r--routers/api/v1/repo/release_attachment.go2
-rw-r--r--routers/api/v1/repo/repo.go6
-rw-r--r--routers/api/v1/repo/repo_test.go4
-rw-r--r--routers/api/v1/repo/status.go2
-rw-r--r--routers/api/v1/repo/wiki.go5
-rw-r--r--routers/api/v1/user/gpg_key.go10
-rw-r--r--routers/api/v1/user/watch.go1
-rw-r--r--routers/api/v1/utils/git.go4
-rw-r--r--routers/common/middleware.go2
-rw-r--r--routers/install/install.go8
-rw-r--r--routers/install/routes.go4
-rw-r--r--routers/private/internal.go6
-rw-r--r--routers/private/manager_unix.go1
-rw-r--r--routers/private/restore_repo.go2
-rw-r--r--routers/web/admin/admin.go2
-rw-r--r--routers/web/admin/admin_test.go2
-rw-r--r--routers/web/admin/emails.go5
-rw-r--r--routers/web/admin/users_test.go1
-rw-r--r--routers/web/auth/auth.go6
-rw-r--r--routers/web/auth/linkaccount.go4
-rw-r--r--routers/web/auth/oauth.go1
-rw-r--r--routers/web/auth/openid.go4
-rw-r--r--routers/web/auth/webauthn.go2
-rw-r--r--routers/web/base.go10
-rw-r--r--routers/web/explore/code.go4
-rw-r--r--routers/web/explore/user.go4
-rw-r--r--routers/web/org/home.go2
-rw-r--r--routers/web/org/members.go2
-rw-r--r--routers/web/org/setting.go3
-rw-r--r--routers/web/repo/attachment.go10
-rw-r--r--routers/web/repo/blame.go6
-rw-r--r--routers/web/repo/branch.go2
-rw-r--r--routers/web/repo/compare.go9
-rw-r--r--routers/web/repo/download.go2
-rw-r--r--routers/web/repo/editor_test.go2
-rw-r--r--routers/web/repo/http.go5
-rw-r--r--routers/web/repo/issue.go32
-rw-r--r--routers/web/repo/issue_content_history.go8
-rw-r--r--routers/web/repo/issue_lock.go1
-rw-r--r--routers/web/repo/issue_test.go4
-rw-r--r--routers/web/repo/lfs.go4
-rw-r--r--routers/web/repo/migrate.go2
-rw-r--r--routers/web/repo/projects.go1
-rw-r--r--routers/web/repo/pull.go23
-rw-r--r--routers/web/repo/release.go2
-rw-r--r--routers/web/repo/repo.go6
-rw-r--r--routers/web/repo/settings_test.go5
-rw-r--r--routers/web/repo/topic.go4
-rw-r--r--routers/web/repo/view.go7
-rw-r--r--routers/web/repo/wiki.go8
-rw-r--r--routers/web/repo/wiki_test.go6
-rw-r--r--routers/web/user/home.go18
-rw-r--r--routers/web/user/profile.go3
-rw-r--r--routers/web/user/setting/account_test.go6
-rw-r--r--routers/web/user/setting/keys.go1
-rw-r--r--routers/web/user/setting/profile.go1
-rw-r--r--routers/web/web.go9
-rw-r--r--services/auth/auth.go6
-rw-r--r--services/auth/auth_test.go1
-rw-r--r--services/auth/basic.go3
-rw-r--r--services/auth/oauth2.go3
-rw-r--r--services/auth/reverseproxy.go3
-rw-r--r--services/auth/session.go3
-rw-r--r--services/auth/source/ldap/source_sync.go1
-rw-r--r--services/auth/source/oauth2/jwtsigningkey.go2
-rw-r--r--services/auth/source/oauth2/providers.go6
-rw-r--r--services/auth/source/oauth2/providers_openid.go3
-rw-r--r--services/auth/source/oauth2/providers_simple.go1
-rw-r--r--services/auth/source/oauth2/source_callout.go2
-rw-r--r--services/auth/source/smtp/auth.go6
-rw-r--r--services/comments/comments.go2
-rw-r--r--services/cron/cron.go1
-rw-r--r--services/cron/tasks.go10
-rw-r--r--services/forms/repo_form_test.go2
-rw-r--r--services/gitdiff/csv.go10
-rw-r--r--services/gitdiff/csv_test.go11
-rw-r--r--services/gitdiff/gitdiff.go20
-rw-r--r--services/gitdiff/gitdiff_test.go9
-rw-r--r--services/issue/issue.go4
-rw-r--r--services/issue/label_test.go4
-rw-r--r--services/lfs/locks.go6
-rw-r--r--services/lfs/server.go2
-rw-r--r--services/mailer/mail_issue.go1
-rw-r--r--services/mailer/mail_test.go48
-rw-r--r--services/mailer/mailer.go10
-rw-r--r--services/migrations/codebase.go12
-rw-r--r--services/migrations/dump.go12
-rw-r--r--services/migrations/error.go6
-rw-r--r--services/migrations/git.go4
-rw-r--r--services/migrations/gitbucket.go3
-rw-r--r--services/migrations/gitea_downloader.go21
-rw-r--r--services/migrations/gitea_uploader.go42
-rw-r--r--services/migrations/github.go44
-rw-r--r--services/migrations/gitlab.go45
-rw-r--r--services/migrations/gogs.go21
-rw-r--r--services/migrations/migrate.go12
-rw-r--r--services/migrations/onedev.go9
-rw-r--r--services/migrations/restore.go18
-rw-r--r--services/mirror/mirror_pull.go4
-rw-r--r--services/pull/commit_status.go2
-rw-r--r--services/pull/merge.go4
-rw-r--r--services/pull/review.go1
-rw-r--r--services/pull/temp_repo.go2
-rw-r--r--services/pull/update.go2
-rw-r--r--services/release/release.go4
-rw-r--r--services/release/release_test.go2
-rw-r--r--services/repository/adopt.go3
-rw-r--r--services/repository/adopt_test.go2
-rw-r--r--services/repository/archiver/archiver.go2
-rw-r--r--services/repository/archiver/archiver_test.go2
-rw-r--r--services/repository/push.go2
-rw-r--r--services/task/task.go2
-rw-r--r--services/webhook/deliver.go3
-rw-r--r--services/webhook/deliver_test.go2
-rw-r--r--services/webhook/dingtalk.go5
-rw-r--r--services/webhook/discord.go4
-rw-r--r--services/webhook/feishu.go6
-rw-r--r--services/webhook/matrix.go4
-rw-r--r--services/webhook/msteams.go4
-rw-r--r--services/webhook/slack.go4
-rw-r--r--services/webhook/telegram.go4
-rw-r--r--services/webhook/webhook.go70
-rw-r--r--services/webhook/wechatwork.go11
-rw-r--r--tools/fuzz.go18
423 files changed, 1586 insertions, 1759 deletions
diff --git a/.golangci.yml b/.golangci.yml
index 235bb76715..9bba34a10c 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -17,6 +17,7 @@ linters:
- bidichk
- ineffassign
- revive
+ - gofumpt
enable-all: false
disable-all: true
fast: false
@@ -57,6 +58,9 @@ linters-settings:
- name: errorf
- name: duplicated-imports
- name: modifies-value-receiver
+ gofumpt:
+ extra-rules: true
+ lang-version: 1.16
issues:
exclude-rules:
diff --git a/Makefile b/Makefile
index 342366492c..d12f83d98b 100644
--- a/Makefile
+++ b/Makefile
@@ -231,8 +231,10 @@ clean:
.PHONY: fmt
fmt:
- @echo "Running gitea-fmt(with gofmt)..."
- @$(GO) run build/code-batch-process.go gitea-fmt -s -w '{file-list}'
+ @hash xgogofumpt > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
+ $(GO) install mvdan.cc/gofumpt@latest; \
+ fi
+ gofumpt -w -l -extra -lang 1.16 .
.PHONY: vet
vet:
diff --git a/build/code-batch-process.go b/build/code-batch-process.go
index 1fd236abd5..02f54b9c0a 100644
--- a/build/code-batch-process.go
+++ b/build/code-batch-process.go
@@ -136,7 +136,7 @@ func (fc *fileCollector) collectFiles() (res [][]string, err error) {
}
// substArgFiles expands the {file-list} to a real file list for commands
-func substArgFiles(args []string, files []string) []string {
+func substArgFiles(args, files []string) []string {
for i, s := range args {
if s == "{file-list}" {
newArgs := append(args[:i], files...)
diff --git a/build/codeformat/formatimports.go b/build/codeformat/formatimports.go
index c6427f6a99..fedc5cc090 100644
--- a/build/codeformat/formatimports.go
+++ b/build/codeformat/formatimports.go
@@ -20,8 +20,10 @@ var importPackageGroupOrders = map[string]int{
var errInvalidCommentBetweenImports = errors.New("comments between imported packages are invalid, please move comments to the end of the package line")
-var importBlockBegin = []byte("\nimport (\n")
-var importBlockEnd = []byte("\n)")
+var (
+ importBlockBegin = []byte("\nimport (\n")
+ importBlockEnd = []byte("\n)")
+)
type importLineParsed struct {
group string
@@ -59,8 +61,10 @@ func parseImportLine(line string) (*importLineParsed, error) {
return il, nil
}
-type importLineGroup []*importLineParsed
-type importLineGroupMap map[string]importLineGroup
+type (
+ importLineGroup []*importLineParsed
+ importLineGroupMap map[string]importLineGroup
+)
func formatGoImports(contentBytes []byte) ([]byte, error) {
p1 := bytes.Index(contentBytes, importBlockBegin)
@@ -153,7 +157,7 @@ func formatGoImports(contentBytes []byte) ([]byte, error) {
return formattedBytes, nil
}
-//FormatGoImports format the imports by our rules (see unit tests)
+// FormatGoImports format the imports by our rules (see unit tests)
func FormatGoImports(file string) error {
f, err := os.Open(file)
if err != nil {
@@ -177,7 +181,7 @@ func FormatGoImports(file string) error {
if bytes.Equal(contentBytes, formattedBytes) {
return nil
}
- f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0644)
+ f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0o644)
if err != nil {
return err
}
diff --git a/build/generate-bindata.go b/build/generate-bindata.go
index 7941af60a1..7fdf9d7616 100644
--- a/build/generate-bindata.go
+++ b/build/generate-bindata.go
@@ -20,7 +20,7 @@ import (
"github.com/shurcooL/vfsgen"
)
-func needsUpdate(dir string, filename string) (bool, []byte) {
+func needsUpdate(dir, filename string) (bool, []byte) {
needRegen := false
_, err := os.Stat(filename)
if err != nil {
@@ -50,7 +50,6 @@ func needsUpdate(dir string, filename string) (bool, []byte) {
newHash := hasher.Sum([]byte{})
if bytes.Compare(oldHash, newHash) != 0 {
-
return true, newHash
}
@@ -87,5 +86,5 @@ func main() {
if err != nil {
log.Fatalf("%v\n", err)
}
- _ = os.WriteFile(filename+".hash", newHash, 0666)
+ _ = os.WriteFile(filename+".hash", newHash, 0o666)
}
diff --git a/build/generate-emoji.go b/build/generate-emoji.go
index aa56d45f74..2f3536342d 100644
--- a/build/generate-emoji.go
+++ b/build/generate-emoji.go
@@ -30,9 +30,7 @@ const (
maxUnicodeVersion = 12
)
-var (
- flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
-)
+var flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
// Gemoji is a set of emoji data.
type Gemoji []Emoji
@@ -68,7 +66,7 @@ func main() {
}
// write
- err = os.WriteFile(*flagOut, buf, 0644)
+ err = os.WriteFile(*flagOut, buf, 0o644)
if err != nil {
log.Fatal(err)
}
@@ -109,7 +107,7 @@ func generate() ([]byte, error) {
return nil, err
}
- var skinTones = make(map[string]string)
+ skinTones := make(map[string]string)
skinTones["\U0001f3fb"] = "Light Skin Tone"
skinTones["\U0001f3fc"] = "Medium-Light Skin Tone"
@@ -119,7 +117,7 @@ func generate() ([]byte, error) {
var tmp Gemoji
- //filter out emoji that require greater than max unicode version
+ // filter out emoji that require greater than max unicode version
for i := range data {
val, _ := strconv.ParseFloat(data[i].UnicodeVersion, 64)
if int(val) <= maxUnicodeVersion {
@@ -158,7 +156,7 @@ func generate() ([]byte, error) {
// write a JSON file to use with tribute (write before adding skin tones since we can't support them there yet)
file, _ := json.Marshal(data)
- _ = os.WriteFile("assets/emoji.json", file, 0644)
+ _ = os.WriteFile("assets/emoji.json", file, 0o644)
// Add skin tones to emoji that support it
var (
diff --git a/build/generate-gitignores.go b/build/generate-gitignores.go
index 811953ee4a..0f7d719d40 100644
--- a/build/generate-gitignores.go
+++ b/build/generate-gitignores.go
@@ -34,7 +34,6 @@ func main() {
flag.Parse()
file, err := os.CreateTemp(os.TempDir(), prefix)
-
if err != nil {
log.Fatalf("Failed to create temp file. %s", err)
}
@@ -65,7 +64,6 @@ func main() {
}
gz, err := gzip.NewReader(file)
-
if err != nil {
log.Fatalf("Failed to gunzip the archive. %s", err)
}
@@ -96,7 +94,6 @@ func main() {
}
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".gitignore")))
-
if err != nil {
log.Fatalf("Failed to create new file. %s", err)
}
@@ -119,7 +116,7 @@ func main() {
}
// Write data to dst
dst = path.Join(destination, dst)
- err = os.WriteFile(dst, data, 0644)
+ err = os.WriteFile(dst, data, 0o644)
if err != nil {
log.Fatalf("Failed to write new file. %s", err)
}
diff --git a/build/generate-licenses.go b/build/generate-licenses.go
index 75fb7cc810..0f9b9f369f 100644
--- a/build/generate-licenses.go
+++ b/build/generate-licenses.go
@@ -34,7 +34,6 @@ func main() {
flag.Parse()
file, err := os.CreateTemp(os.TempDir(), prefix)
-
if err != nil {
log.Fatalf("Failed to create temp file. %s", err)
}
@@ -66,7 +65,6 @@ func main() {
}
gz, err := gzip.NewReader(file)
-
if err != nil {
log.Fatalf("Failed to gunzip the archive. %s", err)
}
@@ -100,7 +98,6 @@ func main() {
continue
}
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".txt")))
-
if err != nil {
log.Fatalf("Failed to create new file. %s", err)
}
diff --git a/build/gocovmerge.go b/build/gocovmerge.go
index 6a1af5b58f..1d2652129f 100644
--- a/build/gocovmerge.go
+++ b/build/gocovmerge.go
@@ -22,7 +22,7 @@ import (
"golang.org/x/tools/cover"
)
-func mergeProfiles(p *cover.Profile, merge *cover.Profile) {
+func mergeProfiles(p, merge *cover.Profile) {
if p.Mode != merge.Mode {
log.Fatalf("cannot merge profiles with different modes")
}
diff --git a/cmd/admin.go b/cmd/admin.go
index 3042df8bb7..66c7959ab3 100644
--- a/cmd/admin.go
+++ b/cmd/admin.go
@@ -525,7 +525,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.
@@ -577,7 +577,6 @@ func runListUsers(c *cli.Context) error {
}
users, err := user_model.GetAllUsers()
-
if err != nil {
return err
}
@@ -601,7 +600,6 @@ func runListUsers(c *cli.Context) error {
w.Flush()
return nil
-
}
func runDeleteUser(c *cli.Context) error {
@@ -826,7 +824,6 @@ func runUpdateOauth(c *cli.Context) error {
if c.IsSet("required-claim-name") {
oAuth2Config.RequiredClaimName = c.String("required-claim-name")
-
}
if c.IsSet("required-claim-value") {
oAuth2Config.RequiredClaimValue = c.String("required-claim-value")
@@ -843,7 +840,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
@@ -926,7 +923,7 @@ func runAddSMTP(c *cli.Context) error {
if !c.IsSet("port") {
return errors.New("port must be set")
}
- var active = true
+ active := true
if c.IsSet("active") {
active = c.BoolT("active")
}
@@ -994,7 +991,6 @@ func runListAuth(c *cli.Context) error {
}
authSources, err := auth.Sources()
-
if err != nil {
return err
}
diff --git a/cmd/admin_auth_ldap_test.go b/cmd/admin_auth_ldap_test.go
index e1cd1c3244..f050b536fd 100644
--- a/cmd/admin_auth_ldap_test.go
+++ b/cmd/admin_auth_ldap_test.go
@@ -17,12 +17,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
source *auth.Source
errMsg string
@@ -243,12 +243,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
authSource *auth.Source
errMsg string
@@ -474,12 +474,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
existingAuthSource *auth.Source
@@ -907,12 +907,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
existingAuthSource *auth.Source
@@ -1161,7 +1161,6 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
authSource: &auth.Source{
Type: auth.DLDAP,
Cfg: &ldap.Source{
-
AttributeMail: "mail",
},
},
diff --git a/cmd/cert.go b/cmd/cert.go
index b62319f808..162c4171bf 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 35cc305f4c..10f62f32c1 100644
--- a/cmd/doctor.go
+++ b/cmd/doctor.go
@@ -121,7 +121,6 @@ func runRecreateTable(ctx *cli.Context) error {
}
return recreateTables(x)
})
-
}
func runDoctor(ctx *cli.Context) error {
diff --git a/cmd/dump.go b/cmd/dump.go
index d6a5230060..4180425598 100644
--- a/cmd/dump.go
+++ b/cmd/dump.go
@@ -370,7 +370,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 1a9344dbe1..e980af3011 100644
--- a/cmd/dump_repo.go
+++ b/cmd/dump_repo.go
@@ -107,7 +107,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 c608667bf8..2930e5d307 100644
--- a/cmd/embedded.go
+++ b/cmd/embedded.go
@@ -109,7 +109,6 @@ type asset struct {
}
func initEmbeddedExtractor(c *cli.Context) error {
-
// Silence the console logger
log.DelNamedLogger("console")
log.DelNamedLogger(log.DEFAULT)
@@ -260,7 +259,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 {
@@ -296,7 +295,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" &&
@@ -307,9 +306,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 99d283b441..50b66cc7f2 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/serv.go b/cmd/serv.go
index ab60358b53..e42213cb98 100644
--- a/cmd/serv.go
+++ b/cmd/serv.go
@@ -247,7 +247,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 ec92ef242a..9a8d9dfa73 100644
--- a/cmd/web.go
+++ b/cmd/web.go
@@ -71,8 +71,7 @@ func runHTTPRedirector() {
http.Redirect(w, r, target, http.StatusTemporaryRedirect)
})
- var err = runHTTP("tcp", source, "HTTP Redirector", handler)
-
+ err := runHTTP("tcp", source, "HTTP Redirector", 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 866b88f7c9..517d71f017 100644
--- a/cmd/web_letsencrypt.go
+++ b/cmd/web_letsencrypt.go
@@ -17,7 +17,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 programmatically
// TODO: these are placeholders until we add options for each in settings with appropriate warning
@@ -77,7 +76,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 74996a1f35..66ff5c54e3 100644
--- a/contrib/fixtures/fixture_generation.go
+++ b/contrib/fixtures/fixture_generation.go
@@ -66,7 +66,7 @@ func generate(name string) error {
return err
}
path := filepath.Join(fixturesDir, name+".yml")
- if err := os.WriteFile(path, []byte(data), 0644); err != nil {
+ if err := os.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 e9dd675d4d..ceeba4de3b 100644
--- a/contrib/pr/checkout.go
+++ b/contrib/pr/checkout.go
@@ -93,13 +93,13 @@ func runPR() {
routers.InitGitServices()
setting.Database.LogSQL = true
- //x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
+ // x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
db.InitEngineWithMigration(context.Background(), func(_ *xorm.Engine) error {
return nil
})
db.HasEngine = true
- //x.ShowSQL(true)
+ // x.ShowSQL(true)
err = unittest.InitFixtures(
unittest.FixturesOptions{
Dir: path.Join(curDir, "models/fixtures/"),
@@ -115,7 +115,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.RegisterRenderers()
markup.Init()
c := routers.NormalRoutes()
@@ -137,7 +137,7 @@ func runPR() {
}
*/
- //Start the server
+ // Start the server
http.ListenAndServe(":8080", c)
log.Printf("[PR] Cleaning up ...\n")
@@ -160,7 +160,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()
@@ -173,15 +173,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 := os.ReadFile(codeFilePath)
if err != nil {
log.Fatalf("Failed to cache this code file : %v", err)
@@ -192,16 +192,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
}
@@ -212,7 +212,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("%s%s/head:%s", gitea_git.PullPrefix, pr, branchRef)
@@ -240,22 +240,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 = os.WriteFile(codeFilePath, dat, 0644)
+ err = os.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 4b5e2481e6..8f36850a1a 100644
--- a/integrations/api_admin_org_test.go
+++ b/integrations/api_admin_org_test.go
@@ -22,7 +22,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",
@@ -56,7 +56,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",
@@ -74,7 +74,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 d898266afe..54fe4a6eda 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 4c4c6308ee..dde51b2d53 100644
--- a/integrations/api_comment_test.go
+++ b/integrations/api_comment_test.go
@@ -44,10 +44,10 @@ func TestAPIListRepoComments(t *testing.T) {
unittest.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 8fc4124a48..38341aecff 100644
--- a/integrations/api_gpg_keys_test.go
+++ b/integrations/api_gpg_keys_test.go
@@ -28,15 +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, 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.StatusNotFound, 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.StatusNotFound, 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])
@@ -66,28 +69,27 @@ 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)
assert.Len(t, keys, 1)
- primaryKey1 := keys[0] //Primary key 1
+ primaryKey1 := keys[0] // Primary key 1
assert.EqualValues(t, "38EA3BCED732982C", primaryKey1.KeyID)
assert.Len(t, primaryKey1.Emails, 1)
assert.EqualValues(t, "user2@example.com", primaryKey1.Emails[0].Email)
assert.True(t, 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.Empty(t, subKey.Emails)
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)
@@ -95,14 +97,14 @@ func TestGPGKeys(t *testing.T) {
assert.EqualValues(t, "user2@example.com", key.Emails[0].Email)
assert.True(t, 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.Empty(t, key.Emails)
})
- //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
@@ -182,7 +184,7 @@ INx/MmBfmtCq05FqNclvU+sj2R3N1JJOtBOjZrJHQbJhzoILou8AkxeX1A+q9OAz
}
func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) {
- //User2 <user2@example.com> //primary & activated
+ // User2 <user2@example.com> //primary & activated
testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW
@@ -216,7 +218,7 @@ uy6MA3VSB99SK9ducGmE1Jv8mcziREroz2TEGr0zPs6h
}
func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) {
- //User2 <user2-2@example.com> //secondary and not activated
+ // User2 <user2-2@example.com> //secondary and not activated
testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
mQGNBGC2K2cBDAC1+Xgk+8UfhASVgRngQi4rnQ8k0t+bWsBz4Czd26+cxVDRwlTT
diff --git a/integrations/api_issue_label_test.go b/integrations/api_issue_label_test.go
index 42bfedf32f..94b487377e 100644
--- a/integrations/api_issue_label_test.go
+++ b/integrations/api_issue_label_test.go
@@ -53,21 +53,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"
@@ -83,10 +83,9 @@ func TestAPIModifyLabels(t *testing.T) {
})
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
- //DeleteLabel
+ // DeleteLabel
req = NewRequest(t, "DELETE", singleURLStr)
session.MakeRequest(t, req, http.StatusNoContent)
-
}
func TestAPIAddIssueLabels(t *testing.T) {
@@ -173,21 +172,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"
@@ -203,8 +202,7 @@ func TestAPIModifyOrgLabels(t *testing.T) {
})
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
- //DeleteLabel
+ // DeleteLabel
req = NewRequest(t, "DELETE", singleURLStr)
session.MakeRequest(t, req, http.StatusNoContent)
-
}
diff --git a/integrations/api_issue_reaction_test.go b/integrations/api_issue_reaction_test.go
index fa0f016ef2..aa6f46f8bd 100644
--- a/integrations/api_issue_reaction_test.go
+++ b/integrations/api_issue_reaction_test.go
@@ -33,19 +33,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",
})
session.MakeRequest(t, req, http.StatusForbidden)
- //Delete not allowed reaction
+ // Delete not allowed reaction
req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{
Reaction: "zzz",
})
session.MakeRequest(t, req, http.StatusOK)
- //Add allowed reaction
+ // Add allowed reaction
req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
Reaction: "rocket",
})
@@ -53,10 +53,10 @@ func TestAPIIssuesReactions(t *testing.T) {
var apiNewReaction api.Reaction
DecodeJSON(t, resp, &apiNewReaction)
- //Add existing reaction
+ // Add existing reaction
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
@@ -93,19 +93,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",
})
session.MakeRequest(t, req, http.StatusForbidden)
- //Delete none existing reaction
+ // Delete none existing reaction
req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{
Reaction: "eyes",
})
session.MakeRequest(t, req, http.StatusOK)
- //Add allowed reaction
+ // Add allowed reaction
req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
Reaction: "+1",
})
@@ -113,10 +113,10 @@ func TestAPICommentReactions(t *testing.T) {
var apiNewReaction api.Reaction
DecodeJSON(t, resp, &apiNewReaction)
- //Add existing reaction
+ // Add existing reaction
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 dfc3edee8d..e0bb388365 100644
--- a/integrations/api_issue_subscription_test.go
+++ b/integrations/api_issue_subscription_test.go
@@ -33,7 +33,6 @@ func TestAPIIssueSubscriptions(t *testing.T) {
token := getTokenForLoggedInUser(t, session)
testSubscription := func(issue *models.Issue, isWatching bool) {
-
issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.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 0912d1d82b..3957c10233 100644
--- a/integrations/api_issue_test.go
+++ b/integrations/api_issue_test.go
@@ -210,7 +210,7 @@ func TestAPISearchIssues(t *testing.T) {
resp = session.MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &apiIssues)
assert.EqualValues(t, "15", 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 94e569113c..335fd2929a 100644
--- a/integrations/api_issue_tracked_time_test.go
+++ b/integrations/api_issue_tracked_time_test.go
@@ -48,8 +48,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)
@@ -71,17 +71,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 := unittest.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 12b3bac425..4bf18632ca 100644
--- a/integrations/api_notification_test.go
+++ b/integrations/api_notification_test.go
@@ -30,7 +30,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
@@ -40,7 +40,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)
@@ -113,7 +113,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))
session.MakeRequest(t, req, http.StatusResetContent)
diff --git a/integrations/api_org_test.go b/integrations/api_org_test.go
index 76979c674d..e33c010e88 100644
--- a/integrations/api_org_test.go
+++ b/integrations/api_org_test.go
@@ -23,7 +23,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",
@@ -80,7 +80,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",
@@ -107,7 +107,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",
@@ -126,7 +126,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_private_serv_test.go b/integrations/api_private_serv_test.go
index 68308bafc5..a58d927cb9 100644
--- a/integrations/api_private_serv_test.go
+++ b/integrations/api_private_serv_test.go
@@ -150,7 +150,5 @@ func TestAPIPrivateServ(t *testing.T) {
assert.Equal(t, "user15", results.OwnerName)
assert.Equal(t, "big_test_private_2", results.RepoName)
assert.Equal(t, int64(20), results.RepoID)
-
})
-
}
diff --git a/integrations/api_pull_review_test.go b/integrations/api_pull_review_test.go
index df6dc75d51..3f80dbdf9b 100644
--- a/integrations/api_pull_review_test.go
+++ b/integrations/api_pull_review_test.go
@@ -80,22 +80,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)
@@ -147,17 +148,18 @@ 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: "",
Event: "COMMENT",
- 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,
- },
+ 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,
+ },
},
})
var commentReview api.PullReview
diff --git a/integrations/api_repo_edit_test.go b/integrations/api_repo_edit_test.go
index 91ec4c699e..f3f0139d95 100644
--- a/integrations/api_repo_edit_test.go
+++ b/integrations/api_repo_edit_test.go
@@ -175,7 +175,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{
@@ -199,7 +199,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}",
@@ -233,7 +233,7 @@ func TestAPIRepoEdit(t *testing.T) {
req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption)
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_git_commits_test.go b/integrations/api_repo_git_commits_test.go
index 2099d568f7..f5a64490b9 100644
--- a/integrations/api_repo_git_commits_test.go
+++ b/integrations/api_repo_git_commits_test.go
@@ -130,7 +130,6 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) {
assert.EqualValues(t,
"From f27c2b2b03dcab38beaf89b0ab4ff61f6de63441 Mon Sep 17 00:00:00 2001\nFrom: User2 <user2@example.com>\nDate: Sun, 6 Aug 2017 19:55:01 +0200\nSubject: [PATCH] good signed commit\n\n---\n readme.md | 1 +\n 1 file changed, 1 insertion(+)\n create mode 100644 readme.md\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n",
resp.Body.String())
-
}
func TestGetFileHistory(t *testing.T) {
diff --git a/integrations/api_repo_lfs_locks_test.go b/integrations/api_repo_lfs_locks_test.go
index 3e0b40f511..ca7bd35001 100644
--- a/integrations/api_repo_lfs_locks_test.go
+++ b/integrations/api_repo_lfs_locks_test.go
@@ -53,8 +53,8 @@ func TestAPILFSLocksNotLogin(t *testing.T) {
func TestAPILFSLocksLogged(t *testing.T) {
defer prepareTestEnv(t)()
setting.LFS.StartServer = true
- user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) //in org 3
- user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) //in org 3
+ user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // in org 3
+ user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // in org 3
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // own by org 3
@@ -101,7 +101,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})
@@ -111,14 +111,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())
@@ -130,7 +130,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{})
@@ -154,7 +154,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 c909e96f06..52764a3a69 100644
--- a/integrations/api_repo_test.go
+++ b/integrations/api_repo_test.go
@@ -79,76 +79,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 {
@@ -464,7 +487,7 @@ func TestAPIRepoTransfer(t *testing.T) {
defer prepareTestEnv(t)()
- //create repo to move
+ // create repo to move
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@@ -480,7 +503,7 @@ func TestAPIRepoTransfer(t *testing.T) {
resp := session.MakeRequest(t, req, http.StatusCreated)
DecodeJSON(t, resp, apiRepo)
- //start testing
+ // start testing
for _, testCase := range testCases {
user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}).(*user_model.User)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository)
@@ -493,13 +516,13 @@ func TestAPIRepoTransfer(t *testing.T) {
session.MakeRequest(t, req, testCase.expectedStatus)
}
- //cleanup
+ // cleanup
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository)
_ = models.DeleteRepository(user, repo.OwnerID, repo.ID)
}
func transfer(t *testing.T) *repo_model.Repository {
- //create repo to move
+ // create repo to move
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
diff --git a/integrations/api_repo_topic_test.go b/integrations/api_repo_topic_test.go
index c417b3a9d2..b7f9a5a5a6 100644
--- a/integrations/api_repo_topic_test.go
+++ b/integrations/api_repo_topic_test.go
@@ -155,5 +155,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)
session.MakeRequest(t, req, http.StatusForbidden)
-
}
diff --git a/integrations/api_user_heatmap_test.go b/integrations/api_user_heatmap_test.go
index 019cf7dcac..69f4ff2249 100644
--- a/integrations/api_user_heatmap_test.go
+++ b/integrations/api_user_heatmap_test.go
@@ -22,7 +22,7 @@ func TestUserHeatmap(t *testing.T) {
normalUsername := "user2"
session := loginUser(t, adminUsername)
- var fakeNow = time.Date(2011, 10, 20, 0, 0, 0, 0, time.Local)
+ fakeNow := time.Date(2011, 10, 20, 0, 0, 0, 0, time.Local)
timeutil.Set(fakeNow)
defer timeutil.Unset()
diff --git a/integrations/api_user_orgs_test.go b/integrations/api_user_orgs_test.go
index 09272726f6..219bd273c9 100644
--- a/integrations/api_user_orgs_test.go
+++ b/integrations/api_user_orgs_test.go
@@ -54,7 +54,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 481104d73f..25243feb3c 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(repo_model.AttachmentRelativePath(tc.uuid), strings.NewReader("hello world"), -1)
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 517e7f005d..ffae471307 100644
--- a/integrations/benchmarks_test.go
+++ b/integrations/benchmarks_test.go
@@ -58,7 +58,7 @@ func BenchmarkRepoBranchCommit(b *testing.B) {
req := NewRequestf(b, "GET", "/api/v1/repos/%s/branches", repo.FullName())
resp := session.MakeRequest(b, req, http.StatusOK)
DecodeJSON(b, resp, &branches)
- b.ResetTimer() //We measure from here
+ b.ResetTimer() // We measure from here
if len(branches) != 0 {
for i := 0; i < b.N; i++ {
req := NewRequestf(b, "GET", "/api/v1/repos/%s/commits?sha=%s", repo.FullName(), branches[i%len(branches)].Name)
diff --git a/integrations/cmd_keys_test.go b/integrations/cmd_keys_test.go
index d33765c445..3d4194c331 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,no-user-rc,restrict 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/dump_restore_test.go b/integrations/dump_restore_test.go
index f35af43a91..053ca47855 100644
--- a/integrations/dump_restore_test.go
+++ b/integrations/dump_restore_test.go
@@ -55,7 +55,7 @@ func TestDumpRestore(t *testing.T) {
//
ctx := context.Background()
- var opts = migrations.MigrateOptions{
+ opts := migrations.MigrateOptions{
GitServiceType: structs.GiteaService,
Issues: true,
Labels: true,
@@ -109,11 +109,11 @@ func TestDumpRestore(t *testing.T) {
beforeBytes, err := os.ReadFile(filepath.Join(d, "issue.yml"))
assert.NoError(t, err)
- var before = make([]*base.Issue, 0, 10)
+ before := make([]*base.Issue, 0, 10)
assert.NoError(t, yaml.Unmarshal(beforeBytes, &before))
afterBytes, err := os.ReadFile(filepath.Join(newd, "issue.yml"))
assert.NoError(t, err)
- var after = make([]*base.Issue, 0, 10)
+ after := make([]*base.Issue, 0, 10)
assert.NoError(t, yaml.Unmarshal(afterBytes, &after))
assert.EqualValues(t, len(before), len(after))
diff --git a/integrations/editor_test.go b/integrations/editor_test.go
index a46712293e..05892aa906 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 8984c1fcb0..ff32988634 100644
--- a/integrations/eventsource_test.go
+++ b/integrations/eventsource_test.go
@@ -69,7 +69,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))
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 282bdd04a9..b13c912fd7 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 := os.MkdirTemp("", "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 = os.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 onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ...
}()
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)
}
@@ -142,7 +141,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) {
// forcibly set default branch to master
_, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(dstPath)
assert.NoError(t, err)
- assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644))
+ assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644))
assert.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{
Email: "test@example.com",
diff --git a/integrations/git_smart_http_test.go b/integrations/git_smart_http_test.go
index c049f71c30..b6043fe706 100644
--- a/integrations/git_smart_http_test.go
+++ b/integrations/git_smart_http_test.go
@@ -18,7 +18,7 @@ func TestGitSmartHTTP(t *testing.T) {
}
func testGitSmartHTTP(t *testing.T, u *url.URL) {
- var kases = []struct {
+ kases := []struct {
p string
code int
}{
diff --git a/integrations/git_test.go b/integrations/git_test.go
index 0d33c786aa..243cca2e55 100644
--- a/integrations/git_test.go
+++ b/integrations/git_test.go
@@ -32,8 +32,8 @@ import (
)
const (
- littleSize = 1024 //1ko
- bigSize = 128 * 1024 * 1024 //128Mo
+ littleSize = 1024 // 1ko
+ bigSize = 128 * 1024 * 1024 // 128Mo
)
func TestGit(t *testing.T) {
@@ -96,15 +96,15 @@ func testGit(t *testing.T, u *url.URL) {
t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, perm.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 := os.MkdirTemp("", sshContext.Reponame)
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
@@ -135,7 +135,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) {
@@ -300,13 +299,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
@@ -339,7 +338,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()))
@@ -639,7 +638,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
t.Run("AddCommit", func(t *testing.T) {
- err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0666)
+ err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666)
if !assert.NoError(t, err) {
return
}
@@ -713,7 +712,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
}
t.Run("AddCommit2", func(t *testing.T) {
- err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0666)
+ err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0o666)
if !assert.NoError(t, err) {
return
}
diff --git a/integrations/gpg_git_test.go b/integrations/gpg_git_test.go
index 8478f53c0e..461f3c503d 100644
--- a/integrations/gpg_git_test.go
+++ b/integrations/gpg_git_test.go
@@ -32,7 +32,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")
@@ -257,7 +257,6 @@ func TestGPGGit(t *testing.T) {
}
assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email)
}))
-
})
}, false)
var pr api.PullRequest
@@ -321,7 +320,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 527d4b951a..dfa5bade78 100644
--- a/integrations/integration_test.go
+++ b/integrations/integration_test.go
@@ -268,10 +268,10 @@ func prepareTestEnv(t testing.TB, skip ...int) func() {
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
@@ -395,7 +395,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 {
@@ -564,10 +564,10 @@ func resetFixtures(t *testing.T) {
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
}
diff --git a/integrations/issue_test.go b/integrations/issue_test.go
index a2c74d4bdd..29de774ee4 100644
--- a/integrations/issue_test.go
+++ b/integrations/issue_test.go
@@ -121,7 +121,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)
@@ -149,7 +148,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)
@@ -244,7 +242,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")
@@ -254,7 +253,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))
@@ -264,7 +264,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")
@@ -274,7 +275,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")
@@ -285,7 +287,8 @@ func TestIssueCrossReference(t *testing.T) {
RefIssueID: issueRef.ID,
RefCommentID: commentID,
RefIsPull: false,
- RefAction: references.XRefActionNone}
+ RefAction: references.XRefActionNone,
+ }
unittest.AssertExistsAndLoadBean(t, comment)
// Ref from a different repository
@@ -296,7 +299,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) {
diff --git a/integrations/lfs_local_endpoint_test.go b/integrations/lfs_local_endpoint_test.go
index 7e0166b381..9de0ec18c9 100644
--- a/integrations/lfs_local_endpoint_test.go
+++ b/integrations/lfs_local_endpoint_test.go
@@ -29,13 +29,13 @@ func TestDetermineLocalEndpoint(t *testing.T) {
rootdotgit, _ := os.MkdirTemp("", "lfs_test")
defer os.RemoveAll(rootdotgit)
- os.Mkdir(filepath.Join(rootdotgit, ".git"), 0700)
+ os.Mkdir(filepath.Join(rootdotgit, ".git"), 0o700)
lfsroot, _ := os.MkdirTemp("", "lfs_test")
defer os.RemoveAll(lfsroot)
// Test cases
- var cases = []struct {
+ cases := []struct {
cloneurl string
lfsurl string
expected *url.URL
diff --git a/integrations/links_test.go b/integrations/links_test.go
index d1d90cd5e3..f514aa7757 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",
@@ -49,7 +49,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",
@@ -67,7 +67,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",
}
@@ -79,7 +79,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",
@@ -138,7 +138,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 2661704122..0518dd1179 100644
--- a/integrations/migration-test/migration_test.go
+++ b/integrations/migration-test/migration_test.go
@@ -74,10 +74,10 @@ func initMigrationTest(t *testing.T) func() {
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
@@ -315,6 +315,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 71d0ee3cb1..f2992ecc1f 100644
--- a/integrations/nonascii_branches_test.go
+++ b/integrations/nonascii_branches_test.go
@@ -210,5 +210,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 7969339644..44df39b6e0 100644
--- a/integrations/privateactivity_test.go
+++ b/integrations/privateactivity_test.go
@@ -18,8 +18,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 ed34a0f6d6..49e7dc04ec 100644
--- a/integrations/pull_merge_test.go
+++ b/integrations/pull_merge_test.go
@@ -65,7 +65,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 := webhook.HookTasks(1, 1) //Retrieve previous hook number
+ hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number
assert.NoError(t, err)
hookTasksLenBefore := len(hookTasks)
@@ -87,7 +87,7 @@ func TestPullMerge(t *testing.T) {
func TestPullRebase(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
- hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number
+ hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number
assert.NoError(t, err)
hookTasksLenBefore := len(hookTasks)
@@ -109,7 +109,7 @@ func TestPullRebase(t *testing.T) {
func TestPullRebaseMerge(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
- hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number
+ hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number
assert.NoError(t, err)
hookTasksLenBefore := len(hookTasks)
@@ -131,7 +131,7 @@ func TestPullRebaseMerge(t *testing.T) {
func TestPullSquash(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
- hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number
+ hookTasks, err := webhook.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 b80b85fbeb..dc2803aca0 100644
--- a/integrations/pull_update_test.go
+++ b/integrations/pull_update_test.go
@@ -23,12 +23,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 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26}).(*user_model.User)
pr := createOutdatedPR(t, user, org26)
- //Test GetDiverging
+ // Test GetDiverging
diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr)
assert.NoError(t, err)
assert.EqualValues(t, 1, diffCount.Behind)
@@ -41,7 +41,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(git.DefaultContext, pr)
assert.NoError(t, err)
assert.EqualValues(t, 0, diffCount.Behind)
@@ -51,12 +51,12 @@ func TestAPIPullUpdate(t *testing.T) {
func TestAPIPullUpdateByRebase(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
- //Create PR to test
+ // Create PR to test
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26}).(*user_model.User)
pr := createOutdatedPR(t, user, org26)
- //Test GetDiverging
+ // Test GetDiverging
diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr)
assert.NoError(t, err)
assert.EqualValues(t, 1, diffCount.Behind)
@@ -69,7 +69,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) {
req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&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(git.DefaultContext, pr)
assert.NoError(t, err)
assert.EqualValues(t, 0, diffCount.Behind)
@@ -98,7 +98,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul
assert.NoError(t, err)
assert.NotEmpty(t, headRepo)
- //create a commit on base Repo
+ // create a commit on base Repo
_, err = files_service.CreateOrUpdateRepoFile(git.DefaultContext, baseRepo, actor, &files_service.UpdateRepoFileOptions{
TreePath: "File_A",
Message: "Add File A",
@@ -121,7 +121,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul
})
assert.NoError(t, err)
- //create a commit on head Repo
+ // create a commit on head Repo
_, err = files_service.CreateOrUpdateRepoFile(git.DefaultContext, headRepo, actor, &files_service.UpdateRepoFileOptions{
TreePath: "File_B",
Message: "Add File on PR branch",
@@ -144,7 +144,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul
})
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 66cc8dcfe2..a10ec7f2d3 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 4be1e4ec8e..b53d988c58 100644
--- a/integrations/repo_commits_test.go
+++ b/integrations/repo_commits_test.go
@@ -71,12 +71,12 @@ 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")
reqOne := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/status")
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
- //By Ref
+ // By Ref
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/statuses")
reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/status")
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
diff --git a/integrations/repofiles_update_test.go b/integrations/repofiles_update_test.go
index 97cdd67ba3..46c73b48f6 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 := files_service.CreateOrUpdateRepoFile(git.DefaultContext, repo, doer, opts)
assert.Nil(t, fileResponse)
assert.Error(t, err)
diff --git a/integrations/setting_test.go b/integrations/setting_test.go
index eb495acb24..c0455a4520 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 f9c807413a..e0ff13543e 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, os.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, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0o644))
assert.NoError(t, 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 69db480c15..246f6fe7d0 100644
--- a/integrations/testlogger.go
+++ b/integrations/testlogger.go
@@ -185,7 +185,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 7cf5f9bc8f..17e9174e5d 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_avatar_test.go b/integrations/user_avatar_test.go
index d1005bce07..7c2267885a 100644
--- a/integrations/user_avatar_test.go
+++ b/integrations/user_avatar_test.go
@@ -42,7 +42,7 @@ func TestUserAvatar(t *testing.T) {
body := &bytes.Buffer{}
- //Setup multi-part
+ // Setup multi-part
writer := multipart.NewWriter(body)
writer.WriteField("source", "local")
part, err := writer.CreateFormFile("avatar", "avatar-for-testuseravatar.png")
diff --git a/integrations/user_test.go b/integrations/user_test.go
index 8552993217..c12c2be40e 100644
--- a/integrations/user_test.go
+++ b/integrations/user_test.go
@@ -119,15 +119,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 <user1@example.com>
+ // Import key
+ // User1 <user1@example.com>
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session)
testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK-----
@@ -161,7 +161,7 @@ GrE0MHOxUbc9tbtyk0F1SuzREUBH
=DDXw
-----END PGP PUBLIC KEY BLOCK-----
`)
- //Export new key
+ // Export new key
testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK-----
xsBNBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo
@@ -200,6 +200,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 6cbdc24401..19b9dd6327 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/auth/webauthn.go b/models/auth/webauthn.go
index 9e09134662..e6c446af94 100644
--- a/models/auth/webauthn.go
+++ b/models/auth/webauthn.go
@@ -12,9 +12,9 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil"
- "xorm.io/xorm"
"github.com/duo-labs/webauthn/webauthn"
+ "xorm.io/xorm"
)
// ErrWebAuthnCredentialNotExist represents a "ErrWebAuthnCRedentialNotExist" kind of error.
@@ -30,14 +30,14 @@ func (err ErrWebAuthnCredentialNotExist) Error() string {
return fmt.Sprintf("WebAuthn credential does not exist [credential_id: %s]", err.CredentialID)
}
-//IsErrWebAuthnCredentialNotExist checks if an error is a ErrWebAuthnCredentialNotExist.
+// IsErrWebAuthnCredentialNotExist checks if an error is a ErrWebAuthnCredentialNotExist.
func IsErrWebAuthnCredentialNotExist(err error) bool {
_, ok := err.(ErrWebAuthnCredentialNotExist)
return ok
}
-//WebAuthnCredential represents the WebAuthn credential data for a public-key
-//credential conformant to WebAuthn Level 1
+// WebAuthnCredential represents the WebAuthn credential data for a public-key
+// credential conformant to WebAuthn Level 1
type WebAuthnCredential struct {
ID int64 `xorm:"pk autoincr"`
Name string
@@ -109,7 +109,7 @@ func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential {
return creds
}
-//GetWebAuthnCredentialsByUID returns all WebAuthn credentials of the given user
+// GetWebAuthnCredentialsByUID returns all WebAuthn credentials of the given user
func GetWebAuthnCredentialsByUID(uid int64) (WebAuthnCredentialList, error) {
return getWebAuthnCredentialsByUID(db.DefaultContext, uid)
}
@@ -119,7 +119,7 @@ func getWebAuthnCredentialsByUID(ctx context.Context, uid int64) (WebAuthnCreden
return creds, db.GetEngine(ctx).Where("user_id = ?", uid).Find(&creds)
}
-//ExistsWebAuthnCredentialsForUID returns if the given user has credentials
+// ExistsWebAuthnCredentialsForUID returns if the given user has credentials
func ExistsWebAuthnCredentialsForUID(uid int64) (bool, error) {
return existsWebAuthnCredentialsByUID(db.DefaultContext, uid)
}
@@ -211,7 +211,7 @@ func deleteCredential(ctx context.Context, id, userID int64) (bool, error) {
return had > 0, err
}
-//WebAuthnCredentials implementns the webauthn.User interface
+// WebAuthnCredentials implementns the webauthn.User interface
func WebAuthnCredentials(userID int64) ([]webauthn.Credential, error) {
dbCreds, err := GetWebAuthnCredentialsByUID(userID)
if err != nil {
diff --git a/models/avatars/avatar.go b/models/avatars/avatar.go
index 6107856ade..9f7b0c474f 100644
--- a/models/avatars/avatar.go
+++ b/models/avatars/avatar.go
@@ -175,12 +175,12 @@ func generateEmailAvatarLink(email string, size int, final bool) string {
return DefaultAvatarLink()
}
-//GenerateEmailAvatarFastLink returns a avatar link (fast, the link may be a delegated one: "/avatar/${hash}")
+// GenerateEmailAvatarFastLink returns a avatar link (fast, the link may be a delegated one: "/avatar/${hash}")
func GenerateEmailAvatarFastLink(email string, size int) string {
return generateEmailAvatarLink(email, size, false)
}
-//GenerateEmailAvatarFinalLink returns a avatar final link (maybe slow)
+// GenerateEmailAvatarFinalLink returns a avatar final link (maybe slow)
func GenerateEmailAvatarFinalLink(email string, size int) string {
return generateEmailAvatarLink(email, size, true)
}
diff --git a/models/consistency.go b/models/consistency.go
index 0b9d9fd2c3..4a94fe25d4 100644
--- a/models/consistency.go
+++ b/models/consistency.go
@@ -240,7 +240,6 @@ func FixIssueLabelWithOutsideLabels() (int64, error) {
WHERE
(label.org_id = 0 AND 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/models/db/engine.go b/models/db/engine.go
index 665808d701..0604d939d3 100755
--- a/models/db/engine.go
+++ b/models/db/engine.go
@@ -121,7 +121,7 @@ func newXORMEngine() (*xorm.Engine, error) {
return engine, nil
}
-//SyncAllTables sync the schemas of all tables, is required by unit test code
+// SyncAllTables sync the schemas of all tables, is required by unit test code
func SyncAllTables() error {
return x.StoreEngine("InnoDB").Sync2(tables...)
}
diff --git a/models/issue_test.go b/models/issue_test.go
index aee9a50184..e2759ba38f 100644
--- a/models/issue_test.go
+++ b/models/issue_test.go
@@ -394,7 +394,6 @@ func TestIssue_InsertIssue(t *testing.T) {
issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7)
_, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue))
assert.NoError(t, err)
-
}
func TestIssue_ResolveMentions(t *testing.T) {
diff --git a/models/issues/content_history.go b/models/issues/content_history.go
index 721ce11f85..2d2febfa5c 100644
--- a/models/issues/content_history.go
+++ b/models/issues/content_history.go
@@ -155,7 +155,6 @@ func FetchIssueContentHistoryList(dbCtx context.Context, issueID, commentID int6
Where(builder.Eq{"issue_id": issueID, "comment_id": commentID}).
OrderBy("edited_unix DESC").
Find(&res)
-
if err != nil {
log.Error("can not fetch issue content history list. err=%v", err)
return nil, err
diff --git a/models/lfs.go b/models/lfs.go
index cf596f5468..e0c16767f7 100644
--- a/models/lfs.go
+++ b/models/lfs.go
@@ -209,7 +209,7 @@ func LFSAutoAssociate(metas []*LFSMetaObject, user *user_model.User, repoID int6
func IterateLFS(f func(mo *LFSMetaObject) error) error {
var start int
const batchSize = 100
- var e = db.GetEngine(db.DefaultContext)
+ e := db.GetEngine(db.DefaultContext)
for {
mos := make([]*LFSMetaObject, 0, batchSize)
if err := e.Limit(batchSize, start).Find(&mos); err != nil {
diff --git a/models/migrate_test.go b/models/migrate_test.go
index 09433b6b41..34183c1854 100644
--- a/models/migrate_test.go
+++ b/models/migrate_test.go
@@ -45,7 +45,7 @@ func assertCreateIssues(t *testing.T, reponame string, isPull bool) {
}
title := "issuetitle1"
- var is = &Issue{
+ is := &Issue{
RepoID: repo.ID,
MilestoneID: milestone.ID,
Repo: repo,
@@ -130,7 +130,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
- var i = &Issue{
+ i := &Issue{
RepoID: repo.ID,
Repo: repo,
Title: "title1",
@@ -140,7 +140,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) {
Poster: owner,
}
- var p = &PullRequest{
+ p := &PullRequest{
Issue: i,
}
diff --git a/models/migrations/migrations_test.go b/models/migrations/migrations_test.go
index 33d589ddb2..f798d50117 100644
--- a/models/migrations/migrations_test.go
+++ b/models/migrations/migrations_test.go
@@ -219,10 +219,10 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
diff --git a/models/migrations/testlogger_test.go b/models/migrations/testlogger_test.go
index 5e3d880b54..01d6b7a0f7 100644
--- a/models/migrations/testlogger_test.go
+++ b/models/migrations/testlogger_test.go
@@ -170,7 +170,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/models/migrations/v176_test.go b/models/migrations/v176_test.go
index 2763e4f120..bc066c3b32 100644
--- a/models/migrations/v176_test.go
+++ b/models/migrations/v176_test.go
@@ -124,5 +124,4 @@ func Test_removeInvalidLabels(t *testing.T) {
t.Errorf("IssueLabel[%d] was deleted but should have remained", id)
}
}
-
}
diff --git a/models/migrations/v177_test.go b/models/migrations/v177_test.go
index f5fc793aa4..5a58e2c614 100644
--- a/models/migrations/v177_test.go
+++ b/models/migrations/v177_test.go
@@ -85,5 +85,4 @@ func Test_deleteOrphanedIssueLabels(t *testing.T) {
pre := preMigration[id]
assert.Equal(t, pre, post, "migration changed issueLabel %d", id)
}
-
}
diff --git a/models/migrations/v181_test.go b/models/migrations/v181_test.go
index b392a9b71d..b9a6c6619b 100644
--- a/models/migrations/v181_test.go
+++ b/models/migrations/v181_test.go
@@ -38,7 +38,7 @@ func Test_addPrimaryEmail2EmailAddress(t *testing.T) {
IsPrimary bool `xorm:"DEFAULT(false) NOT NULL"`
}
- var users = make([]User, 0, 20)
+ users := make([]User, 0, 20)
err = x.Find(&users)
assert.NoError(t, err)
diff --git a/models/migrations/v182_test.go b/models/migrations/v182_test.go
index 9fb371e078..0d3eda9c51 100644
--- a/models/migrations/v182_test.go
+++ b/models/migrations/v182_test.go
@@ -37,10 +37,10 @@ func Test_addIssueResourceIndexTable(t *testing.T) {
MaxIndex int64 `xorm:"index"`
}
- var start = 0
+ start := 0
const batchSize = 1000
for {
- var indexes = make([]ResourceIndex, 0, batchSize)
+ indexes := make([]ResourceIndex, 0, batchSize)
err := x.Table("issue_index").Limit(batchSize, start).Find(&indexes)
assert.NoError(t, err)
diff --git a/models/migrations/v189_test.go b/models/migrations/v189_test.go
index fcae5dcc73..4ec3fe8c60 100644
--- a/models/migrations/v189_test.go
+++ b/models/migrations/v189_test.go
@@ -26,7 +26,6 @@ func (ls *LoginSourceOriginalV189) TableName() string {
}
func Test_unwrapLDAPSourceCfg(t *testing.T) {
-
// Prepare and load the testing database
x, deferable := prepareTestEnv(t, 0, new(LoginSourceOriginalV189))
if x == nil || t.Failed() {
@@ -80,5 +79,4 @@ func Test_unwrapLDAPSourceCfg(t *testing.T) {
assert.EqualValues(t, source.ID%2 == 0, source.IsActive, "unwrapLDAPSourceCfg failed for %d", source.ID)
}
}
-
}
diff --git a/models/migrations/v191.go b/models/migrations/v191.go
index c91990e0f3..9a688243e1 100644
--- a/models/migrations/v191.go
+++ b/models/migrations/v191.go
@@ -11,7 +11,6 @@ import (
)
func alterIssueAndCommentTextFieldsToLongText(x *xorm.Engine) error {
-
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
diff --git a/models/migrations/v195_test.go b/models/migrations/v195_test.go
index baf9cb61c2..05f8469daa 100644
--- a/models/migrations/v195_test.go
+++ b/models/migrations/v195_test.go
@@ -40,10 +40,10 @@ func Test_addTableCommitStatusIndex(t *testing.T) {
MaxIndex int64 `xorm:"index"`
}
- var start = 0
+ start := 0
const batchSize = 1000
for {
- var indexes = make([]CommitStatusIndex, 0, batchSize)
+ indexes := make([]CommitStatusIndex, 0, batchSize)
err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes)
assert.NoError(t, err)
diff --git a/models/migrations/v207.go b/models/migrations/v207.go
index 82e2e3aa31..4964a8435c 100644
--- a/models/migrations/v207.go
+++ b/models/migrations/v207.go
@@ -16,7 +16,6 @@ import (
)
func addWebAuthnCred(x *xorm.Engine) error {
-
// Create webauthnCredential table
type webauthnCredential struct {
ID int64 `xorm:"pk autoincr"`
diff --git a/models/migrations/v208.go b/models/migrations/v208.go
index 04bb981a4e..c1e656b98d 100644
--- a/models/migrations/v208.go
+++ b/models/migrations/v208.go
@@ -12,7 +12,6 @@ import (
)
func useBase32HexForCredIDInWebAuthnCredential(x *xorm.Engine) error {
-
// Create webauthnCredential table
type webauthnCredential struct {
ID int64 `xorm:"pk autoincr"`
diff --git a/models/repo.go b/models/repo.go
index 83031c508c..2a857c43df 100644
--- a/models/repo.go
+++ b/models/repo.go
@@ -718,7 +718,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
if err != nil {
return fmt.Errorf("listDeployKeys: %v", err)
}
- var needRewriteKeysFile = len(deployKeys) > 0
+ needRewriteKeysFile := len(deployKeys) > 0
for _, dKey := range deployKeys {
if err := DeleteDeployKey(ctx, doer, dKey.ID); err != nil {
return fmt.Errorf("deleteDeployKeys: %v", err)
@@ -844,7 +844,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
return err
}
- var lfsPaths = make([]string, 0, len(lfsObjects))
+ lfsPaths := make([]string, 0, len(lfsObjects))
for _, v := range lfsObjects {
count, err := sess.Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: v.Oid}})
if err != nil {
@@ -867,7 +867,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
return err
}
- var archivePaths = make([]string, 0, len(archives))
+ archivePaths := make([]string, 0, len(archives))
for _, v := range archives {
p, _ := v.RelativePath()
archivePaths = append(archivePaths, p)
@@ -893,7 +893,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
return err
}
- var newAttachmentPaths = make([]string, 0, len(newAttachments))
+ newAttachmentPaths := make([]string, 0, len(newAttachments))
for _, attach := range newAttachments {
newAttachmentPaths = append(newAttachmentPaths, attach.RelativePath())
}
diff --git a/models/repo/archiver.go b/models/repo/archiver.go
index c29891397f..dc64cce49b 100644
--- a/models/repo/archiver.go
+++ b/models/repo/archiver.go
@@ -90,7 +90,7 @@ type FindRepoArchiversOption struct {
}
func (opts FindRepoArchiversOption) toConds() builder.Cond {
- var cond = builder.NewCond()
+ cond := builder.NewCond()
if opts.OlderThan > 0 {
cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-opts.OlderThan).Unix()})
}
@@ -99,7 +99,7 @@ func (opts FindRepoArchiversOption) toConds() builder.Cond {
// FindRepoArchives find repo archivers
func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) {
- var archivers = make([]*RepoArchiver, 0, opts.PageSize)
+ archivers := make([]*RepoArchiver, 0, opts.PageSize)
start, limit := opts.GetSkipTake()
err := db.GetEngine(db.DefaultContext).Where(opts.toConds()).
Asc("created_unix").
diff --git a/models/repo/attachment.go b/models/repo/attachment.go
index 3fb331a202..f5351578fb 100644
--- a/models/repo/attachment.go
+++ b/models/repo/attachment.go
@@ -241,7 +241,7 @@ func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...str
// UpdateAttachmentCtx updates the given attachment in database
func UpdateAttachmentCtx(ctx context.Context, atta *Attachment) error {
- var sess = db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
+ sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
if atta.ID != 0 && atta.UUID == "" {
sess = sess.ID(atta.ID)
} else {
diff --git a/models/repo/mirror.go b/models/repo/mirror.go
index bdb449af3a..e73226534e 100644
--- a/models/repo/mirror.go
+++ b/models/repo/mirror.go
@@ -17,10 +17,8 @@ import (
"xorm.io/xorm"
)
-var (
- // ErrMirrorNotExist mirror does not exist error
- ErrMirrorNotExist = errors.New("Mirror does not exist")
-)
+// ErrMirrorNotExist mirror does not exist error
+var ErrMirrorNotExist = errors.New("Mirror does not exist")
// RemoteMirrorer defines base methods for pull/push mirrors.
type RemoteMirrorer interface {
diff --git a/models/repo/pushmirror.go b/models/repo/pushmirror.go
index 0b62161641..bf39bb1ac0 100644
--- a/models/repo/pushmirror.go
+++ b/models/repo/pushmirror.go
@@ -15,10 +15,8 @@ import (
"xorm.io/xorm"
)
-var (
- // ErrPushMirrorNotExist mirror does not exist error
- ErrPushMirrorNotExist = errors.New("PushMirror does not exist")
-)
+// ErrPushMirrorNotExist mirror does not exist error
+var ErrPushMirrorNotExist = errors.New("PushMirror does not exist")
// PushMirror represents mirror information of a repository.
type PushMirror struct {
diff --git a/models/review_test.go b/models/review_test.go
index 20810dac4a..a4a71cc709 100644
--- a/models/review_test.go
+++ b/models/review_test.go
@@ -199,5 +199,4 @@ func TestDismissReview(t *testing.T) {
assert.False(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.True(t, approveReviewExample.Dismissed)
-
}
diff --git a/models/unittest/testdb.go b/models/unittest/testdb.go
index 6f3a36ed21..c904646d28 100644
--- a/models/unittest/testdb.go
+++ b/models/unittest/testdb.go
@@ -117,10 +117,10 @@ func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) {
fatalTestError("unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
@@ -182,10 +182,10 @@ func PrepareTestEnv(t testing.TB) {
repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
assert.NoError(t, err)
for _, repoDir := range repoDirs {
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
- _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
+ _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
diff --git a/models/user/email_address.go b/models/user/email_address.go
index 0ff62fb6a8..726af7b3b4 100644
--- a/models/user/email_address.go
+++ b/models/user/email_address.go
@@ -21,10 +21,8 @@ import (
"xorm.io/builder"
)
-var (
- // ErrEmailNotActivated e-mail address has not been activated error
- ErrEmailNotActivated = errors.New("E-mail address has not been activated")
-)
+// ErrEmailNotActivated e-mail address has not been activated error
+var ErrEmailNotActivated = errors.New("E-mail address has not been activated")
// ErrEmailInvalid represents an error where the email address does not comply with RFC 5322
type ErrEmailInvalid struct {
diff --git a/modules/activitypub/keypair_test.go b/modules/activitypub/keypair_test.go
index 5d876937b1..defe498614 100644
--- a/modules/activitypub/keypair_test.go
+++ b/modules/activitypub/keypair_test.go
@@ -26,7 +26,6 @@ func TestKeygen(t *testing.T) {
assert.Regexp(t, regexp.MustCompile("^-----BEGIN RSA PRIVATE KEY-----.*"), priv)
assert.Regexp(t, regexp.MustCompile("^-----BEGIN PUBLIC KEY-----.*"), pub)
-
}
func TestSignUsingKeys(t *testing.T) {
diff --git a/modules/appstate/db.go b/modules/appstate/db.go
index a594b01d85..2538d1b5c8 100644
--- a/modules/appstate/db.go
+++ b/modules/appstate/db.go
@@ -12,8 +12,7 @@ import (
)
// DBStore can be used to store app state items in local filesystem
-type DBStore struct {
-}
+type DBStore struct{}
// Get reads the state item
func (f *DBStore) Get(item StateItem) error {
diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go
index 931e5c7945..28546f6031 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 40f38c2d2e..8926fc6d7a 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 73ecae0c2c..30f13e440b 100644
--- a/modules/auth/pam/pam.go
+++ b/modules/auth/pam/pam.go
@@ -27,7 +27,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/webauthn/webauthn.go b/modules/auth/webauthn/webauthn.go
index 8f380e7c34..e39b6f46d6 100644
--- a/modules/auth/webauthn/webauthn.go
+++ b/modules/auth/webauthn/webauthn.go
@@ -17,10 +17,10 @@ import (
"github.com/duo-labs/webauthn/webauthn"
)
-//WebAuthn represents the global WebAuthn instance
+// WebAuthn represents the global WebAuthn instance
var WebAuthn *webauthn.WebAuthn
-//Init initializes the WebAuthn instance from the config.
+// Init initializes the WebAuthn instance from the config.
func Init() {
gob.Register(&webauthn.SessionData{})
@@ -42,14 +42,14 @@ func Init() {
// User represents an implementation of webauthn.User based on User model
type User user_model.User
-//WebAuthnID implements the webauthn.User interface
+// WebAuthnID implements the webauthn.User interface
func (u *User) WebAuthnID() []byte {
id := make([]byte, 8)
binary.PutVarint(id, u.ID)
return id
}
-//WebAuthnName implements the webauthn.User interface
+// WebAuthnName implements the webauthn.User interface
func (u *User) WebAuthnName() string {
if u.LoginName == "" {
return u.Name
@@ -57,17 +57,17 @@ func (u *User) WebAuthnName() string {
return u.LoginName
}
-//WebAuthnDisplayName implements the webauthn.User interface
+// WebAuthnDisplayName implements the webauthn.User interface
func (u *User) WebAuthnDisplayName() string {
return (*user_model.User)(u).DisplayName()
}
-//WebAuthnIcon implements the webauthn.User interface
+// WebAuthnIcon implements the webauthn.User interface
func (u *User) WebAuthnIcon() string {
return (*user_model.User)(u).AvatarLink()
}
-//WebAuthnCredentials implementns the webauthn.User interface
+// WebAuthnCredentials implementns the webauthn.User interface
func (u *User) WebAuthnCredentials() []webauthn.Credential {
dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ID)
if err != nil {
diff --git a/modules/avatar/avatar_test.go b/modules/avatar/avatar_test.go
index b958a9e236..a2acc54438 100644
--- a/modules/avatar/avatar_test.go
+++ b/modules/avatar/avatar_test.go
@@ -61,6 +61,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 dff0d70420..bf53a8ea8a 100644
--- a/modules/base/tool.go
+++ b/modules/base/tool.go
@@ -152,7 +152,7 @@ func PrettyNumber(v int64) string {
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 e7630638bf..0198f8da73 100644
--- a/modules/cache/cache.go
+++ b/modules/cache/cache.go
@@ -16,9 +16,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 92be69252d..f418f77e46 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.go b/modules/charset/charset.go
index ae5cf5aa1a..cf8aa0cb75 100644
--- a/modules/charset/charset.go
+++ b/modules/charset/charset.go
@@ -25,7 +25,7 @@ var UTF8BOM = []byte{'\xef', '\xbb', '\xbf'}
// ToUTF8WithFallbackReader detects the encoding of content and coverts to UTF-8 reader if possible
func ToUTF8WithFallbackReader(rd io.Reader) io.Reader {
- var buf = make([]byte, 2048)
+ buf := make([]byte, 2048)
n, err := util.ReadAtMost(rd, buf)
if err != nil {
return io.MultiReader(bytes.NewReader(RemoveBOMIfPresent(buf[:n])), rd)
diff --git a/modules/charset/charset_test.go b/modules/charset/charset_test.go
index 8957bf3c1c..8376a0698a 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)
diff --git a/modules/context/api.go b/modules/context/api.go
index dae6d23989..c825e48753 100644
--- a/modules/context/api.go
+++ b/modules/context/api.go
@@ -56,29 +56,29 @@ type APIInvalidTopicsError struct {
InvalidTopics []string `json:"invalidTopics"`
}
-//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
@@ -269,13 +269,12 @@ func APIAuth(authMethod auth_service.Method) func(*APIContext) {
// 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{}{},
@@ -354,7 +353,7 @@ func ReferencesGitRepo(allowEmpty bool) func(ctx *APIContext) (cancel context.Ca
// NotFound handles 404s for APIContext
// String will replace message, errors will be added to a slice
func (ctx *APIContext) NotFound(objs ...interface{}) {
- var message = ctx.Tr("error.not_found")
+ message := ctx.Tr("error.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 e7e3e230af..323fdbd2cc 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": {
`<http://localhost:3000/api/v1/repos/jerrykan/example-repo/issues?page=2&state=all>; rel="next"`,
`<http://localhost:3000/api/v1/repos/jerrykan/example-repo/issues?page=5&state=all>; rel="last"`,
diff --git a/modules/context/captcha.go b/modules/context/captcha.go
index b8540136a1..6117d30713 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 ab83ae4eb5..998eafe965 100644
--- a/modules/context/context.go
+++ b/modules/context/context.go
@@ -362,7 +362,7 @@ func (ctx *Context) ServeStream(rd io.Reader, name 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]
}
@@ -606,16 +606,16 @@ func Auth(authMethod auth.Method) func(*Context) {
// 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(), "/")
+ locale := middleware.Locale(resp, req)
+ startTime := time.Now()
+ link := setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/")
- var ctx = Context{
+ ctx := Context{
Resp: NewResponse(resp),
Cache: mc.GetCache(),
Locale: locale,
diff --git a/modules/context/csrf.go b/modules/context/csrf.go
index 8d179ca904..99c223c884 100644
--- a/modules/context/csrf.go
+++ b/modules/context/csrf.go
@@ -57,9 +57,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/private.go b/modules/context/private.go
index 3e31a7e7d8..6e5ef1bd12 100644
--- a/modules/context/private.go
+++ b/modules/context/private.go
@@ -44,9 +44,7 @@ func (ctx *PrivateContext) Err() error {
return ctx.Req.Context().Err()
}
-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 4acb800b64..97b417ffd1 100644
--- a/modules/context/repo.go
+++ b/modules/context/repo.go
@@ -111,7 +111,6 @@ type CanCommitToBranchResults struct {
// and branch is not protected for push
func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.User) (CanCommitToBranchResults, error) {
protectedBranch, err := models.GetProtectedBranchBy(r.Repository.ID, r.BranchName)
-
if err != nil {
return CanCommitToBranchResults{}, err
}
diff --git a/modules/context/response.go b/modules/context/response.go
index a20fc63536..112964dbe1 100644
--- a/modules/context/response.go
+++ b/modules/context/response.go
@@ -17,9 +17,7 @@ type ResponseWriter interface {
Size() int
}
-var (
- _ ResponseWriter = &Response{}
-)
+var _ ResponseWriter = &Response{}
// Response represents a response
type Response struct {
diff --git a/modules/convert/notification.go b/modules/convert/notification.go
index a0bd4cdc27..f304eadf69 100644
--- a/modules/convert/notification.go
+++ b/modules/convert/notification.go
@@ -22,12 +22,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, perm.AccessModeRead)
}
- //handle Subject
+ // handle Subject
switch n.Source {
case models.NotificationSourceIssue:
result.Subject = &api.NotificationSubject{Type: api.NotifySubjectIssue}
@@ -83,7 +83,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 5351b5e172..8574ccfd26 100644
--- a/modules/convert/pull_test.go
+++ b/modules/convert/pull_test.go
@@ -18,7 +18,7 @@ import (
)
func TestPullRequest_APIFormat(t *testing.T) {
- //with HeadRepo
+ // with HeadRepo
assert.NoError(t, unittest.PrepareTestDatabase())
headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest)
@@ -34,7 +34,7 @@ func TestPullRequest_APIFormat(t *testing.T) {
Repository: ToRepo(headRepo, perm.AccessModeRead),
}, apiPullRequest.Head)
- //withOut HeadRepo
+ // withOut HeadRepo
pr = unittest.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 459f98f396..a356925539 100644
--- a/modules/convert/repository.go
+++ b/modules/convert/repository.go
@@ -40,7 +40,7 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo
}
}
- //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 eb77c14dab..1ac2a0f3e1 100644
--- a/modules/convert/status.go
+++ b/modules/convert/status.go
@@ -33,7 +33,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/csv/csv.go b/modules/csv/csv.go
index 47ea62699d..0dd54271f1 100644
--- a/modules/csv/csv.go
+++ b/modules/csv/csv.go
@@ -17,8 +17,10 @@ import (
"code.gitea.io/gitea/modules/util"
)
-const maxLines = 10
-const guessSampleSize = 1e4 // 10k
+const (
+ maxLines = 10
+ guessSampleSize = 1e4 // 10k
+)
// CreateReader creates a csv.Reader with the given delimiter.
func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader {
@@ -35,7 +37,7 @@ func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader {
// CreateReaderAndDetermineDelimiter tries to guess the field delimiter from the content and creates a csv.Reader.
// Reads at most guessSampleSize bytes.
func CreateReaderAndDetermineDelimiter(ctx *markup.RenderContext, rd io.Reader) (*stdcsv.Reader, error) {
- var data = make([]byte, guessSampleSize)
+ data := make([]byte, guessSampleSize)
size, err := util.ReadAtMost(rd, data)
if err != nil {
return nil, err
diff --git a/modules/csv/csv_test.go b/modules/csv/csv_test.go
index 41c4ddaee2..b1e928ae99 100644
--- a/modules/csv/csv_test.go
+++ b/modules/csv/csv_test.go
@@ -31,7 +31,7 @@ func decodeSlashes(t *testing.T, s string) string {
}
func TestCreateReaderAndDetermineDelimiter(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
csv string
expectedRows [][]string
expectedDelimiter rune
@@ -135,7 +135,7 @@ func TestDetermineDelimiterReadAllError(t *testing.T) {
}
func TestDetermineDelimiter(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
csv string
filename string
expectedDelimiter rune
@@ -236,7 +236,7 @@ John Doe john@doe.com This,note,had,a,lot,of,commas,to,test,delimiters`,
}
func TestRemoveQuotedString(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
text string
expectedText string
}{
@@ -301,7 +301,7 @@ abc | |123
}
func TestGuessDelimiter(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
csv string
expectedDelimiter rune
}{
@@ -456,7 +456,7 @@ jkl`,
}
func TestGuessFromBeforeAfterQuotes(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
csv string
expectedDelimiter rune
}{
@@ -562,7 +562,7 @@ func (l mockLocale) TrN(_cnt interface{}, key1, _keyN string, _args ...interface
}
func TestFormatError(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
err error
expectedMessage string
expectsError bool
diff --git a/modules/doctor/fix16961.go b/modules/doctor/fix16961.go
index b929616b38..e241838068 100644
--- a/modules/doctor/fix16961.go
+++ b/modules/doctor/fix16961.go
@@ -296,7 +296,6 @@ func fixBrokenRepoUnits16961(ctx context.Context, logger log.Logger, autofix boo
return repo_model.UpdateRepoUnit(repoUnit)
},
)
-
if err != nil {
logger.Critical("Unable to iterate across repounits to fix the broken units: Error %v", err)
return err
diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go
index cb302c9c5b..ec2fec20b3 100644
--- a/modules/doctor/misc.go
+++ b/modules/doctor/misc.go
@@ -119,7 +119,6 @@ func checkEnablePushOptions(ctx context.Context, logger log.Logger, autofix bool
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 623df863cb..22c095c227 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 85df2d6973..89a86a7f3e 100644
--- a/modules/emoji/emoji.go
+++ b/modules/emoji/emoji.go
@@ -44,9 +44,7 @@ var (
)
func loadMap() {
-
once.Do(func() {
-
// initialize
codeMap = make(map[string]int, len(GemojiData))
aliasMap = make(map[string]int, len(GemojiData))
@@ -87,7 +85,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/git/command_test.go b/modules/git/command_test.go
index 58d616a038..4e257178ef 100644
--- a/modules/git/command_test.go
+++ b/modules/git/command_test.go
@@ -14,7 +14,6 @@ import (
)
func TestRunInDirTimeoutPipelineNoTimeout(t *testing.T) {
-
maxLoops := 1000
// 'git --version' does not block so it must be finished before the timeout triggered.
@@ -27,7 +26,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 8a78653553..0ba53897f5 100644
--- a/modules/git/commit.go
+++ b/modules/git/commit.go
@@ -36,7 +36,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 ccf90fc8c7..ab6e738103 100644
--- a/modules/git/commit_info_gogit.go
+++ b/modules/git/commit_info_gogit.go
@@ -158,7 +158,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 b58c1885b6..347ad7d059 100644
--- a/modules/git/commit_info_nogogit.go
+++ b/modules/git/commit_info_nogogit.go
@@ -104,7 +104,7 @@ func getLastCommitForPathsByCache(ctx context.Context, commitID, treePath string
defer cancel()
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), wr, rd)
if err != nil {
diff --git a/modules/git/commit_info_test.go b/modules/git/commit_info_test.go
index a4c0483004..4cc207de64 100644
--- a/modules/git/commit_info_test.go
+++ b/modules/git/commit_info_test.go
@@ -16,8 +16,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/commit_test.go b/modules/git/commit_test.go
index 2b3365342d..6e9dd34ea7 100644
--- a/modules/git/commit_test.go
+++ b/modules/git/commit_test.go
@@ -234,5 +234,4 @@ func TestParseCommitFileStatus(t *testing.T) {
assert.Equal(t, kase.removed, fileStatus.Removed)
assert.Equal(t, kase.modified, fileStatus.Modified)
}
-
}
diff --git a/modules/git/git.go b/modules/git/git.go
index cca5ce6714..294d33f916 100644
--- a/modules/git/git.go
+++ b/modules/git/git.go
@@ -112,8 +112,8 @@ func SetExecutablePath(path string) error {
// VersionInfo returns git version information
func VersionInfo() string {
- var format = "Git Version: %s"
- var args = []interface{}{gitVersion.Original()}
+ format := "Git Version: %s"
+ args := []interface{}{gitVersion.Original()}
// Since git wire protocol has been released from git v2.18
if setting.Git.EnableAutoGitWireProtocol && CheckGitVersionAtLeast("2.18") == nil {
format += ", Wire Protocol %s Enabled"
diff --git a/modules/git/hook.go b/modules/git/hook.go
index ecd2db3cc3..c50f891224 100644
--- a/modules/git/hook.go
+++ b/modules/git/hook.go
@@ -23,10 +23,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 {
@@ -142,5 +140,5 @@ func SetUpdateHook(repoPath, content string) (err error) {
if err != nil {
return err
}
- return os.WriteFile(hookPath, []byte(content), 0777)
+ return os.WriteFile(hookPath, []byte(content), 0o777)
}
diff --git a/modules/git/last_commit_cache_gogit.go b/modules/git/last_commit_cache_gogit.go
index b57e9ad11f..06e85a6db2 100644
--- a/modules/git/last_commit_cache_gogit.go
+++ b/modules/git/last_commit_cache_gogit.go
@@ -64,7 +64,6 @@ func (c *LastCommitCache) Get(ref, entryPath string) (interface{}, error) {
// CacheCommit will cache the commit from the gitRepository
func (c *LastCommitCache) CacheCommit(ctx context.Context, commit *Commit) error {
-
commitNodeIndex, _ := commit.repo.CommitNodeIndex()
index, err := commitNodeIndex.Get(commit.ID)
diff --git a/modules/git/lfs.go b/modules/git/lfs.go
index 79049c9824..3a809d393d 100644
--- a/modules/git/lfs.go
+++ b/modules/git/lfs.go
@@ -16,8 +16,8 @@ var once sync.Once
// CheckLFSVersion will check lfs version, if not satisfied, then disable it.
func CheckLFSVersion() {
if setting.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 := LoadGitVersion()
if err != nil {
diff --git a/modules/git/parse_nogogit_test.go b/modules/git/parse_nogogit_test.go
index 5f58237de8..d6d6f3868c 100644
--- a/modules/git/parse_nogogit_test.go
+++ b/modules/git/parse_nogogit_test.go
@@ -14,7 +14,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 591ef7362b..6368c6459b 100644
--- a/modules/git/repo.go
+++ b/modules/git/repo.go
@@ -146,7 +146,7 @@ func CloneWithArgs(ctx context.Context, from, to string, args []string, opts Clo
opts.Timeout = -1
}
- var envs = os.Environ()
+ envs := os.Environ()
u, err := url.Parse(from)
if err == nil && (strings.EqualFold(u.Scheme, "http") || strings.EqualFold(u.Scheme, "https")) {
if proxy.Match(u.Host) {
@@ -154,7 +154,7 @@ func CloneWithArgs(ctx context.Context, from, to string, args []string, opts Clo
}
}
- var stderr = new(bytes.Buffer)
+ stderr := new(bytes.Buffer)
if err = cmd.RunWithContext(&RunContext{
Timeout: opts.Timeout,
Env: envs,
diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go
index 0bb550bb4b..d12f0b1099 100644
--- a/modules/git/repo_attribute.go
+++ b/modules/git/repo_attribute.go
@@ -87,7 +87,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_attribute_test.go b/modules/git/repo_attribute_test.go
index 92d1a78fa4..901a0aa244 100644
--- a/modules/git/repo_attribute_test.go
+++ b/modules/git/repo_attribute_test.go
@@ -45,7 +45,7 @@ func Test_nulSeparatedAttributeWriter_ReadAttribute(t *testing.T) {
assert.Fail(t, "took too long to read an attribute from the list")
}
- //Write a partial attribute
+ // Write a partial attribute
_, err = wr.Write([]byte("incomplete-file"))
assert.NoError(t, err)
_, err = wr.Write([]byte("name\x00"))
@@ -133,7 +133,7 @@ func Test_lineSeparatedAttributeWriter_ReadAttribute(t *testing.T) {
assert.Fail(t, "took too long to read an attribute from the list")
}
- //Write a partial attribute
+ // Write a partial attribute
_, err = wr.Write([]byte("incomplete-file"))
assert.NoError(t, err)
_, err = wr.Write([]byte("name: "))
diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go
index ed04ee2f67..0423f15786 100644
--- a/modules/git/repo_commit.go
+++ b/modules/git/repo_commit.go
@@ -88,7 +88,6 @@ func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) {
stdout, err := NewCommandContext(repo.Ctx, "log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize),
"--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunInDirBytes(repo.Path)
-
if err != nil {
return nil, err
}
diff --git a/modules/git/repo_commit_test.go b/modules/git/repo_commit_test.go
index 5943334843..232d6a218c 100644
--- a/modules/git/repo_commit_test.go
+++ b/modules/git/repo_commit_test.go
@@ -90,9 +90,9 @@ func TestRepository_CommitsBetweenIDs(t *testing.T) {
NewID string
ExpectedCommits int
}{
- {"fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", "78a445db1eac62fe15e624e1137965969addf344", 1}, //com1 -> com2
- {"78a445db1eac62fe15e624e1137965969addf344", "fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", 0}, //reset HEAD~, com2 -> com1
- {"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, //com2 -> com2_new
+ {"fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", "78a445db1eac62fe15e624e1137965969addf344", 1}, // com1 -> com2
+ {"78a445db1eac62fe15e624e1137965969addf344", "fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", 0}, // reset HEAD~, com2 -> com1
+ {"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, // com2 -> com2_new
}
for i, c := range cases {
commits, err := bareRepo1.CommitsBetweenIDs(c.NewID, c.OldID)
diff --git a/modules/git/repo_language_stats.go b/modules/git/repo_language_stats.go
index ac23caa0fc..daeb4b591f 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 3921e6a1d4..1d08c6bf79 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 6b5dbeef48..9d1e47a497 100644
--- a/modules/git/repo_tag.go
+++ b/modules/git/repo_tag.go
@@ -174,7 +174,7 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) {
tagNames = util.PaginateSlice(tagNames, page, pageSize).([]string)
}
- 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/submodule_test.go b/modules/git/submodule_test.go
index ff8dc579f6..653f0a6f08 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 71dd866a18..3482f81e90 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 a8d619cd18..be7cb33d35 100644
--- a/modules/git/tree_blob_gogit.go
+++ b/modules/git/tree_blob_gogit.go
@@ -22,7 +22,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 b029c6fc47..d999ccc02a 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/gitgraph/graph_test.go b/modules/gitgraph/graph_test.go
index c805ff4647..e7173b521c 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")
@@ -255,7 +254,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 62e0505652..5432962784 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 8c3b95c4aa..031c10d41b 100644
--- a/modules/graceful/manager.go
+++ b/modules/graceful/manager.go
@@ -190,6 +190,7 @@ func (g *Manager) RunAtHammer(hammer func()) {
hammer()
})
}
+
func (g *Manager) doShutdown() {
if !g.setStateTransition(stateRunning, stateShuttingDown) {
return
diff --git a/modules/highlight/highlight.go b/modules/highlight/highlight.go
index 04bd30bceb..344be78144 100644
--- a/modules/highlight/highlight.go
+++ b/modules/highlight/highlight.go
@@ -83,7 +83,7 @@ func Code(fileName, language, code string) string {
if lexer == nil {
if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
- //use mapped value to find lexer
+ // use mapped value to find lexer
lexer = lexers.Get(val)
}
}
@@ -198,7 +198,7 @@ func File(numLines int, fileName, language string, code []byte) []string {
m := make([]string, 0, numLines)
for _, v := range strings.SplitN(htmlbuf.String(), "\n", numLines) {
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"
} else if content == `</span><span class="w">` {
@@ -220,7 +220,7 @@ func plainText(code string, numLines int) []string {
m := make([]string, 0, numLines)
for _, v := range strings.SplitN(string(code), "\n", numLines) {
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/httpcache/httpcache_test.go b/modules/httpcache/httpcache_test.go
index 68ac892c91..49e54d147e 100644
--- a/modules/httpcache/httpcache_test.go
+++ b/modules/httpcache/httpcache_test.go
@@ -15,8 +15,7 @@ import (
"github.com/stretchr/testify/assert"
)
-type mockFileInfo struct {
-}
+type mockFileInfo struct{}
func (m mockFileInfo) Name() string { return "gitea.test" }
func (m mockFileInfo) Size() int64 { return int64(10) }
diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go
index 64e974dc18..cfadcfebd8 100644
--- a/modules/indexer/code/bleve.go
+++ b/modules/indexer/code/bleve.go
@@ -38,8 +38,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 {
@@ -158,9 +160,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 {
@@ -337,7 +337,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 eb57d4d68a..9bd2fa301e 100644
--- a/modules/indexer/code/elastic_search.go
+++ b/modules/indexer/code/elastic_search.go
@@ -35,9 +35,7 @@ const (
esMultiMatchTypePhrasePrefix = "phrase_prefix"
)
-var (
- _ Indexer = &ElasticSearchIndexer{}
-)
+var _ Indexer = &ElasticSearchIndexer{}
// ElasticSearchIndexer implements Indexer interface
type ElasticSearchIndexer struct {
@@ -131,7 +129,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 {
@@ -327,7 +325,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{})
if err := json.Unmarshal(hit.Source, &res); err != nil {
return 0, nil, nil, err
}
@@ -378,7 +376,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 247354054c..ae73f5690d 100644
--- a/modules/indexer/code/git.go
+++ b/modules/indexer/code/git.go
@@ -73,7 +73,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 a17484cae5..4c7a1d4f17 100644
--- a/modules/indexer/code/indexer.go
+++ b/modules/indexer/code/indexer.go
@@ -78,9 +78,7 @@ type IndexerData struct {
RepoID int64
}
-var (
- indexerQueue queue.UniqueQueue
-)
+var indexerQueue queue.UniqueQueue
func index(ctx context.Context, indexer Indexer, repoID int64) error {
repo, err := repo_model.GetRepositoryByID(repoID)
diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go
index 71d58c08c5..0f9915c84b 100644
--- a/modules/indexer/code/indexer_test.go
+++ b/modules/indexer/code/indexer_test.go
@@ -25,45 +25,43 @@ func testIndexer(name string, t *testing.T, indexer Indexer) {
var repoID int64 = 1
err := index(git.DefaultContext, 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) {
@@ -72,7 +70,7 @@ func testIndexer(name string, t *testing.T, indexer Indexer) {
assert.EqualValues(t, len(kw.IDs), total)
assert.Len(t, langs, kw.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 e7b5b89eef..56baadd6fc 100644
--- a/modules/indexer/code/wrapped.go
+++ b/modules/indexer/code/wrapped.go
@@ -12,9 +12,7 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
)
-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")
@@ -80,7 +78,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 db12874e84..d986a0e55e 100644
--- a/modules/indexer/issues/bleve.go
+++ b/modules/indexer/issues/bleve.go
@@ -156,9 +156,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 {
@@ -256,7 +254,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 036b318d85..df036fb573 100644
--- a/modules/indexer/issues/bleve_test.go
+++ b/modules/indexer/issues/bleve_test.go
@@ -53,43 +53,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 d0cca4fd18..f02cbddce8 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 3af64ed30e..187b69b749 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 ba35e37fd8..ee6ebcdd18 100644
--- a/modules/indexer/issues/indexer_test.go
+++ b/modules/indexer/issues/indexer_test.go
@@ -71,7 +71,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 9d2942a266..e425b95d20 100644
--- a/modules/indexer/stats/db.go
+++ b/modules/indexer/stats/db.go
@@ -15,8 +15,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/endpoint_test.go b/modules/lfs/endpoint_test.go
index a7e8b1bfb7..69f4768650 100644
--- a/modules/lfs/endpoint_test.go
+++ b/modules/lfs/endpoint_test.go
@@ -18,7 +18,7 @@ func str2url(raw string) *url.URL {
func TestDetermineEndpoint(t *testing.T) {
// Test cases
- var cases = []struct {
+ cases := []struct {
cloneurl string
lfsurl string
expected *url.URL
diff --git a/modules/lfs/http_client_test.go b/modules/lfs/http_client_test.go
index 5b514a1230..0ffe663da5 100644
--- a/modules/lfs/http_client_test.go
+++ b/modules/lfs/http_client_test.go
@@ -23,8 +23,7 @@ func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
-type DummyTransferAdapter struct {
-}
+type DummyTransferAdapter struct{}
func (a *DummyTransferAdapter) Name() string {
return "dummy"
@@ -172,7 +171,7 @@ func TestHTTPClientDownload(t *testing.T) {
})}
dummy := &DummyTransferAdapter{}
- var cases = []struct {
+ cases := []struct {
endpoint string
expectederror string
}{
@@ -279,7 +278,7 @@ func TestHTTPClientUpload(t *testing.T) {
})}
dummy := &DummyTransferAdapter{}
- var cases = []struct {
+ cases := []struct {
endpoint string
expectederror string
}{
diff --git a/modules/lfs/pointer_scanner_gogit.go b/modules/lfs/pointer_scanner_gogit.go
index 7e8b812f46..b4ba6fc133 100644
--- a/modules/lfs/pointer_scanner_gogit.go
+++ b/modules/lfs/pointer_scanner_gogit.go
@@ -51,7 +51,6 @@ func SearchPointerBlobs(ctx context.Context, repo *git.Repository, pointerChan c
return nil
})
}()
-
if err != nil {
select {
case <-ctx.Done():
diff --git a/modules/log/colors.go b/modules/log/colors.go
index ad3120ee6c..15e23a0dac 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 158a8ca6ce..1d373506a4 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 bc9d741724..7dc77c0942 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,
@@ -137,7 +137,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 {
@@ -202,7 +202,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
}
@@ -234,7 +234,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 09a07b1e27..c3074b69df 100644
--- a/modules/log/file_test.go
+++ b/modules/log/file_test.go
@@ -27,11 +27,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.True(t, ok)
+ // realFileLogger, ok := fileLogger.(*FileLogger)
+ // assert.True(t, ok)
// Fail if there is bad json
err = fileLogger.Init("{")
@@ -44,7 +44,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) {
@@ -125,7 +124,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()
}
@@ -202,7 +201,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()
}
@@ -217,9 +216,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 d14daa5a20..33f68c8e8e 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 75f361ccdb..0045d79322 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/stack.go b/modules/log/stack.go
index 8fc3f35421..4b40d81ab7 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 e8d06b67ab..1c4f5b4a19 100644
--- a/modules/log/writer.go
+++ b/modules/log/writer.go
@@ -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/markup/common/footnote.go b/modules/markup/common/footnote.go
index 92a54101f0..7b6c57f927 100644
--- a/modules/markup/common/footnote.go
+++ b/modules/markup/common/footnote.go
@@ -178,8 +178,7 @@ func NewFootnoteList() *FootnoteList {
var footnoteListKey = parser.NewContextKey()
-type footnoteBlockParser struct {
-}
+type footnoteBlockParser struct{}
var defaultFootnoteBlockParser = &footnoteBlockParser{}
@@ -265,8 +264,7 @@ func (b *footnoteBlockParser) CanAcceptIndentedLine() bool {
return false
}
-type footnoteParser struct {
-}
+type footnoteParser struct{}
var defaultFootnoteParser = &footnoteParser{}
@@ -337,8 +335,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{}
@@ -357,7 +354,7 @@ func (a *footnoteASTTransformer) Transform(node *ast.Document, reader text.Reade
}
pc.Set(footnoteListKey, nil)
for footnote := list.FirstChild(); footnote != nil; {
- var container ast.Node = footnote
+ container := footnote
next := footnote.NextSibling()
if fc := container.LastChild(); fc != nil && ast.IsParagraph(fc) {
container = fc
diff --git a/modules/markup/common/html.go b/modules/markup/common/html.go
index 3a47686f1e..a2328a2288 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 8a4b2a8985..2140486a30 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() {
@@ -58,7 +59,7 @@ func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Cont
var m []int
var protocol []byte
- var typ ast.AutoLinkType = ast.AutoLinkURL
+ typ := ast.AutoLinkURL
if bytes.HasPrefix(line, protoHTTP) || bytes.HasPrefix(line, protoHTTPS) || bytes.HasPrefix(line, protoFTP) {
m = LinkRegex.FindSubmatchIndex(line)
}
@@ -139,8 +140,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 c1d9d18b67..de32c57a64 100644
--- a/modules/markup/csv/csv.go
+++ b/modules/markup/csv/csv.go
@@ -22,8 +22,7 @@ func init() {
}
// Renderer implements markup.Renderer for csv files
-type Renderer struct {
-}
+type Renderer struct{}
// Name implements markup.Renderer
func (Renderer) Name() string {
@@ -83,7 +82,7 @@ func writeField(w io.Writer, element, class, field string) error {
// Render implements markup.Renderer
func (Renderer) Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
- var tmpBlock = bufio.NewWriter(output)
+ tmpBlock := bufio.NewWriter(output)
// FIXME: don't read all to memory
rawBytes, err := io.ReadAll(input)
diff --git a/modules/markup/csv/csv_test.go b/modules/markup/csv/csv_test.go
index 613762f86c..612f78c76c 100644
--- a/modules/markup/csv/csv_test.go
+++ b/modules/markup/csv/csv_test.go
@@ -15,7 +15,7 @@ import (
func TestRenderCSV(t *testing.T) {
var render Renderer
- var kases = map[string]string{
+ kases := map[string]string{
"a": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>a</th></tr></table>",
"1,2": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>1</th><th>2</th></tr></table>",
"1;2\n3;4": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>1</th><th>2</th></tr><tr><td class=\"line-num\">2</td><td>3</td><td>4</td></tr></table>",
diff --git a/modules/markup/html.go b/modules/markup/html.go
index f082b97dbb..e28e26c6d1 100644
--- a/modules/markup/html.go
+++ b/modules/markup/html.go
@@ -202,7 +202,7 @@ func RenderCommitMessage(
ctx *RenderContext,
content string,
) (string, error) {
- var procs = commitMessageProcessors
+ procs := commitMessageProcessors
if ctx.DefaultLink != "" {
// we don't have to fear data races, because being
// commitMessageProcessors of fixed len and cap, every time we append
@@ -238,7 +238,7 @@ func RenderCommitMessageSubject(
ctx *RenderContext,
content string,
) (string, error) {
- var procs = commitMessageSubjectProcessors
+ procs := commitMessageSubjectProcessors
if ctx.DefaultLink != "" {
// we don't have to fear data races, because being
// commitMessageSubjectProcessors of fixed len and cap, every time we
@@ -291,8 +291,10 @@ func RenderEmoji(
return renderProcessString(&RenderContext{}, emojiProcessors, content)
}
-var tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL]\b)|(/?[hH][eE][aA][dD]\b))`)
-var nulCleaner = strings.NewReplacer("\000", "")
+var (
+ tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL]\b)|(/?[hH][eE][aA][dD]\b))`)
+ nulCleaner = strings.NewReplacer("\000", "")
+)
func postProcess(ctx *RenderContext, procs []processor, input io.Reader, output io.Writer) error {
defer ctx.Cancel()
diff --git a/modules/markup/html_internal_test.go b/modules/markup/html_internal_test.go
index a79b982473..f0eb3253e1 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 TestAppURL = "http://localhost:3000/"
-const TestOrgRepo = "gogits/gogs"
-const TestRepoURL = TestAppURL + TestOrgRepo + "/"
+const (
+ TestAppURL = "http://localhost:3000/"
+ TestOrgRepo = "gogits/gogs"
+ TestRepoURL = TestAppURL + TestOrgRepo + "/"
+)
// 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 2824dca504..ee9b17df2f 100644
--- a/modules/markup/html_test.go
+++ b/modules/markup/html_test.go
@@ -38,17 +38,17 @@ func TestRender_Commits(t *testing.T) {
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer))
}
- var sha = "65f1bf27bc3bf70f64657658635e66094edbcb4d"
- var repo = TestRepoURL
- var commit = util.URLJoin(repo, "commit", sha)
- var tree = util.URLJoin(repo, "tree", sha, "src")
-
- var file = util.URLJoin(repo, "commit", sha, "example.txt")
- var fileWithExtra = file + ":"
- var fileWithHash = file + "#L2"
- var fileWithHasExtra = file + "#L2:"
- var commitCompare = util.URLJoin(repo, "compare", sha+"..."+sha)
- var commitCompareWithHash = commitCompare + "#L2"
+ sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
+ repo := TestRepoURL
+ commit := util.URLJoin(repo, "commit", sha)
+ tree := util.URLJoin(repo, "tree", sha, "src")
+
+ file := util.URLJoin(repo, "commit", sha, "example.txt")
+ fileWithExtra := file + ":"
+ fileWithHash := file + "#L2"
+ fileWithHasExtra := file + "#L2:"
+ commitCompare := util.URLJoin(repo, "compare", sha+"..."+sha)
+ commitCompareWithHash := commitCompare + "#L2"
test(sha, `<p><a href="`+commit+`" rel="nofollow"><code>65f1bf27bc</code></a></p>`)
test(sha[:7], `<p><a href="`+commit[:len(commit)-(40-7)]+`" rel="nofollow"><code>65f1bf2</code></a></p>`)
@@ -102,8 +102,8 @@ func TestRender_CrossReferences(t *testing.T) {
func TestMisc_IsSameDomain(t *testing.T) {
setting.AppURL = TestAppURL
- var sha = "b6dd6210eaebc915fd5be5579c58cce4da2e2579"
- var commit = util.URLJoin(TestRepoURL, "commit", sha)
+ sha := "b6dd6210eaebc915fd5be5579c58cce4da2e2579"
+ commit := util.URLJoin(TestRepoURL, "commit", sha)
assert.True(t, IsSameDomain(commit))
assert.False(t, IsSameDomain("http://google.com/ncr"))
@@ -291,7 +291,7 @@ func TestRender_emoji(t *testing.T) {
`<p><span class="emoji" aria-label="`+emoji.GemojiData[i].Description+`">`+emoji.GemojiData[i].Emoji+`</span></p>`)
}
- //Text that should be turned into or recognized as emoji
+ // Text that should be turned into or recognized as emoji
test(
":gitea:",
`<p><span class="emoji" aria-label="gitea"><img alt=":gitea:" src="`+setting.StaticURLPrefix+`/assets/img/emoji/gitea.png"/></span></p>`)
@@ -472,7 +472,7 @@ func TestRender_RelativeImages(t *testing.T) {
func Test_ParseClusterFuzz(t *testing.T) {
setting.AppURL = TestAppURL
- var localMetas = map[string]string{
+ localMetas := map[string]string{
"user": "go-gitea",
"repo": "gitea",
}
@@ -502,7 +502,7 @@ func Test_ParseClusterFuzz(t *testing.T) {
func TestIssue16020(t *testing.T) {
setting.AppURL = TestAppURL
- 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 83afb8b663..9b6cd3aaef 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",
diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go
index 5ce36a1d16..b45b9c8b8a 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 limitWriter struct {
w io.Writer
@@ -134,7 +138,6 @@ func actualRender(ctx *markup.RenderContext, input io.Reader, output io.Writer)
util.Prioritized(NewHTMLRenderer(), 10),
),
)
-
})
lw := &limitWriter{
@@ -190,10 +193,8 @@ func render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error
return actualRender(ctx, input, output)
}
-var (
- // MarkupName describes markup's name
- MarkupName = "markdown"
-)
+// MarkupName describes markup's name
+var MarkupName = "markdown"
func init() {
markup.RegisterRenderer(Renderer{})
diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go
index 84295b3d4e..54c2ea87d6 100644
--- a/modules/markup/markdown/markdown_test.go
+++ b/modules/markup/markdown/markdown_test.go
@@ -18,9 +18,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{
@@ -120,7 +122,6 @@ func TestRender_Images(t *testing.T) {
test(
"[!["+title+"]("+url+")]("+href+")",
`<p><a href="`+href+`" rel="nofollow"><img src="`+result+`" alt="`+title+`"/></a></p>`)
-
}
func testAnswers(baseURLContent, baseURLImages string) []string {
diff --git a/modules/markup/mdstripper/mdstripper.go b/modules/markup/mdstripper/mdstripper.go
index 2977c81977..64079194ff 100644
--- a/modules/markup/mdstripper/mdstripper.go
+++ b/modules/markup/mdstripper/mdstripper.go
@@ -147,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 13cea0ff72..8045c34c07 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 b035e04a1f..8aa5f45ee2 100644
--- a/modules/markup/orgmode/orgmode.go
+++ b/modules/markup/orgmode/orgmode.go
@@ -27,8 +27,7 @@ func init() {
}
// Renderer implements markup.Renderer for orgmode
-type Renderer struct {
-}
+type Renderer struct{}
// Name implements markup.Renderer
func (Renderer) Name() string {
diff --git a/modules/markup/orgmode/orgmode_test.go b/modules/markup/orgmode/orgmode_test.go
index 38c010ef68..4fc0a20db2 100644
--- a/modules/markup/orgmode/orgmode_test.go
+++ b/modules/markup/orgmode/orgmode_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 + "/"
+)
func TestRender_StandardLinks(t *testing.T) {
setting.AppURL = AppURL
diff --git a/modules/markup/sanitizer.go b/modules/markup/sanitizer.go
index 92dd19f0a1..388af56712 100644
--- a/modules/markup/sanitizer.go
+++ b/modules/markup/sanitizer.go
@@ -86,7 +86,8 @@ func createDefaultPolicy() *bluemonday.Policy {
policy.AllowAttrs("class").Matching(regexp.MustCompile(`^((icon(\s+[\p{L}\p{N}_-]+)+)|(emoji))$|^([a-z][a-z0-9]{0,2})$|^` + keywordClass + `$`)).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/markup/sanitizer_test.go b/modules/markup/sanitizer_test.go
index 64189e1435..a0753c4a56 100644
--- a/modules/markup/sanitizer_test.go
+++ b/modules/markup/sanitizer_test.go
@@ -59,5 +59,4 @@ func TestSanitizeNonEscape(t *testing.T) {
if strings.Contains(string(output), "<script>") {
t.Errorf("un-escaped <script> in output: %q", output)
}
-
}
diff --git a/modules/metrics/collector.go b/modules/metrics/collector.go
index 6463118581..069633a565 100755
--- a/modules/metrics/collector.go
+++ b/modules/metrics/collector.go
@@ -47,7 +47,6 @@ type Collector struct {
// NewCollector returns a new Collector with all prometheus.Desc initialized
func NewCollector() Collector {
-
return Collector{
Accesses: prometheus.NewDesc(
namespace+"accesses",
diff --git a/modules/migration/null_downloader.go b/modules/migration/null_downloader.go
index 69d5ac7b56..6192870873 100644
--- a/modules/migration/null_downloader.go
+++ b/modules/migration/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/migration/retry_downloader.go b/modules/migration/retry_downloader.go
index 1f034ab0c7..1095a26891 100644
--- a/modules/migration/retry_downloader.go
+++ b/modules/migration/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/nosql/redis.go b/modules/nosql/redis.go
index 528f5fc802..13795f3d7b 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 bdf4a50995..ed4ce3dd1a 100644
--- a/modules/notification/action/action.go
+++ b/modules/notification/action/action.go
@@ -25,9 +25,7 @@ type actionNotifier struct {
base.NullNotifier
}
-var (
- _ base.Notifier = &actionNotifier{}
-)
+var _ base.Notifier = &actionNotifier{}
// NewNotifier create a new actionNotifier notifier
func NewNotifier() base.Notifier {
@@ -220,7 +218,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 177864994d..7f5caa3bcc 100644
--- a/modules/notification/base/notifier.go
+++ b/modules/notification/base/notifier.go
@@ -14,14 +14,12 @@ import (
// Notifier defines an interface to notify receiver
type Notifier interface {
Run()
-
- NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository)
- NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository)
+ NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository)
+ NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository)
NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository)
NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository)
NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string)
NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string)
-
NotifyNewIssue(issue *models.Issue, mentions []*user_model.User)
NotifyIssueChangeStatus(*user_model.User, *models.Issue, *models.Comment, bool)
NotifyIssueChangeMilestone(doer *user_model.User, issue *models.Issue, oldMilestoneID int64)
@@ -32,8 +30,7 @@ type Notifier interface {
NotifyIssueChangeTitle(doer *user_model.User, issue *models.Issue, oldTitle string)
NotifyIssueChangeRef(doer *user_model.User, issue *models.Issue, oldRef string)
NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue,
- addedLabels []*models.Label, removedLabels []*models.Label)
-
+ addedLabels, removedLabels []*models.Label)
NotifyNewPullRequest(pr *models.PullRequest, mentions []*user_model.User)
NotifyMergePullRequest(*models.PullRequest, *user_model.User)
NotifyPullRequestSynchronized(doer *user_model.User, pr *models.PullRequest)
@@ -42,23 +39,18 @@ type Notifier interface {
NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *models.PullRequest, oldBranch string)
NotifyPullRequestPushCommits(doer *user_model.User, pr *models.PullRequest, comment *models.Comment)
NotifyPullRevieweDismiss(doer *user_model.User, review *models.Review, comment *models.Comment)
-
NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository,
issue *models.Issue, comment *models.Comment, mentions []*user_model.User)
NotifyUpdateComment(*user_model.User, *models.Comment, string)
NotifyDeleteComment(*user_model.User, *models.Comment)
-
NotifyNewRelease(rel *models.Release)
NotifyUpdateRelease(doer *user_model.User, rel *models.Release)
NotifyDeleteRelease(doer *user_model.User, rel *models.Release)
-
NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits)
NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string)
NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string)
-
NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits)
NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string)
NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string)
-
NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository)
}
diff --git a/modules/notification/base/null.go b/modules/notification/base/null.go
index 9524f02f1b..bd52b843a7 100644
--- a/modules/notification/base/null.go
+++ b/modules/notification/base/null.go
@@ -12,12 +12,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() {
@@ -118,7 +115,7 @@ func (*NullNotifier) NotifyIssueChangeRef(doer *user_model.User, issue *models.I
// NotifyIssueChangeLabels places a place holder function
func (*NullNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue,
- addedLabels []*models.Label, removedLabels []*models.Label) {
+ addedLabels, removedLabels []*models.Label) {
}
// NotifyCreateRepository places a place holder function
diff --git a/modules/notification/indexer/indexer.go b/modules/notification/indexer/indexer.go
index 715ec724c3..26f19e7791 100644
--- a/modules/notification/indexer/indexer.go
+++ b/modules/notification/indexer/indexer.go
@@ -22,9 +22,7 @@ type indexerNotifier struct {
base.NullNotifier
}
-var (
- _ base.Notifier = &indexerNotifier{}
-)
+var _ base.Notifier = &indexerNotifier{}
// NewNotifier create a new indexerNotifier notifier
func NewNotifier() base.Notifier {
diff --git a/modules/notification/mail/mail.go b/modules/notification/mail/mail.go
index b96871597f..94ee16ff8c 100644
--- a/modules/notification/mail/mail.go
+++ b/modules/notification/mail/mail.go
@@ -21,9 +21,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 201f652b3c..a0acd01561 100644
--- a/modules/notification/notification.go
+++ b/modules/notification/notification.go
@@ -18,9 +18,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) {
@@ -203,7 +201,7 @@ func NotifyIssueChangeRef(doer *user_model.User, issue *models.Issue, oldRef str
// NotifyIssueChangeLabels notifies change labels to notifiers
func NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue,
- addedLabels []*models.Label, removedLabels []*models.Label) {
+ addedLabels, removedLabels []*models.Label) {
for _, notifier := range notifiers {
notifier.NotifyIssueChangeLabels(doer, issue, addedLabels, removedLabels)
}
diff --git a/modules/notification/ui/ui.go b/modules/notification/ui/ui.go
index fd44cd15fd..ecedd70193 100644
--- a/modules/notification/ui/ui.go
+++ b/modules/notification/ui/ui.go
@@ -29,9 +29,7 @@ type (
}
)
-var (
- _ base.Notifier = &notificationService{}
-)
+var _ base.Notifier = &notificationService{}
// NewNotifier create a new notificationService notifier
func NewNotifier() base.Notifier {
@@ -55,7 +53,7 @@ func (ns *notificationService) Run() {
func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository,
issue *models.Issue, comment *models.Comment, mentions []*user_model.User) {
- var opts = issueNotificationOpts{
+ opts := issueNotificationOpts{
IssueID: issue.ID,
NotificationAuthorID: doer.ID,
}
@@ -64,7 +62,7 @@ func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, r
}
_ = ns.issueQueue.Push(opts)
for _, mention := range mentions {
- var opts = issueNotificationOpts{
+ opts := issueNotificationOpts{
IssueID: issue.ID,
NotificationAuthorID: doer.ID,
ReceiverID: mention.ID,
@@ -153,7 +151,7 @@ func (ns *notificationService) NotifyNewPullRequest(pr *models.PullRequest, ment
}
func (ns *notificationService) NotifyPullRequestReview(pr *models.PullRequest, r *models.Review, c *models.Comment, mentions []*user_model.User) {
- var opts = issueNotificationOpts{
+ opts := issueNotificationOpts{
IssueID: pr.Issue.ID,
NotificationAuthorID: r.Reviewer.ID,
}
@@ -162,7 +160,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,
@@ -186,7 +184,7 @@ func (ns *notificationService) NotifyPullRequestCodeComment(pr *models.PullReque
}
func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.User, pr *models.PullRequest, comment *models.Comment) {
- var opts = issueNotificationOpts{
+ opts := issueNotificationOpts{
IssueID: pr.IssueID,
NotificationAuthorID: doer.ID,
CommentID: comment.ID,
@@ -195,7 +193,7 @@ func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.Use
}
func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, review *models.Review, comment *models.Comment) {
- var opts = issueNotificationOpts{
+ opts := issueNotificationOpts{
IssueID: review.IssueID,
NotificationAuthorID: doer.ID,
CommentID: comment.ID,
@@ -205,7 +203,7 @@ func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, r
func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User, issue *models.Issue, assignee *user_model.User, removed bool, comment *models.Comment) {
if !removed {
- var opts = issueNotificationOpts{
+ opts := issueNotificationOpts{
IssueID: issue.ID,
NotificationAuthorID: doer.ID,
ReceiverID: assignee.ID,
@@ -221,7 +219,7 @@ func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User,
func (ns *notificationService) NotifyPullReviewRequest(doer *user_model.User, issue *models.Issue, reviewer *user_model.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 39b50b3cd1..ea70faa3c7 100644
--- a/modules/notification/webhook/webhook.go
+++ b/modules/notification/webhook/webhook.go
@@ -29,9 +29,7 @@ type webhookNotifier struct {
base.NullNotifier
}
-var (
- _ base.Notifier = &webhookNotifier{}
-)
+var _ base.Notifier = &webhookNotifier{}
// NewNotifier create a new webhookNotifier notifier
func NewNotifier() base.Notifier {
@@ -497,11 +495,10 @@ func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *mo
if err != nil {
log.Error("PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
}
-
}
func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue,
- addedLabels []*models.Label, removedLabels []*models.Label) {
+ addedLabels, removedLabels []*models.Label) {
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeLabels User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID))
defer finished()
diff --git a/modules/options/dynamic.go b/modules/options/dynamic.go
index 78b0450d9b..e1b9353c33 100644
--- a/modules/options/dynamic.go
+++ b/modules/options/dynamic.go
@@ -17,9 +17,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) {
@@ -27,9 +25,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)
@@ -39,7 +35,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)
}
@@ -55,7 +50,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 afe32216d3..5b61e58f8f 100644
--- a/modules/options/static.go
+++ b/modules/options/static.go
@@ -18,9 +18,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) {
@@ -28,9 +26,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)
@@ -39,7 +35,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)
}
@@ -48,7 +43,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)
}
@@ -69,7 +63,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())
}
@@ -133,7 +127,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 bcf601b029..3efef3bece 100644
--- a/modules/private/mail.go
+++ b/modules/private/mail.go
@@ -50,7 +50,7 @@ func SendEmail(ctx context.Context, subject, message string, to []string) (int,
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 337b0dac64..2543e141ea 100644
--- a/modules/private/manager.go
+++ b/modules/private/manager.go
@@ -170,7 +170,6 @@ func AddLogger(ctx context.Context, group, name, mode string, config map[string]
}
return http.StatusOK, "Added"
-
}
// RemoveLogger removes a logger
diff --git a/modules/private/restore_repo.go b/modules/private/restore_repo.go
index 6ebf4c63d5..6f8eaf927f 100644
--- a/modules/private/restore_repo.go
+++ b/modules/private/restore_repo.go
@@ -44,7 +44,7 @@ func RestoreRepo(ctx context.Context, repoDir, ownerName, repoName string, units
defer resp.Body.Close()
if resp.StatusCode != 200 {
- var ret = struct {
+ ret := struct {
Err string `json:"err"`
}{}
body, err := io.ReadAll(resp.Body)
diff --git a/modules/private/serv.go b/modules/private/serv.go
index a7a56df7b3..e1204c23a7 100644
--- a/modules/private/serv.go
+++ b/modules/private/serv.go
@@ -106,5 +106,4 @@ func ServCommand(ctx context.Context, keyID int64, ownerName, repoName string, m
return nil, err
}
return &results, nil
-
}
diff --git a/modules/process/manager.go b/modules/process/manager.go
index a9a2862958..d9d2f8c3e5 100644
--- a/modules/process/manager.go
+++ b/modules/process/manager.go
@@ -260,7 +260,6 @@ func (pm *Manager) ExecDirEnvStdIn(ctx context.Context, timeout time.Duration, d
}
err := cmd.Wait()
-
if err != nil {
err = &Error{
PID: GetPID(ctx),
diff --git a/modules/process/manager_test.go b/modules/process/manager_test.go
index eb4228e72c..152c7a9235 100644
--- a/modules/process/manager_test.go
+++ b/modules/process/manager_test.go
@@ -90,7 +90,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++ {
@@ -102,7 +101,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 f4a769f27a..91ecf42a3c 100644
--- a/modules/public/public.go
+++ b/modules/public/public.go
@@ -28,7 +28,7 @@ const AssetsURLPathPrefix = "/assets/"
// AssetsHandlerFunc implements the static handler for serving custom or original assets.
func AssetsHandlerFunc(opts *Options) http.HandlerFunc {
- var custPath = filepath.Join(setting.CustomPath, "public")
+ custPath := filepath.Join(setting.CustomPath, "public")
if !filepath.IsAbs(custPath) {
custPath = filepath.Join(setting.AppWorkPath, custPath)
}
@@ -85,7 +85,7 @@ func AssetsHandlerFunc(opts *Options) http.HandlerFunc {
// 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 cf8dced431..430e734564 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 a81efacfa4..d373c712ee 100644
--- a/modules/public/static.go
+++ b/modules/public/static.go
@@ -41,7 +41,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 23e96155a9..e0384d15a3 100644
--- a/modules/queue/manager.go
+++ b/modules/queue/manager.go
@@ -109,8 +109,8 @@ func GetManager() *Manager {
func (m *Manager) Add(managed interface{},
t Type,
configuration,
- exemplar interface{}) int64 {
-
+ exemplar interface{},
+) int64 {
cfg, _ := json.Marshal(configuration)
mq := &ManagedQueue{
Type: t,
@@ -141,7 +141,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
@@ -225,7 +224,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 7159048c11..80a9f1f2c7 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(func())) {}
diff --git a/modules/queue/queue_bytefifo.go b/modules/queue/queue_bytefifo.go
index edde47a62d..c4d5d20a89 100644
--- a/modules/queue/queue_bytefifo.go
+++ b/modules/queue/queue_bytefifo.go
@@ -195,9 +195,11 @@ loop:
}
}
-var errQueueEmpty = fmt.Errorf("empty queue")
-var errEmptyBytes = fmt.Errorf("empty bytes")
-var errUnmarshal = fmt.Errorf("failed to unmarshal")
+var (
+ errQueueEmpty = fmt.Errorf("empty queue")
+ errEmptyBytes = fmt.Errorf("empty bytes")
+ errUnmarshal = fmt.Errorf("failed to unmarshal")
+)
func (q *ByteFIFOQueue) doPop() error {
q.lock.Lock()
diff --git a/modules/queue/queue_disk_channel.go b/modules/queue/queue_disk_channel.go
index c3a1c5781e..f3cd132d7d 100644
--- a/modules/queue/queue_disk_channel.go
+++ b/modules/queue/queue_disk_channel.go
@@ -173,7 +173,6 @@ func (q *PersistableChannelQueue) Run(atShutdown, atTerminate func(func())) {
q.internal.(*LevelQueue).Shutdown()
GetManager().Remove(q.internal.(*LevelQueue).qid)
}
-
}
// Flush flushes the queue and blocks till the queue is empty
diff --git a/modules/queue/queue_disk_channel_test.go b/modules/queue/queue_disk_channel_test.go
index c90d715a73..db12d9575c 100644
--- a/modules/queue/queue_disk_channel_test.go
+++ b/modules/queue/queue_disk_channel_test.go
@@ -188,5 +188,4 @@ func TestPersistableChannelQueue(t *testing.T) {
for _, callback := range callbacks {
callback()
}
-
}
diff --git a/modules/queue/queue_wrapped.go b/modules/queue/queue_wrapped.go
index ec30ab0281..edb589338a 100644
--- a/modules/queue/queue_wrapped.go
+++ b/modules/queue/queue_wrapped.go
@@ -55,7 +55,7 @@ func (q *delayedStarter) setInternal(atShutdown func(func()), handle HandlerFunc
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/unique_queue_disk_channel.go b/modules/queue/unique_queue_disk_channel.go
index af42c0913d..d71f5e2b04 100644
--- a/modules/queue/unique_queue_disk_channel.go
+++ b/modules/queue/unique_queue_disk_channel.go
@@ -197,7 +197,6 @@ func (q *PersistableChannelUniqueQueue) Run(atShutdown, atTerminate func(func())
q.internal.(*LevelUniqueQueue).Shutdown()
GetManager().Remove(q.internal.(*LevelUniqueQueue).qid)
}
-
}
// Flush flushes the queue
diff --git a/modules/queue/workerpool.go b/modules/queue/workerpool.go
index 0176e2e0b2..653d0558c8 100644
--- a/modules/queue/workerpool.go
+++ b/modules/queue/workerpool.go
@@ -341,7 +341,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 74837b8553..630e621043 100644
--- a/modules/references/references.go
+++ b/modules/references/references.go
@@ -371,7 +371,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
diff --git a/modules/references/references_test.go b/modules/references/references_test.go
index 11a31b41b6..adf86a3c6c 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/repository/generate.go b/modules/repository/generate.go
index c7ba617919..5b5e1064aa 100644
--- a/modules/repository/generate.go
+++ b/modules/repository/generate.go
@@ -62,7 +62,7 @@ func generateExpansion(src string, templateRepo, generateRepo *repo_model.Reposi
{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 {
@@ -159,7 +159,7 @@ func generateRepoCommit(ctx context.Context, repo, templateRepo, generateRepo *r
if err := os.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 bd77423afc..debaa0ecc4 100644
--- a/modules/repository/hooks.go
+++ b/modules/repository/hooks.go
@@ -129,7 +129,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 = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
+ if err = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0o777); err != nil {
return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
}
@@ -140,7 +140,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 = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
+ if err = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0o777); err != nil {
return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
}
@@ -157,7 +157,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 {
@@ -165,10 +165,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 c5dd8cb909..d6911161de 100644
--- a/modules/repository/init.go
+++ b/modules/repository/init.go
@@ -62,7 +62,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir,
"OwnerName": repo.OwnerName,
}
if err = os.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)
}
@@ -81,7 +81,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir,
}
if buf.Len() > 0 {
- if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
+ if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0o644); err != nil {
return fmt.Errorf("write .gitignore: %v", err)
}
}
@@ -94,7 +94,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir,
return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err)
}
- if err = os.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
+ if err = os.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 a8d65a4429..22bdf77093 100644
--- a/modules/repository/repo.go
+++ b/modules/repository/repo.go
@@ -310,7 +310,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagN
}
var author *user_model.User
- var createdAt = time.Unix(1, 0)
+ createdAt := time.Unix(1, 0)
if sig != nil {
author, err = user_model.GetUserByEmail(sig.Email)
@@ -325,7 +325,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagN
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/session/db.go b/modules/session/db.go
index 7ba27cba23..f9de37210f 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 := auth.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 409c2b87e5..c3c2c3fafd 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 2bfe2318f5..9a44965124 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 4c7997d584..a843194ff9 100644
--- a/modules/setting/cors.go
+++ b/modules/setting/cors.go
@@ -10,23 +10,21 @@ 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
- XFrameOptions string
- }{
- Enabled: false,
- MaxAge: 10 * time.Minute,
- XFrameOptions: "SAMEORIGIN",
- }
-)
+// CORSConfig defines CORS settings
+var CORSConfig = struct {
+ Enabled bool
+ Scheme string
+ AllowDomain []string
+ AllowSubdomain bool
+ Methods []string
+ MaxAge time.Duration
+ AllowCredentials bool
+ XFrameOptions string
+}{
+ Enabled: false,
+ MaxAge: 10 * time.Minute,
+ XFrameOptions: "SAMEORIGIN",
+}
func newCORSService() {
sec := Cfg.Section("cors")
diff --git a/modules/setting/cron_test.go b/modules/setting/cron_test.go
index 8670a92bac..cb397d81c4 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 8db1cd13eb..5be2d8deea 100644
--- a/modules/setting/database.go
+++ b/modules/setting/database.go
@@ -102,7 +102,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 4cf7e722e7..9b2698f01e 100644
--- a/modules/setting/git.go
+++ b/modules/setting/git.go
@@ -10,63 +10,61 @@ import (
"code.gitea.io/gitea/modules/log"
)
-var (
- // Git settings
- Git = struct {
- Path string
- DisableDiffHighlight bool
- MaxGitDiffLines int
- MaxGitDiffLineCharacters int
- MaxGitDiffFiles int
- CommitsRangeSize int // CommitsRangeSize the default commits range size
- BranchesRangeSize int // BranchesRangeSize the default branches range size
- VerbosePush bool
- VerbosePushDelay time.Duration
- GCArgs []string `ini:"GC_ARGS" delim:" "`
- EnableAutoGitWireProtocol bool
- PullRequestPushMessage bool
- LargeObjectThreshold int64
- DisableCoreProtectNTFS bool
- DisablePartialClone 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 // CommitsRangeSize the default commits range size
+ BranchesRangeSize int // BranchesRangeSize the default branches range size
+ VerbosePush bool
+ VerbosePushDelay time.Duration
+ GCArgs []string `ini:"GC_ARGS" delim:" "`
+ EnableAutoGitWireProtocol bool
+ PullRequestPushMessage bool
+ LargeObjectThreshold int64
+ DisableCoreProtectNTFS bool
+ DisablePartialClone 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,
+ LargeObjectThreshold: 1024 * 1024,
+ DisablePartialClone: false,
+ 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,
- LargeObjectThreshold: 1024 * 1024,
- DisablePartialClone: false,
- Timeout: struct {
- Default int
- Migrate int
- Mirror int
- Clone int
- Pull int
- GC int `ini:"GC"`
- }{
- Default: 360,
- Migrate: 600,
- Mirror: 300,
- Clone: 300,
- Pull: 300,
- GC: 60,
- },
- }
-)
+ Default: 360,
+ Migrate: 600,
+ Mirror: 300,
+ Clone: 300,
+ Pull: 300,
+ GC: 60,
+ },
+}
func newGit() {
if err := Cfg.Section("git").MapTo(&Git); err != nil {
diff --git a/modules/setting/indexer.go b/modules/setting/indexer.go
index f103a7464b..46d4027d14 100644
--- a/modules/setting/indexer.go
+++ b/modules/setting/indexer.go
@@ -14,39 +14,37 @@ import (
"github.com/gobwas/glob"
)
-var (
- // Indexer settings
- Indexer = struct {
- IssueType string
- IssuePath string
- IssueConnStr string
- IssueIndexerName string
- StartupTimeout time.Duration
+// Indexer settings
+var Indexer = struct {
+ IssueType string
+ IssuePath string
+ IssueConnStr string
+ IssueIndexerName string
+ StartupTimeout time.Duration
- RepoIndexerEnabled bool
- RepoType string
- RepoPath string
- RepoConnStr string
- RepoIndexerName string
- MaxIndexerFileSize int64
- IncludePatterns []glob.Glob
- ExcludePatterns []glob.Glob
- ExcludeVendored bool
- }{
- IssueType: "bleve",
- IssuePath: "indexers/issues.bleve",
- IssueConnStr: "",
- IssueIndexerName: "gitea_issues",
+ RepoIndexerEnabled bool
+ RepoType string
+ RepoPath string
+ RepoConnStr string
+ RepoIndexerName string
+ MaxIndexerFileSize int64
+ IncludePatterns []glob.Glob
+ ExcludePatterns []glob.Glob
+ ExcludeVendored bool
+}{
+ IssueType: "bleve",
+ IssuePath: "indexers/issues.bleve",
+ IssueConnStr: "",
+ IssueIndexerName: "gitea_issues",
- 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 ed631747dc..0ff1d814ab 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 7065ce6383..3179a67ce7 100644
--- a/modules/setting/lfs.go
+++ b/modules/setting/lfs.go
@@ -36,7 +36,7 @@ func newLFSService() {
storageType := lfsSec.Key("STORAGE_TYPE").MustString("")
// Specifically default PATH to LFS_CONTENT_PATH
- //FIXME: DEPRECATED to be removed in v1.18.0
+ // FIXME: DEPRECATED to be removed in v1.18.0
deprecatedSetting("server", "LFS_CONTENT_PATH", "lfs", "PATH")
lfsSec.Key("PATH").MustString(
sec.Key("LFS_CONTENT_PATH").String())
diff --git a/modules/setting/log.go b/modules/setting/log.go
index a53b431196..e666e2a027 100644
--- a/modules/setting/log.go
+++ b/modules/setting/log.go
@@ -19,9 +19,11 @@ import (
ini "gopkg.in/ini.v1"
)
-var filenameSuffix = ""
-var descriptionLock = sync.RWMutex{}
-var logDescriptions = make(map[string]*LogDescription)
+var (
+ filenameSuffix = ""
+ descriptionLock = sync.RWMutex{}
+ logDescriptions = make(map[string]*LogDescription)
+)
// GetLogDescriptions returns a race safe set of descriptions
func GetLogDescriptions() map[string]*LogDescription {
@@ -86,7 +88,7 @@ func RemoveSubLogDescription(key, 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
}
diff --git a/modules/setting/mailer.go b/modules/setting/mailer.go
index 5da520171e..8a26f8b0c4 100644
--- a/modules/setting/mailer.go
+++ b/modules/setting/mailer.go
@@ -43,10 +43,8 @@ type Mailer struct {
SendmailConvertCRLF bool
}
-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 0bf6797712..09b86b9b1a 100644
--- a/modules/setting/markup.go
+++ b/modules/setting/markup.go
@@ -123,7 +123,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 34d9037275..4b10f3dc6e 100644
--- a/modules/setting/migrations.go
+++ b/modules/setting/migrations.go
@@ -4,20 +4,18 @@
package setting
-var (
- // Migrations settings
- Migrations = struct {
- MaxAttempts int
- RetryBackoff int
- AllowedDomains string
- BlockedDomains string
- AllowLocalNetworks bool
- SkipTLSVerify bool
- }{
- MaxAttempts: 3,
- RetryBackoff: 3,
- }
-)
+// Migrations settings
+var Migrations = struct {
+ MaxAttempts int
+ RetryBackoff int
+ AllowedDomains string
+ BlockedDomains string
+ AllowLocalNetworks bool
+ SkipTLSVerify bool
+}{
+ MaxAttempts: 3,
+ RetryBackoff: 3,
+}
func newMigrationsService() {
sec := Cfg.Section("migrations")
diff --git a/modules/setting/mime_type_map.go b/modules/setting/mime_type_map.go
index 5c1fc7f71a..8e5b864e24 100644
--- a/modules/setting/mime_type_map.go
+++ b/modules/setting/mime_type_map.go
@@ -6,16 +6,14 @@ package setting
import "strings"
-var (
- // MimeTypeMap defines custom mime type mapping settings
- MimeTypeMap = struct {
- Enabled bool
- Map map[string]string
- }{
- Enabled: false,
- Map: map[string]string{},
- }
-)
+// MimeTypeMap defines custom mime type mapping settings
+var MimeTypeMap = struct {
+ Enabled bool
+ Map map[string]string
+}{
+ Enabled: false,
+ Map: map[string]string{},
+}
func newMimeTypeMap() {
sec := Cfg.Section("repository.mimetype_mapping")
diff --git a/modules/setting/mirror.go b/modules/setting/mirror.go
index e49393e39c..2bd0322d06 100644
--- a/modules/setting/mirror.go
+++ b/modules/setting/mirror.go
@@ -10,22 +10,20 @@ import (
"code.gitea.io/gitea/modules/log"
)
-var (
- // Mirror settings
- Mirror = struct {
- Enabled bool
- DisableNewPull bool
- DisableNewPush bool
- DefaultInterval time.Duration
- MinInterval time.Duration
- }{
- Enabled: true,
- DisableNewPull: false,
- DisableNewPush: false,
- MinInterval: 10 * time.Minute,
- DefaultInterval: 8 * time.Hour,
- }
-)
+// Mirror settings
+var Mirror = struct {
+ Enabled bool
+ DisableNewPull bool
+ DisableNewPush bool
+ DefaultInterval time.Duration
+ MinInterval time.Duration
+}{
+ Enabled: true,
+ DisableNewPull: false,
+ DisableNewPush: false,
+ MinInterval: 10 * time.Minute,
+ DefaultInterval: 8 * time.Hour,
+}
func newMirror() {
// Handle old configuration through `[repository]` `DISABLE_MIRRORS`
diff --git a/modules/setting/proxy.go b/modules/setting/proxy.go
index b99237a398..53fb0066d9 100644
--- a/modules/setting/proxy.go
+++ b/modules/setting/proxy.go
@@ -10,19 +10,17 @@ import (
"code.gitea.io/gitea/modules/log"
)
-var (
- // Proxy settings
- Proxy = struct {
- Enabled bool
- ProxyURL string
- ProxyURLFixed *url.URL
- ProxyHosts []string
- }{
- Enabled: false,
- ProxyURL: "",
- ProxyHosts: []string{},
- }
-)
+// Proxy settings
+var Proxy = struct {
+ Enabled bool
+ ProxyURL string
+ ProxyURLFixed *url.URL
+ ProxyHosts []string
+}{
+ Enabled: false,
+ ProxyURL: "",
+ ProxyHosts: []string{},
+}
func newProxyService() {
sec := Cfg.Section("proxy")
diff --git a/modules/setting/session.go b/modules/setting/session.go
index 9e6193e826..62ca1d82e8 100644
--- a/modules/setting/session.go
+++ b/modules/setting/session.go
@@ -14,33 +14,31 @@ import (
"code.gitea.io/gitea/modules/log"
)
-var (
- // SessionConfig defines 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 defines 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 3c8e009daa..5b8683f578 100644
--- a/modules/setting/setting.go
+++ b/modules/setting/setting.go
@@ -644,7 +644,7 @@ func loadFromConf(allowEmpty bool, extraConfig string) {
}
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)
}
@@ -800,16 +800,16 @@ func loadFromConf(allowEmpty bool, extraConfig string) {
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 := os.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)
}
}
@@ -1080,7 +1080,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)
}
@@ -1173,7 +1173,6 @@ func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte {
},
},
})
-
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 6284f397b1..b576f9573b 100644
--- a/modules/setting/webhook.go
+++ b/modules/setting/webhook.go
@@ -10,27 +10,25 @@ import (
"code.gitea.io/gitea/modules/log"
)
-var (
- // Webhook settings
- Webhook = struct {
- QueueLength int
- DeliverTimeout int
- SkipTLSVerify bool
- AllowedHostList string
- 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
+ AllowedHostList string
+ 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 4f876ec39a..6f4e993457 100644
--- a/modules/ssh/ssh.go
+++ b/modules/ssh/ssh.go
@@ -342,7 +342,6 @@ func Listen(host string, port int, ciphers, keyExchanges, macs []string) {
srv.HostSigners = signers
go listen(&srv)
-
}
// wrapSigner wraps a signer and overrides its public key type with the provided algorithm
@@ -387,7 +386,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
}
@@ -408,7 +407,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 08a7c85752..98fe17b3bc 100644
--- a/modules/ssh/ssh_graceful.go
+++ b/modules/ssh/ssh_graceful.go
@@ -27,7 +27,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 54e0d0563d..022e6186d4 100644
--- a/modules/storage/local.go
+++ b/modules/storage/local.go
@@ -15,9 +15,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 f78ba6aa27..f35f4092a9 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/storage/storage.go b/modules/storage/storage.go
index 2532ceb35d..f11e1ac743 100644
--- a/modules/storage/storage.go
+++ b/modules/storage/storage.go
@@ -16,10 +16,8 @@ import (
"code.gitea.io/gitea/modules/setting"
)
-var (
- // ErrURLNotSupported represents url is not supported
- ErrURLNotSupported = errors.New("url method not supported")
-)
+// ErrURLNotSupported represents url is not supported
+var ErrURLNotSupported = errors.New("url method not supported")
// ErrInvalidConfiguration is called when there is invalid configuration for a storage
type ErrInvalidConfiguration struct {
diff --git a/modules/structs/hook.go b/modules/structs/hook.go
index 163fb5c94d..bb62483cda 100644
--- a/modules/structs/hook.go
+++ b/modules/structs/hook.go
@@ -13,10 +13,8 @@ import (
"code.gitea.io/gitea/modules/json"
)
-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 680277ea60..671885f20a 100644
--- a/modules/structs/repo.go
+++ b/modules/structs/repo.go
@@ -326,19 +326,17 @@ 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,
- OneDevService,
- GitBucketService,
- CodebaseService,
- }
-)
+// 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,
+ OneDevService,
+ GitBucketService,
+ CodebaseService,
+}
// RepoTransfer represents a pending repo transfer
type RepoTransfer struct {
diff --git a/modules/templates/base.go b/modules/templates/base.go
index f3052770ea..282019f826 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 fde58a4a70..c6c47a6c88 100644
--- a/modules/templates/dynamic.go
+++ b/modules/templates/dynamic.go
@@ -71,7 +71,6 @@ func Mailer() (*texttmpl.Template, *template.Template) {
}
content, err := os.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 := os.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 833b582073..255866e2ed 100644
--- a/modules/templates/helper.go
+++ b/modules/templates/helper.go
@@ -213,7 +213,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 {
@@ -286,7 +286,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]
}
@@ -302,7 +302,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))
@@ -478,7 +478,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]
}
@@ -502,8 +502,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
@@ -741,7 +743,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 5b06aaad8f..cb2978c2ef 100644
--- a/modules/templates/static.go
+++ b/modules/templates/static.go
@@ -47,7 +47,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:])
}
@@ -76,7 +76,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
@@ -111,7 +110,6 @@ func Mailer() (*texttmpl.Template, *template.Template) {
}
content, err := os.ReadFile(path.Join(customDir, filePath))
-
if err != nil {
log.Warn("Failed to read custom %s template. %v", filePath, err)
continue
@@ -142,7 +140,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 1bc1d104bc..e6c78bcaa5 100644
--- a/modules/test/context_tests.go
+++ b/modules/test/context_tests.go
@@ -29,8 +29,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{
@@ -42,7 +42,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{},
}
@@ -133,8 +133,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/executable.go b/modules/timeutil/executable.go
index b0a3280753..1875b63349 100644
--- a/modules/timeutil/executable.go
+++ b/modules/timeutil/executable.go
@@ -13,8 +13,10 @@ import (
"code.gitea.io/gitea/modules/log"
)
-var executablModTime = time.Now()
-var executablModTimeOnce sync.Once
+var (
+ executablModTime = time.Now()
+ executablModTimeOnce sync.Once
+)
// GetExecutableModTime get executable file modified time of current process.
func GetExecutableModTime() time.Time {
diff --git a/modules/timeutil/language.go b/modules/timeutil/language.go
index 121b50f277..d0380cac3d 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/typesniffer/typesniffer.go b/modules/typesniffer/typesniffer.go
index 9e29b3557c..e4bed6595a 100644
--- a/modules/typesniffer/typesniffer.go
+++ b/modules/typesniffer/typesniffer.go
@@ -20,8 +20,10 @@ const sniffLen = 1024
// SvgMimeType MIME type of SVG images.
const SvgMimeType = "image/svg+xml"
-var svgTagRegex = regexp.MustCompile(`(?si)\A\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`)
-var svgTagInXMLRegex = regexp.MustCompile(`(?si)\A<\?xml\b.*?\?>\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`)
+var (
+ svgTagRegex = regexp.MustCompile(`(?si)\A\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`)
+ svgTagInXMLRegex = regexp.MustCompile(`(?si)\A<\?xml\b.*?\?>\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`)
+)
// SniffedType contains information about a blobs type.
type SniffedType struct {
diff --git a/modules/updatechecker/update_checker.go b/modules/updatechecker/update_checker.go
index b144166ee9..9c1569b15e 100644
--- a/modules/updatechecker/update_checker.go
+++ b/modules/updatechecker/update_checker.go
@@ -60,7 +60,6 @@ func GiteaUpdateChecker(httpEndpoint string) error {
}
return UpdateRemoteVersion(respData.Latest.Version)
-
}
// UpdateRemoteVersion updates the latest available version of Gitea
diff --git a/modules/util/paginate_test.go b/modules/util/paginate_test.go
index d962e04c16..3657efc919 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_test.go b/modules/util/path_test.go
index 41104f79fc..b0ea448a1c 100644
--- a/modules/util/path_test.go
+++ b/modules/util/path_test.go
@@ -13,7 +13,7 @@ import (
)
func TestFileURLToPath(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
url string
expected string
haserror bool
diff --git a/modules/util/sanitize.go b/modules/util/sanitize.go
index de59ffaa2e..a782fcf512 100644
--- a/modules/util/sanitize.go
+++ b/modules/util/sanitize.go
@@ -9,8 +9,10 @@ import (
"strings"
)
-const userPlaceholder = "sanitized-credential"
-const unparsableURL = "(unparsable url)"
+const (
+ userPlaceholder = "sanitized-credential"
+ unparsableURL = "(unparsable url)"
+)
type sanitizedError struct {
err error
diff --git a/modules/util/sanitize_test.go b/modules/util/sanitize_test.go
index 578f75f518..c141f5e947 100644
--- a/modules/util/sanitize_test.go
+++ b/modules/util/sanitize_test.go
@@ -16,7 +16,7 @@ func TestNewSanitizedError(t *testing.T) {
err2 := NewSanitizedError(err)
assert.Equal(t, err.Error(), err2.Error())
- var cases = []struct {
+ cases := []struct {
input error
oldnew []string
expected string
@@ -43,7 +43,7 @@ func TestNewSanitizedError(t *testing.T) {
}
func TestNewStringURLSanitizer(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
input string
placeholder bool
expected string
@@ -101,7 +101,7 @@ func TestNewStringURLSanitizer(t *testing.T) {
}
func TestNewStringURLSanitizedError(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
input string
placeholder bool
expected string
diff --git a/modules/util/shellquote.go b/modules/util/shellquote.go
index bde24a1517..5a12c2e261 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/truncate.go b/modules/util/truncate.go
index 38c2c0d1d6..2e6f7f68b0 100644
--- a/modules/util/truncate.go
+++ b/modules/util/truncate.go
@@ -7,8 +7,10 @@ package util
import "unicode/utf8"
// in UTF8 "…" is 3 bytes so doesn't really gain us anything...
-const utf8Ellipsis = "…"
-const asciiEllipsis = "..."
+const (
+ utf8Ellipsis = "…"
+ asciiEllipsis = "..."
+)
// SplitStringAtByteN splits a string at byte n accounting for rune boundaries. (Combining characters are not accounted for.)
func SplitStringAtByteN(input string, n int) (left, right string) {
diff --git a/modules/util/util_test.go b/modules/util/util_test.go
index f42b1a930f..e2e26b2627 100644
--- a/modules/util/util_test.go
+++ b/modules/util/util_test.go
@@ -46,7 +46,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 5d5c64611f..7baa36ccc5 100644
--- a/modules/validation/binding.go
+++ b/modules/validation/binding.go
@@ -24,16 +24,13 @@ const (
ErrRegexPattern = "RegexPattern"
)
-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/flash.go b/modules/web/middleware/flash.go
index cd9b089b94..d1d4a864e3 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 ede38ef933..3daf5f32d4 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 86e407701c..4341b1bf5d 100644
--- a/modules/web/route.go
+++ b/modules/web/route.go
@@ -20,7 +20,7 @@ import (
// 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()
}
@@ -28,7 +28,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)
@@ -86,8 +86,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...)
@@ -110,7 +110,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)
@@ -118,7 +118,7 @@ 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...))
}
@@ -126,7 +126,7 @@ func (r *Route) Any(pattern 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...))
}
@@ -134,12 +134,12 @@ func (r *Route) Route(pattern, 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
@@ -147,51 +147,51 @@ 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...))
}
// Options delegate options method
func (r *Route) Options(pattern string, h ...interface{}) {
- var middlewares = r.getMiddlewares(h)
+ middlewares := r.getMiddlewares(h)
r.R.Options(r.getPattern(pattern), Wrap(middlewares...))
}
// GetOptions delegate get and options method
func (r *Route) GetOptions(pattern string, h ...interface{}) {
- var middlewares = r.getMiddlewares(h)
+ middlewares := r.getMiddlewares(h)
r.R.Get(r.getPattern(pattern), Wrap(middlewares...))
r.R.Options(r.getPattern(pattern), Wrap(middlewares...))
}
// PostOptions delegate post and options method
func (r *Route) PostOptions(pattern string, h ...interface{}) {
- var middlewares = r.getMiddlewares(h)
+ middlewares := r.getMiddlewares(h)
r.R.Post(r.getPattern(pattern), Wrap(middlewares...))
r.R.Options(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/modules/web/routing/context.go b/modules/web/routing/context.go
index f57b2e9026..d3c7759e64 100644
--- a/modules/web/routing/context.go
+++ b/modules/web/routing/context.go
@@ -13,7 +13,7 @@ type contextKeyType struct{}
var contextKey contextKeyType
-//UpdateFuncInfo updates a context's func info
+// UpdateFuncInfo updates a context's func info
func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) {
record, ok := ctx.Value(contextKey).(*requestRecord)
if !ok {
@@ -23,7 +23,6 @@ func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) {
record.lock.Lock()
record.funcInfo = funcInfo
record.lock.Unlock()
-
}
// MarkLongPolling marks the reuqest is a long-polling request, and the logger may output different message for it
@@ -38,7 +37,7 @@ func MarkLongPolling(resp http.ResponseWriter, req *http.Request) {
record.lock.Unlock()
}
-//UpdatePanicError updates a context's error info, a panic may be recovered by other middlewares, but we still need to know that.
+// UpdatePanicError updates a context's error info, a panic may be recovered by other middlewares, but we still need to know that.
func UpdatePanicError(ctx context.Context, err interface{}) {
record, ok := ctx.Value(contextKey).(*requestRecord)
if !ok {
diff --git a/modules/web/routing/funcinfo.go b/modules/web/routing/funcinfo.go
index 6d3986e364..9bb38af1c8 100644
--- a/modules/web/routing/funcinfo.go
+++ b/modules/web/routing/funcinfo.go
@@ -12,9 +12,11 @@ import (
"sync"
)
-var funcInfoMap = map[uintptr]*FuncInfo{}
-var funcInfoNameMap = map[string]*FuncInfo{}
-var funcInfoMapMu sync.RWMutex
+var (
+ funcInfoMap = map[uintptr]*FuncInfo{}
+ funcInfoNameMap = map[string]*FuncInfo{}
+ funcInfoMapMu sync.RWMutex
+)
// FuncInfo contains information about the function to be logged by the router log
type FuncInfo struct {
diff --git a/modules/web/routing/logger_manager.go b/modules/web/routing/logger_manager.go
index 31fd09f312..cc434c338d 100644
--- a/modules/web/routing/logger_manager.go
+++ b/modules/web/routing/logger_manager.go
@@ -17,13 +17,13 @@ import (
type Event int
const (
- //StartEvent at the beginning of a request
+ // StartEvent at the beginning of a request
StartEvent Event = iota
- //StillExecutingEvent the request is still executing
+ // StillExecutingEvent the request is still executing
StillExecutingEvent
- //EndEvent the request has ended (either completed or failed)
+ // EndEvent the request has ended (either completed or failed)
EndEvent
)
diff --git a/modules/web/wrap_convert.go b/modules/web/wrap_convert.go
index f2e05de7c1..d4a24b3ad4 100644
--- a/modules/web/wrap_convert.go
+++ b/modules/web/wrap_convert.go
@@ -87,7 +87,7 @@ func convertHandler(handler interface{}) wrappedHandlerFunc {
}
case func(http.Handler) http.Handler:
return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) {
- var next = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
+ next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
if len(others) > 0 {
next = wrapInternal(others)
}
diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go
index bdfe87fd4e..aaa27afb9e 100644
--- a/routers/api/v1/admin/org.go
+++ b/routers/api/v1/admin/org.go
@@ -82,7 +82,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 e95ab33d77..0ecebad5d7 100644
--- a/routers/api/v1/admin/user.go
+++ b/routers/api/v1/admin/user.go
@@ -403,7 +403,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 7a723a138a..df00a852f2 100644
--- a/routers/api/v1/api.go
+++ b/routers/api/v1/api.go
@@ -333,7 +333,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)
@@ -545,12 +545,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(http.StatusUnprocessableEntity, "validationError", fmt.Sprintf("%s: %s", errs[0].FieldNames, errs[0].Error()))
@@ -562,16 +562,16 @@ func bind(obj interface{}) http.HandlerFunc {
// Routes registers all v1 APIs routes to web application.
func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
- var m = web.NewRoute()
+ m := web.NewRoute()
m.Use(sessioner)
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,
AllowedHeaders: []string{"Authorization", "X-CSRFToken", "X-Gitea-OTP"},
diff --git a/routers/api/v1/misc/markdown_test.go b/routers/api/v1/misc/markdown_test.go
index dc6762c4cf..349498e2ab 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/org/hook.go b/routers/api/v1/org/hook.go
index b9d1fa2f67..67957430d1 100644
--- a/routers/api/v1/org/hook.go
+++ b/routers/api/v1/org/hook.go
@@ -123,7 +123,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
}
@@ -161,7 +161,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 133cce3416..1f097225f2 100644
--- a/routers/api/v1/org/org.go
+++ b/routers/api/v1/org/org.go
@@ -25,7 +25,7 @@ func listUserOrgs(ctx *context.APIContext, u *user_model.User) {
listOptions := utils.GetListOptions(ctx)
showPrivate := ctx.IsSigned && (ctx.User.IsAdmin || ctx.User.ID == u.ID)
- var opts = models.FindOrgOptions{
+ opts := models.FindOrgOptions{
ListOptions: listOptions,
UserID: u.ID,
IncludePrivate: showPrivate,
@@ -357,7 +357,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/repo/branch.go b/routers/api/v1/repo/branch.go
index c5480bf2c5..3a0c3201ac 100644
--- a/routers/api/v1/repo/branch.go
+++ b/routers/api/v1/repo/branch.go
@@ -177,23 +177,18 @@ func CreateBranch(ctx *context.APIContext) {
}
err := repo_service.CreateNewBranch(ctx, 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
}
@@ -532,7 +527,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 b0ba5db253..d814ae909e 100644
--- a/routers/api/v1/repo/fork.go
+++ b/routers/api/v1/repo/fork.go
@@ -149,6 +149,6 @@ func CreateFork(ctx *context.APIContext) {
return
}
- //TODO change back to 201
+ // TODO change back to 201
ctx.JSON(http.StatusAccepted, convert.ToRepo(fork, perm.AccessModeOwner))
}
diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go
index 5137c7246e..5ce0c109e6 100644
--- a/routers/api/v1/repo/issue.go
+++ b/routers/api/v1/repo/issue.go
@@ -599,7 +599,7 @@ func CreateIssue(ctx *context.APIContext) {
DeadlineUnix: deadlineUnix,
}
- var assigneeIDs = make([]int64, 0)
+ assigneeIDs := make([]int64, 0)
var err error
if ctx.Repo.CanWrite(unit.TypeIssues) {
issue.MilestoneID = form.Milestone
diff --git a/routers/api/v1/repo/issue_reaction.go b/routers/api/v1/repo/issue_reaction.go
index 6184ea71f0..9c5086700c 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)
}
}
@@ -435,7 +435,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 9c6b4e4647..76c668697e 100644
--- a/routers/api/v1/repo/issue_subscription.go
+++ b/routers/api/v1/repo/issue_subscription.go
@@ -127,7 +127,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", fmt.Errorf("%s is not permitted to change subscriptions for %s", ctx.User.Name, user.Name))
return
@@ -269,7 +269,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 00f8e77feb..79ba59996c 100644
--- a/routers/api/v1/repo/issue_tracked_time.go
+++ b/routers/api/v1/repo/issue_tracked_time.go
@@ -201,7 +201,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 = user_model.GetUserByName(form.User)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
@@ -365,7 +365,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 8a6f421c87..394504a99d 100644
--- a/routers/api/v1/repo/migrate.go
+++ b/routers/api/v1/repo/migrate.go
@@ -56,7 +56,7 @@ func Migrate(ctx *context.APIContext) {
form := web.GetForm(ctx).(*api.MigrateRepoOptions)
- //get repoOwner
+ // get repoOwner
var (
repoOwner *user_model.User
err error
@@ -137,7 +137,7 @@ func Migrate(ctx *context.APIContext) {
}
}
- 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 be1da18c5d..3b4b85158c 100644
--- a/routers/api/v1/repo/milestone.go
+++ b/routers/api/v1/repo/milestone.go
@@ -213,7 +213,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 52ff8425de..a494cb06cc 100644
--- a/routers/api/v1/repo/pull.go
+++ b/routers/api/v1/repo/pull.go
@@ -95,7 +95,6 @@ func ListPullRequests(ctx *context.APIContext) {
Labels: ctx.FormStrings("labels"),
MilestoneID: ctx.FormInt64("milestone"),
})
-
if err != nil {
ctx.Error(http.StatusInternalServerError, "PullRequests", err)
return
diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go
index fe82915a94..b1bc48d30f 100644
--- a/routers/api/v1/repo/release_attachment.go
+++ b/routers/api/v1/repo/release_attachment.go
@@ -178,7 +178,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
}
defer file.Close()
- var filename = header.Filename
+ filename := header.Filename
if query := ctx.FormString("name"); query != "" {
filename = query
}
diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go
index 5f17dc9268..c2dfc4f193 100644
--- a/routers/api/v1/repo/repo.go
+++ b/routers/api/v1/repo/repo.go
@@ -160,7 +160,7 @@ func Search(ctx *context.APIContext) {
opts.Collaborate = util.OptionalBoolFalse
}
- var mode = ctx.FormString("mode")
+ mode := ctx.FormString("mode")
switch mode {
case "source":
opts.Fork = util.OptionalBoolFalse
@@ -186,9 +186,9 @@ func Search(ctx *context.APIContext) {
opts.IsPrivate = util.OptionalBoolOf(ctx.FormBool("is_private"))
}
- var sortMode = ctx.FormString("sort")
+ sortMode := ctx.FormString("sort")
if len(sortMode) > 0 {
- var sortOrder = ctx.FormString("order")
+ sortOrder := ctx.FormString("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 17b49f7f58..652fecefbc 100644
--- a/routers/api/v1/repo/repo_test.go
+++ b/routers/api/v1/repo/repo_test.go
@@ -55,7 +55,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)
@@ -77,7 +77,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 72d790794e..01faf5ad25 100644
--- a/routers/api/v1/repo/status.go
+++ b/routers/api/v1/repo/status.go
@@ -176,7 +176,7 @@ func GetCommitStatusesByRef(ctx *context.APIContext) {
return
}
- getCommitStatuses(ctx, filter) //By default filter is maybe the raw SHA
+ getCommitStatuses(ctx, filter) // By default filter is maybe the raw SHA
}
func getCommitStatuses(ctx *context.APIContext, sha string) {
diff --git a/routers/api/v1/repo/wiki.go b/routers/api/v1/repo/wiki.go
index 94f1dbe0ea..f7054b5067 100644
--- a/routers/api/v1/repo/wiki.go
+++ b/routers/api/v1/repo/wiki.go
@@ -167,7 +167,7 @@ func getWikiPage(ctx *context.APIContext, title string) *api.WikiPage {
return nil
}
- //lookup filename in wiki - get filecontent, real filename
+ // lookup filename in wiki - get filecontent, real filename
content, pageFilename := wikiContentsByName(ctx, commit, title, false)
if ctx.Written() {
return nil
@@ -412,7 +412,7 @@ func ListPageRevisions(ctx *context.APIContext) {
pageName = "Home"
}
- //lookup filename in wiki - get filecontent, gitTree entry , real filename
+ // lookup filename in wiki - get filecontent, gitTree entry , real filename
_, pageFilename := wikiContentsByName(ctx, commit, pageName, false)
if ctx.Written() {
return
@@ -501,7 +501,6 @@ func wikiContentsByEntry(ctx *context.APIContext, entry *git.TreeEntry) string {
func wikiContentsByName(ctx *context.APIContext, commit *git.Commit, wikiName string, isSidebarOrFooter bool) (string, string) {
pageFilename := wiki_service.NameToFilename(wikiName)
entry, err := findEntryForFile(commit, pageFilename)
-
if err != nil {
if git.IsErrNotExist(err) {
if !isSidebarOrFooter {
diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go
index a90e8c30f0..26aeeeabf9 100644
--- a/routers/api/v1/user/gpg_key.go
+++ b/routers/api/v1/user/gpg_key.go
@@ -39,7 +39,7 @@ func listGPGKeys(ctx *context.APIContext, uid int64, listOptions db.ListOptions)
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
// ---
@@ -71,7 +71,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
// ---
@@ -94,7 +94,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
// ---
@@ -212,7 +212,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
// ---
@@ -233,7 +233,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 6c3e1c86fa..49b1d47d95 100644
--- a/routers/api/v1/user/watch.go
+++ b/routers/api/v1/user/watch.go
@@ -170,7 +170,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/api/v1/utils/git.go b/routers/api/v1/utils/git.go
index a941c1fc2c..f7a7fe83c9 100644
--- a/routers/api/v1/utils/git.go
+++ b/routers/api/v1/utils/git.go
@@ -50,12 +50,12 @@ func GetGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, strin
}
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/common/middleware.go b/routers/common/middleware.go
index 2b6343b10f..880700969a 100644
--- a/routers/common/middleware.go
+++ b/routers/common/middleware.go
@@ -21,7 +21,7 @@ import (
// Middlewares returns common middlewares
func Middlewares() []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) {
// First of all escape the URL RawPath to ensure that all routing is done using a correctly escaped URL
diff --git a/routers/install/install.go b/routers/install/install.go
index 230f6e0602..043fae26de 100644
--- a/routers/install/install.go
+++ b/routers/install/install.go
@@ -54,7 +54,7 @@ func getDbTypeNames() []map[string]string {
// Init prepare for rendering installation page
func Init(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 {
@@ -62,9 +62,9 @@ func Init(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,
diff --git a/routers/install/routes.go b/routers/install/routes.go
index d7d8527cf5..f377cd40c9 100644
--- a/routers/install/routes.go
+++ b/routers/install/routes.go
@@ -28,7 +28,7 @@ func (d *dataStore) GetData() map[string]interface{} {
}
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() {
@@ -53,7 +53,7 @@ func installRecovery() func(next http.Handler) http.Handler {
log.Error("%s", combinedErr)
lc := middleware.Locale(w, req)
- var store = dataStore{
+ store := dataStore{
"Language": lc.Language(),
"CurrentURL": setting.AppSubURL + req.URL.RequestURI(),
"i18n": lc,
diff --git a/routers/private/internal.go b/routers/private/internal.go
index 4960f561c1..263180bd58 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 f00f202207..402bade5d4 100644
--- a/routers/private/manager_unix.go
+++ b/routers/private/manager_unix.go
@@ -18,7 +18,6 @@ import (
func Restart(ctx *context.PrivateContext) {
graceful.GetManager().DoGracefulRestart()
ctx.PlainText(http.StatusOK, "success")
-
}
// Shutdown causes the server to perform a graceful shutdown
diff --git a/routers/private/restore_repo.go b/routers/private/restore_repo.go
index 85aada192f..8dfe569325 100644
--- a/routers/private/restore_repo.go
+++ b/routers/private/restore_repo.go
@@ -23,7 +23,7 @@ func RestoreRepo(ctx *myCtx.PrivateContext) {
})
return
}
- var params = struct {
+ params := struct {
RepoDir string
OwnerName string
RepoName string
diff --git a/routers/web/admin/admin.go b/routers/web/admin/admin.go
index 7e25f96ee0..276e1939ad 100644
--- a/routers/web/admin/admin.go
+++ b/routers/web/admin/admin.go
@@ -209,7 +209,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/web/admin/admin_test.go b/routers/web/admin/admin_test.go
index da404e50d7..1bc43998b2 100644
--- a/routers/web/admin/admin_test.go
+++ b/routers/web/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/web/admin/emails.go b/routers/web/admin/emails.go
index cbf0ec5e98..b94f9d72c4 100644
--- a/routers/web/admin/emails.go
+++ b/routers/web/admin/emails.go
@@ -101,9 +101,7 @@ func Emails(ctx *context.Context) {
ctx.HTML(http.StatusOK, tplEmails)
}
-var (
- nullByte = []byte{0x00}
-)
+var nullByte = []byte{0x00}
func isKeywordValid(keyword string) bool {
return !bytes.Contains([]byte(keyword), nullByte)
@@ -111,7 +109,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.FormInt64("uid")
diff --git a/routers/web/admin/users_test.go b/routers/web/admin/users_test.go
index 1849781bc4..46133688a5 100644
--- a/routers/web/admin/users_test.go
+++ b/routers/web/admin/users_test.go
@@ -19,7 +19,6 @@ import (
)
func TestNewUserPost_MustChangePassword(t *testing.T) {
-
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "admin/users/new")
diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go
index d6b3635584..ce8ec8a1e3 100644
--- a/routers/web/auth/auth.go
+++ b/routers/web/auth/auth.go
@@ -297,7 +297,7 @@ func handleSignIn(ctx *context.Context, u *user_model.User, remember bool) {
ctx.Redirect(redirect)
}
-func handleSignInFull(ctx *context.Context, u *user_model.User, remember bool, obeyRedirect bool) string {
+func handleSignInFull(ctx *context.Context, u *user_model.User, remember, obeyRedirect bool) string {
if remember {
days := 86400 * setting.LogInRememberDays
ctx.SetCookie(setting.CookieUserName, u.Name, days)
@@ -417,7 +417,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(http.StatusOK, tplSignUp)
@@ -438,7 +438,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(http.StatusForbidden)
return
diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go
index 27eb954a58..bf5fb83265 100644
--- a/routers/web/auth/linkaccount.go
+++ b/routers/web/auth/linkaccount.go
@@ -27,9 +27,7 @@ import (
"github.com/markbates/goth"
)
-var (
- tplLinkAccount base.TplName = "user/auth/link_account"
-)
+var tplLinkAccount base.TplName = "user/auth/link_account"
// LinkAccount shows the page where the user can decide to login or create a new account
func LinkAccount(ctx *context.Context) {
diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go
index fa2b0aa65f..7bf1adf308 100644
--- a/routers/web/auth/oauth.go
+++ b/routers/web/auth/oauth.go
@@ -1158,5 +1158,4 @@ func oAuth2UserLoginCallback(authSource *auth.Source, request *http.Request, res
// no user found to login
return nil, gothUser, nil
-
}
diff --git a/routers/web/auth/openid.go b/routers/web/auth/openid.go
index 4395641795..e0c6069546 100644
--- a/routers/web/auth/openid.go
+++ b/routers/web/auth/openid.go
@@ -67,7 +67,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 {
@@ -144,13 +143,12 @@ func SignInOpenIDPost(ctx *context.Context) {
// signInOpenIDVerify handles response from OpenID provider
func signInOpenIDVerify(ctx *context.Context) {
-
log.Trace("Incoming call to: %s", ctx.Req.URL.String())
fullURL := setting.AppURL + ctx.Req.URL.String()[1:]
log.Trace("Full URL: %s", fullURL)
- var id, err = openid.Verify(fullURL)
+ id, err := openid.Verify(fullURL)
if err != nil {
ctx.RenderWithErr(err.Error(), tplSignInOpenID, &forms.SignInOpenIDForm{
Openid: id,
diff --git a/routers/web/auth/webauthn.go b/routers/web/auth/webauthn.go
index 77b1bee18a..bedbe7ddc3 100644
--- a/routers/web/auth/webauthn.go
+++ b/routers/web/auth/webauthn.go
@@ -33,7 +33,7 @@ func WebAuthn(ctx *context.Context) {
return
}
- //Ensure user is in a 2FA session.
+ // Ensure user is in a 2FA session.
if ctx.Session.Get("twofaUid") == nil {
ctx.ServerError("UserSignIn", errors.New("not in WebAuthn session"))
return
diff --git a/routers/web/base.go b/routers/web/base.go
index fd942d3c87..f7eb003cc4 100644
--- a/routers/web/base.go
+++ b/routers/web/base.go
@@ -92,7 +92,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) {
@@ -125,7 +125,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() {
@@ -136,14 +136,14 @@ func Recovery() func(next http.Handler) http.Handler {
sessionStore := session.GetSession(req)
- var lc = middleware.Locale(w, req)
- var store = dataStore{
+ lc := middleware.Locale(w, req)
+ store := dataStore{
"Language": lc.Language(),
"CurrentURL": setting.AppSubURL + req.URL.RequestURI(),
"i18n": lc,
}
- var user = context.GetContextUser(req)
+ user := context.GetContextUser(req)
if user == nil {
// Get user from session if logged in - do not attempt to sign-in
user = auth.SessionUser(sessionStore)
diff --git a/routers/web/explore/code.go b/routers/web/explore/code.go
index b61f25a96c..d2acefde92 100644
--- a/routers/web/explore/code.go
+++ b/routers/web/explore/code.go
@@ -76,7 +76,7 @@ func Code(ctx *context.Context) {
return
}
- var rightRepoMap = make(map[int64]*repo_model.Repository, len(repoMaps))
+ rightRepoMap := make(map[int64]*repo_model.Repository, len(repoMaps))
repoIDs = make([]int64, 0, len(repoMaps))
for id, repo := range repoMaps {
if models.CheckRepoUnitUser(repo, ctx.User, unit.TypeCode) {
@@ -100,7 +100,7 @@ func Code(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/web/explore/user.go b/routers/web/explore/user.go
index 27634c3d4e..b264bf1b4a 100644
--- a/routers/web/explore/user.go
+++ b/routers/web/explore/user.go
@@ -25,9 +25,7 @@ const (
// UserSearchDefaultSortType is the default sort type for user search
const UserSearchDefaultSortType = "alphabetically"
-var (
- nullByte = []byte{0x00}
-)
+var nullByte = []byte{0x00}
func isKeywordValid(keyword string) bool {
return !bytes.Contains([]byte(keyword), nullByte)
diff --git a/routers/web/org/home.go b/routers/web/org/home.go
index 43f6211af3..cf23a1e291 100644
--- a/routers/web/org/home.go
+++ b/routers/web/org/home.go
@@ -110,7 +110,7 @@ func Home(ctx *context.Context) {
return
}
- var opts = &models.FindOrgMembersOpts{
+ opts := &models.FindOrgMembersOpts{
OrgID: org.ID,
PublicOnly: true,
ListOptions: db.ListOptions{Page: 1, PageSize: 25},
diff --git a/routers/web/org/members.go b/routers/web/org/members.go
index e9b7317c98..b8e7fa1ff5 100644
--- a/routers/web/org/members.go
+++ b/routers/web/org/members.go
@@ -31,7 +31,7 @@ func Members(ctx *context.Context) {
page = 1
}
- var opts = &models.FindOrgMembersOpts{
+ opts := &models.FindOrgMembersOpts{
OrgID: org.ID,
PublicOnly: true,
}
diff --git a/routers/web/org/setting.go b/routers/web/org/setting.go
index 747a5134b4..404aac8894 100644
--- a/routers/web/org/setting.go
+++ b/routers/web/org/setting.go
@@ -117,7 +117,8 @@ func SettingsPost(ctx *context.Context) {
// update forks visibility
if visibilityChanged {
repos, _, err := models.GetUserRepositories(&models.SearchRepoOptions{
- Actor: org.AsUser(), Private: true, ListOptions: db.ListOptions{Page: 1, PageSize: org.NumRepos}})
+ Actor: org.AsUser(), Private: true, ListOptions: db.ListOptions{Page: 1, PageSize: org.NumRepos},
+ })
if err != nil {
ctx.ServerError("GetRepositories", err)
return
diff --git a/routers/web/repo/attachment.go b/routers/web/repo/attachment.go
index 303eee24d1..4101d81ac5 100644
--- a/routers/web/repo/attachment.go
+++ b/routers/web/repo/attachment.go
@@ -100,12 +100,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())
@@ -123,7 +123,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 {
@@ -136,7 +136,7 @@ func GetAttachment(ctx *context.Context) {
return
}
- //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/web/repo/blame.go b/routers/web/repo/blame.go
index bff6a039e8..588e432e3a 100644
--- a/routers/web/repo/blame.go
+++ b/routers/web/repo/blame.go
@@ -233,12 +233,12 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m
language = ""
}
}
- var lines = make([]string, 0)
+ lines := make([]string, 0)
rows := make([]*blameRow, 0)
escapeStatus := charset.EscapeStatus{}
- var i = 0
- var commitCnt = 0
+ i := 0
+ commitCnt := 0
for _, part := range blameParts {
for index, line := range part.Lines {
i++
diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go
index ed1b2a9b1a..5d19fd1185 100644
--- a/routers/web/repo/branch.go
+++ b/routers/web/repo/branch.go
@@ -203,7 +203,7 @@ func loadBranches(ctx *context.Context, skip, limit int) (*Branch, []*Branch, in
continue
}
- var branch = loadOneBranch(ctx, rawBranches[i], defaultBranch, protectedBranches, repoIDToRepo, repoIDToGitRepo)
+ branch := loadOneBranch(ctx, rawBranches[i], defaultBranch, protectedBranches, repoIDToRepo, repoIDToGitRepo)
if branch == nil {
return nil, nil, 0
}
diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go
index 22e6be2021..cdb6f9d7fe 100644
--- a/routers/web/repo/compare.go
+++ b/routers/web/repo/compare.go
@@ -111,7 +111,7 @@ func setCsvCompareContext(ctx *context.Context) {
Error string
}
- ctx.Data["CreateCsvDiff"] = func(diffFile *gitdiff.DiffFile, baseCommit *git.Commit, headCommit *git.Commit) CsvDiffResult {
+ ctx.Data["CreateCsvDiff"] = func(diffFile *gitdiff.DiffFile, baseCommit, headCommit *git.Commit) CsvDiffResult {
if diffFile == nil || baseCommit == nil || headCommit == nil {
return CsvDiffResult{nil, ""}
}
@@ -541,8 +541,8 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo {
func PrepareCompareDiff(
ctx *context.Context,
ci *CompareInfo,
- whitespaceBehavior string) bool {
-
+ whitespaceBehavior string,
+) bool {
var (
repo = ctx.Repo.Repository
err error
@@ -839,7 +839,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" {
diff --git a/routers/web/repo/download.go b/routers/web/repo/download.go
index 430de24c69..72d34cb937 100644
--- a/routers/web/repo/download.go
+++ b/routers/web/repo/download.go
@@ -52,7 +52,7 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob) error {
}
if setting.LFS.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.LFS.URL(pointer.RelativePath(), blob.Name())
if u != nil && err == nil {
ctx.Redirect(u.String())
diff --git a/routers/web/repo/editor_test.go b/routers/web/repo/editor_test.go
index 77f94ff550..ab7532ebb5 100644
--- a/routers/web/repo/editor_test.go
+++ b/routers/web/repo/editor_test.go
@@ -17,7 +17,7 @@ import (
func TestCleanUploadName(t *testing.T) {
unittest.PrepareTestEnv(t)
- var kases = map[string]string{
+ kases := map[string]string{
".git/refs/master": "",
"/root/abc": "root/abc",
"./../../abc": "abc",
diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go
index 5e73843920..3805ceea76 100644
--- a/routers/web/repo/http.go
+++ b/routers/web/repo/http.go
@@ -104,7 +104,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {
}
isWiki := false
- var unitType = unit.TypeCode
+ unitType := unit.TypeCode
var wikiRepoName string
if strings.HasSuffix(reponame, ".wiki") {
isWiki = true
@@ -457,7 +457,6 @@ func serviceRPC(ctx gocontext.Context, h serviceHandler, service string) {
if err := h.r.Body.Close(); err != nil {
log.Error("serviceRPC: Close: %v", err)
}
-
}()
if !hasAccess(ctx, service, h, true) {
@@ -468,7 +467,7 @@ func serviceRPC(ctx gocontext.Context, 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/web/repo/issue.go b/routers/web/repo/issue.go
index ba871127f7..aff5fa8498 100644
--- a/routers/web/repo/issue.go
+++ b/routers/web/repo/issue.go
@@ -57,17 +57,15 @@ const (
issueTemplateTitleKey = "IssueTemplateTitle"
)
-var (
- // IssueTemplateCandidates issue templates
- IssueTemplateCandidates = []string{
- "ISSUE_TEMPLATE.md",
- "issue_template.md",
- ".gitea/ISSUE_TEMPLATE.md",
- ".gitea/issue_template.md",
- ".github/ISSUE_TEMPLATE.md",
- ".github/issue_template.md",
- }
-)
+// IssueTemplateCandidates issue templates
+var IssueTemplateCandidates = []string{
+ "ISSUE_TEMPLATE.md",
+ "issue_template.md",
+ ".gitea/ISSUE_TEMPLATE.md",
+ ".gitea/issue_template.md",
+ ".github/ISSUE_TEMPLATE.md",
+ ".github/issue_template.md",
+}
// MustAllowUserComment checks to make sure if an issue is locked.
// If locked and user has permissions to write to the repository,
@@ -245,7 +243,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
}
}
- var issueList = models.IssueList(issues)
+ issueList := models.IssueList(issues)
approvalCounts, err := issueList.GetApprovalCounts()
if err != nil {
ctx.ServerError("ApprovalCounts", err)
@@ -311,8 +309,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
assigneeID = 0 // Reset ID to prevent unexpected selection of assignee.
}
- ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] =
- issue_service.GetRefEndNamesAndURLs(issues, ctx.Repo.RepoLink)
+ ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, ctx.Repo.RepoLink)
ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 {
counts, ok := approvalCounts[issueID]
@@ -442,7 +439,6 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.R
}
func retrieveProjects(ctx *context.Context, repo *repo_model.Repository) {
-
var err error
ctx.Data["OpenProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{
@@ -2508,7 +2504,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])
}
@@ -2522,7 +2518,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)
@@ -2667,7 +2663,7 @@ func handleTeamMentions(ctx *context.Context) {
var isAdmin bool
var err error
var teams []*models.Team
- var org = models.OrgFromUser(ctx.Repo.Owner)
+ org := models.OrgFromUser(ctx.Repo.Owner)
// Admin has super access.
if ctx.User.IsAdmin {
isAdmin = true
diff --git a/routers/web/repo/issue_content_history.go b/routers/web/repo/issue_content_history.go
index 08eb98acb8..75951ca25b 100644
--- a/routers/web/repo/issue_content_history.go
+++ b/routers/web/repo/issue_content_history.go
@@ -83,8 +83,8 @@ func GetContentHistoryList(ctx *context.Context) {
// canSoftDeleteContentHistory checks whether current user can soft-delete a history revision
// Admins or owners can always delete history revisions. Normal users can only delete own history revisions.
func canSoftDeleteContentHistory(ctx *context.Context, issue *models.Issue, comment *models.Comment,
- history *issuesModel.ContentHistory) bool {
-
+ history *issuesModel.ContentHistory,
+) bool {
canSoftDelete := false
if ctx.Repo.IsOwner() {
canSoftDelete = true
@@ -103,7 +103,7 @@ func canSoftDeleteContentHistory(ctx *context.Context, issue *models.Issue, comm
return canSoftDelete
}
-//GetContentHistoryDetail get detail
+// GetContentHistoryDetail get detail
func GetContentHistoryDetail(ctx *context.Context) {
issue := GetActionIssue(ctx)
if issue == nil {
@@ -169,7 +169,7 @@ func GetContentHistoryDetail(ctx *context.Context) {
})
}
-//SoftDeleteContentHistory soft delete
+// SoftDeleteContentHistory soft delete
func SoftDeleteContentHistory(ctx *context.Context) {
issue := GetActionIssue(ctx)
if issue == nil {
diff --git a/routers/web/repo/issue_lock.go b/routers/web/repo/issue_lock.go
index 36894b4be3..103b60c65d 100644
--- a/routers/web/repo/issue_lock.go
+++ b/routers/web/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/web/repo/issue_test.go b/routers/web/repo/issue_test.go
index b8862cf43d..debd2a8a3c 100644
--- a/routers/web/repo/issue_test.go
+++ b/routers/web/repo/issue_test.go
@@ -13,7 +13,7 @@ import (
)
func TestCombineLabelComments(t *testing.T) {
- var kases = []struct {
+ kases := []struct {
name string
beforeCombined []*models.Comment
afterCombined []*models.Comment
@@ -366,7 +366,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/web/repo/lfs.go b/routers/web/repo/lfs.go
index 6b5e1dd624..2cb4330c08 100644
--- a/routers/web/repo/lfs.go
+++ b/routers/web/repo/lfs.go
@@ -305,7 +305,7 @@ func LFSFileGet(ctx *context.Context) {
var output bytes.Buffer
lines := strings.Split(escapedContent.String(), "\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]
}
@@ -536,7 +536,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/web/repo/migrate.go b/routers/web/repo/migrate.go
index 23e5b21b48..9a31d809d4 100644
--- a/routers/web/repo/migrate.go
+++ b/routers/web/repo/migrate.go
@@ -203,7 +203,7 @@ func MigratePost(ctx *context.Context) {
}
}
- var opts = migrations.MigrateOptions{
+ opts := migrations.MigrateOptions{
OriginalURL: form.CloneAddr,
GitServiceType: form.Service,
CloneAddr: remoteAddr,
diff --git a/routers/web/repo/projects.go b/routers/web/repo/projects.go
index f6be8add0b..3836a00d04 100644
--- a/routers/web/repo/projects.go
+++ b/routers/web/repo/projects.go
@@ -531,7 +531,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
diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go
index 517156863e..0aea66ca67 100644
--- a/routers/web/repo/pull.go
+++ b/routers/web/repo/pull.go
@@ -48,16 +48,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) *repo_model.Repository {
repo, err := repo_model.GetRepositoryByID(repoID)
@@ -125,7 +123,7 @@ func getForkRepository(ctx *context.Context) *repo_model.Repository {
}
}
- var traverseParentRepo = forkRepo
+ traverseParentRepo := forkRepo
for {
if ctx.User.ID == traverseParentRepo.OwnerID {
canForkToUser = false
@@ -195,7 +193,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)
@@ -1085,7 +1083,6 @@ func MergePullRequest(ctx *context.Context) {
}
func stopTimerIfAvailable(user *user_model.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/web/repo/release.go b/routers/web/repo/release.go
index 13623e15ef..4f58ac9546 100644
--- a/routers/web/repo/release.go
+++ b/routers/web/repo/release.go
@@ -481,7 +481,7 @@ func EditReleasePost(ctx *context.Context) {
const delPrefix = "attachment-del-"
const editPrefix = "attachment-edit-"
var addAttachmentUUIDs, delAttachmentUUIDs []string
- var editAttachments = make(map[string]string) // uuid -> new name
+ editAttachments := make(map[string]string) // uuid -> new name
if setting.Attachment.Enabled {
addAttachmentUUIDs = form.Files
for k, v := range ctx.Req.Form {
diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go
index 6bd16ff2b8..89ebef3a59 100644
--- a/routers/web/repo/repo.go
+++ b/routers/web/repo/repo.go
@@ -410,7 +410,7 @@ func Download(ctx *context.Context) {
}
var times int
- var t = time.NewTicker(time.Second * 1)
+ t := time.NewTicker(time.Second * 1)
defer t.Stop()
for {
@@ -447,7 +447,7 @@ func download(ctx *context.Context, archiveName string, archiver *repo_model.Rep
}
if setting.RepoArchive.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.RepoArchives.URL(rPath, downloadName)
if u != nil && err == nil {
ctx.Redirect(u.String())
@@ -455,7 +455,7 @@ func download(ctx *context.Context, archiveName string, archiver *repo_model.Rep
}
}
- //If we have matched and access to release or issue
+ // If we have matched and access to release or issue
fr, err := storage.RepoArchives.Open(rPath)
if err != nil {
ctx.ServerError("Open", err)
diff --git a/routers/web/repo/settings_test.go b/routers/web/repo/settings_test.go
index 5b62e1ed16..bd29eca195 100644
--- a/routers/web/repo/settings_test.go
+++ b/routers/web/repo/settings_test.go
@@ -100,7 +100,6 @@ func TestAddReadWriteOnlyDeployKey(t *testing.T) {
}
func TestCollaborationPost(t *testing.T) {
-
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/issues/labels")
test.LoadUser(t, ctx, 2)
@@ -136,7 +135,6 @@ func TestCollaborationPost(t *testing.T) {
}
func TestCollaborationPost_InactiveUser(t *testing.T) {
-
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/issues/labels")
test.LoadUser(t, ctx, 2)
@@ -160,7 +158,6 @@ func TestCollaborationPost_InactiveUser(t *testing.T) {
}
func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) {
-
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/issues/labels")
test.LoadUser(t, ctx, 2)
@@ -202,7 +199,6 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) {
}
func TestCollaborationPost_NonExistentUser(t *testing.T) {
-
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/issues/labels")
test.LoadUser(t, ctx, 2)
@@ -302,7 +298,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/web/repo/topic.go b/routers/web/repo/topic.go
index 810b241e28..a6a7ac6c8e 100644
--- a/routers/web/repo/topic.go
+++ b/routers/web/repo/topic.go
@@ -22,8 +22,8 @@ func TopicsPost(ctx *context.Context) {
return
}
- var topics = make([]string, 0)
- var topicsStr = ctx.FormTrim("topics")
+ topics := make([]string, 0)
+ topicsStr := ctx.FormTrim("topics")
if len(topicsStr) > 0 {
topics = strings.Split(topicsStr, ",")
}
diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go
index e8c02b64b8..150ace212b 100644
--- a/routers/web/repo/view.go
+++ b/routers/web/repo/view.go
@@ -77,7 +77,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
@@ -150,7 +150,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())
@@ -368,7 +368,6 @@ func renderDirectory(ctx *context.Context, treeLink string) {
ctx.Data["CanAddFile"] = !ctx.Repo.Repository.IsArchived
ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled && !ctx.Repo.Repository.IsArchived
}
-
}
func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
@@ -399,7 +398,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
isDisplayingSource := ctx.FormString("display") == "source"
isDisplayingRendered := !isDisplayingSource
- //Check for LFS meta file
+ // Check for LFS meta file
if isTextFile && setting.LFS.StartServer {
pointer, _ := lfs.ReadPointerFromBuffer(buf)
if pointer.IsValid() {
diff --git a/routers/web/repo/wiki.go b/routers/web/repo/wiki.go
index e57aa5ec29..633458081f 100644
--- a/routers/web/repo/wiki.go
+++ b/routers/web/repo/wiki.go
@@ -191,7 +191,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/?action=_pages")
@@ -219,7 +219,7 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {
return nil, nil
}
- var rctx = &markup.RenderContext{
+ rctx := &markup.RenderContext{
Ctx: ctx,
URLPrefix: ctx.Repo.RepoLink,
Metas: ctx.Repo.Repository.ComposeDocumentMetas(),
@@ -291,7 +291,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/?action=_pages")
@@ -365,7 +365,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/?action=_pages")
diff --git a/routers/web/repo/wiki_test.go b/routers/web/repo/wiki_test.go
index 1bfda50d19..b19c628a9f 100644
--- a/routers/web/repo/wiki_test.go
+++ b/routers/web/repo/wiki_test.go
@@ -20,8 +20,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 *repo_model.Repository, wikiName string) *git.TreeEntry {
wikiRepo, err := git.OpenRepository(repo.WikiPath())
diff --git a/routers/web/user/home.go b/routers/web/user/home.go
index 04459573af..13fa9bd8c4 100644
--- a/routers/web/user/home.go
+++ b/routers/web/user/home.go
@@ -197,7 +197,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
@@ -350,7 +350,6 @@ func Issues(ctx *context.Context) {
var issueReposQueryPattern = regexp.MustCompile(`^\[\d+(,\d+)*,?\]$`)
func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
-
// ----------------------------------------------------
// Determine user; can be either user or organization.
// Return with NotFound or ServerError if unsuccessful.
@@ -586,8 +585,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {
ctx.Data["IsShowClosed"] = isShowClosed
- ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] =
- issue_service.GetRefEndNamesAndURLs(issues, ctx.FormString("RepoLink"))
+ ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, ctx.FormString("RepoLink"))
ctx.Data["Issues"] = issues
@@ -661,7 +659,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" {
@@ -693,8 +691,8 @@ func issueIDsFromSearch(ctxUser *user_model.User, keyword string, opts *models.I
}
func loadRepoByIDs(ctxUser *user_model.User, issueCountByRepo map[int64]int64, unitType unit.Type) (map[int64]*repo_model.Repository, error) {
- var totalRes = make(map[int64]*repo_model.Repository, len(issueCountByRepo))
- var repoIDs = make([]int64, 0, 500)
+ totalRes := make(map[int64]*repo_model.Repository, len(issueCountByRepo))
+ repoIDs := make([]int64, 0, 500)
for id := range issueCountByRepo {
if id <= 0 {
continue
@@ -745,7 +743,7 @@ func ShowGPGKeys(ctx *context.Context, uid int64) {
if err != nil {
if asymkey_model.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
@@ -755,12 +753,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/web/user/profile.go b/routers/web/user/profile.go
index 40fc44ed14..86ecb7c02c 100644
--- a/routers/web/user/profile.go
+++ b/routers/web/user/profile.go
@@ -258,7 +258,8 @@ func Profile(ctx *context.Context) {
total = ctxUser.NumFollowing
case "activity":
- ctx.Data["Feeds"] = feed.RetrieveFeeds(ctx, models.GetFeedsOptions{RequestedUser: ctxUser,
+ ctx.Data["Feeds"] = feed.RetrieveFeeds(ctx, models.GetFeedsOptions{
+ RequestedUser: ctxUser,
Actor: ctx.User,
IncludePrivate: showPrivate,
OnlyPerformedBy: true,
diff --git a/routers/web/user/setting/account_test.go b/routers/web/user/setting/account_test.go
index cd5c77795e..a67d09e9ed 100644
--- a/routers/web/user/setting/account_test.go
+++ b/routers/web/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/web/user/setting/keys.go b/routers/web/user/setting/keys.go
index 26bbf7c195..f926c1f311 100644
--- a/routers/web/user/setting/keys.go
+++ b/routers/web/user/setting/keys.go
@@ -211,7 +211,6 @@ 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
diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go
index ab156b43fc..3a61f2f92a 100644
--- a/routers/web/user/setting/profile.go
+++ b/routers/web/user/setting/profile.go
@@ -415,5 +415,4 @@ func UpdateUserLang(ctx *context.Context) {
log.Trace("User settings updated: %s", ctx.User.Name)
ctx.Flash.Success(i18n.Tr(ctx.User.Language, "settings.update_language_success"))
ctx.Redirect(setting.AppSubURL + "/user/settings/appearance")
-
}
diff --git a/routers/web/web.go b/routers/web/web.go
index e934095b79..698f91b8ca 100644
--- a/routers/web/web.go
+++ b/routers/web/web.go
@@ -56,9 +56,9 @@ const (
func CorsHandler() func(next http.Handler) http.Handler {
if setting.CORSConfig.Enabled {
return 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()),
@@ -459,7 +459,6 @@ func RegisterRoutes(m *web.Route) {
m.Post("/msteams/new", bindIgnErr(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
m.Post("/feishu/new", bindIgnErr(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
m.Post("/wechatwork/new", bindIgnErr(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost)
-
})
m.Group("/auths", func() {
@@ -691,7 +690,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
@@ -818,7 +816,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
@@ -857,7 +854,6 @@ func RegisterRoutes(m *web.Route) {
}
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
})
-
}, ignSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoReleaseReader)
// to maintain compatibility with old attachments
@@ -1085,5 +1081,4 @@ func RegisterRoutes(m *web.Route) {
ctx := context.GetContext(req)
ctx.NotFound("", nil)
})
-
}
diff --git a/services/auth/auth.go b/services/auth/auth.go
index 3eb7f027d2..bdff777f50 100644
--- a/services/auth/auth.go
+++ b/services/auth/auth.go
@@ -95,8 +95,10 @@ func isAttachmentDownload(req *http.Request) bool {
return strings.HasPrefix(req.URL.Path, "/attachments/") && req.Method == "GET"
}
-var gitRawReleasePathRe = regexp.MustCompile(`^/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+/(?:(?:git-(?:(?:upload)|(?:receive))-pack$)|(?:info/refs$)|(?:HEAD$)|(?:objects/)|(?:raw/)|(?:releases/download/))`)
-var lfsPathRe = regexp.MustCompile(`^/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+/info/lfs/`)
+var (
+ gitRawReleasePathRe = regexp.MustCompile(`^/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+/(?:(?:git-(?:(?:upload)|(?:receive))-pack$)|(?:info/refs$)|(?:HEAD$)|(?:objects/)|(?:raw/)|(?:releases/download/))`)
+ lfsPathRe = regexp.MustCompile(`^/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+/info/lfs/`)
+)
func isGitRawReleaseOrLFSPath(req *http.Request) bool {
if gitRawReleasePathRe.MatchString(req.URL.Path) {
diff --git a/services/auth/auth_test.go b/services/auth/auth_test.go
index b0d23bb4e9..8a9dee6cef 100644
--- a/services/auth/auth_test.go
+++ b/services/auth/auth_test.go
@@ -13,7 +13,6 @@ import (
)
func Test_isGitRawOrLFSPath(t *testing.T) {
-
tests := []struct {
path string
diff --git a/services/auth/basic.go b/services/auth/basic.go
index e2448eeca0..d8667c65d5 100644
--- a/services/auth/basic.go
+++ b/services/auth/basic.go
@@ -30,8 +30,7 @@ const BasicMethodName = "basic"
// Basic implements the Auth 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{}
// Name represents the name of auth method
func (b *Basic) Name() string {
diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go
index fae981d800..fcff5313e3 100644
--- a/services/auth/oauth2.go
+++ b/services/auth/oauth2.go
@@ -53,8 +53,7 @@ func CheckOAuthAccessToken(accessToken string) int64 {
// OAuth2 implements the Auth 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{}
// Name represents the name of auth method
func (o *OAuth2) Name() string {
diff --git a/services/auth/reverseproxy.go b/services/auth/reverseproxy.go
index 3e44d8b863..1b151f6504 100644
--- a/services/auth/reverseproxy.go
+++ b/services/auth/reverseproxy.go
@@ -32,8 +32,7 @@ const ReverseProxyMethodName = "reverse_proxy"
// 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/services/auth/session.go b/services/auth/session.go
index 256598d100..6a23a17665 100644
--- a/services/auth/session.go
+++ b/services/auth/session.go
@@ -19,8 +19,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{}
// Name represents the name of auth method
func (s *Session) Name() string {
diff --git a/services/auth/source/ldap/source_sync.go b/services/auth/source/ldap/source_sync.go
index 78aa90aaa5..398d9ef798 100644
--- a/services/auth/source/ldap/source_sync.go
+++ b/services/auth/source/ldap/source_sync.go
@@ -164,7 +164,6 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
if err == nil && len(source.AttributeAvatar) > 0 {
_ = user_service.UploadAvatar(usr, su.Avatar)
}
-
}
}
}
diff --git a/services/auth/source/oauth2/jwtsigningkey.go b/services/auth/source/oauth2/jwtsigningkey.go
index 187c6999e0..24f2c41119 100644
--- a/services/auth/source/oauth2/jwtsigningkey.go
+++ b/services/auth/source/oauth2/jwtsigningkey.go
@@ -410,7 +410,7 @@ func loadOrCreateAsymmetricKey() (interface{}, error) {
return err
}
- 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
}
diff --git a/services/auth/source/oauth2/providers.go b/services/auth/source/oauth2/providers.go
index 065c6884e0..45851c8799 100644
--- a/services/auth/source/oauth2/providers.go
+++ b/services/auth/source/oauth2/providers.go
@@ -139,10 +139,8 @@ func ClearProviders() {
goth.ClearProviders()
}
-var (
- // ErrAuthSourceNotActived login source is not actived error
- ErrAuthSourceNotActived = errors.New("auth source is not actived")
-)
+// ErrAuthSourceNotActived login source is not actived error
+var ErrAuthSourceNotActived = errors.New("auth source is not actived")
// used to create different types of goth providers
func createProvider(providerName string, source *Source) (goth.Provider, error) {
diff --git a/services/auth/source/oauth2/providers_openid.go b/services/auth/source/oauth2/providers_openid.go
index 838311b4a1..80ee56d4a4 100644
--- a/services/auth/source/oauth2/providers_openid.go
+++ b/services/auth/source/oauth2/providers_openid.go
@@ -13,8 +13,7 @@ import (
)
// OpenIDProvider is a GothProvider for OpenID
-type OpenIDProvider struct {
-}
+type OpenIDProvider struct{}
// Name provides the technical name for this provider
func (o *OpenIDProvider) Name() string {
diff --git a/services/auth/source/oauth2/providers_simple.go b/services/auth/source/oauth2/providers_simple.go
index a4d61eb2f3..0f118b596d 100644
--- a/services/auth/source/oauth2/providers_simple.go
+++ b/services/auth/source/oauth2/providers_simple.go
@@ -107,5 +107,4 @@ func init() {
return microsoftonline.New(clientID, secret, callbackURL, scopes...)
},
))
-
}
diff --git a/services/auth/source/oauth2/source_callout.go b/services/auth/source/oauth2/source_callout.go
index 8596dd187d..7447e5d453 100644
--- a/services/auth/source/oauth2/source_callout.go
+++ b/services/auth/source/oauth2/source_callout.go
@@ -18,7 +18,7 @@ func (source *Source) Callout(request *http.Request, response http.ResponseWrite
// 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)
gothRWMutex.RLock()
defer gothRWMutex.RUnlock()
diff --git a/services/auth/source/smtp/auth.go b/services/auth/source/smtp/auth.go
index c5bd09b0a7..8d0cbb11cd 100644
--- a/services/auth/source/smtp/auth.go
+++ b/services/auth/source/smtp/auth.go
@@ -51,10 +51,8 @@ const (
// Authenticators contains available SMTP authentication type names.
var Authenticators = []string{PlainAuthentication, LoginAuthentication, CRAMMD5Authentication}
-var (
- // ErrUnsupportedLoginType login source is unknown error
- ErrUnsupportedLoginType = errors.New("Login source is unknown")
-)
+// ErrUnsupportedLoginType login source is unknown error
+var ErrUnsupportedLoginType = errors.New("Login source is unknown")
// Authenticate performs an SMTP authentication.
func Authenticate(a smtp.Auth, source *Source) error {
diff --git a/services/comments/comments.go b/services/comments/comments.go
index 296f06d75c..6f63060c45 100644
--- a/services/comments/comments.go
+++ b/services/comments/comments.go
@@ -40,7 +40,7 @@ func CreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issu
// UpdateComment updates information of comment.
func UpdateComment(c *models.Comment, doer *user_model.User, oldContent string) error {
- var needsContentHistory = c.Content != oldContent &&
+ needsContentHistory := c.Content != oldContent &&
(c.Type == models.CommentTypeComment || c.Type == models.CommentTypeReview || c.Type == models.CommentTypeCode)
if needsContentHistory {
hasContentHistory, err := issues.HasIssueContentHistory(db.DefaultContext, c.IssueID, c.ID)
diff --git a/services/cron/cron.go b/services/cron/cron.go
index ae309bd866..19f703caf1 100644
--- a/services/cron/cron.go
+++ b/services/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/services/cron/tasks.go b/services/cron/tasks.go
index 29062233c8..07da2fe8d6 100644
--- a/services/cron/tasks.go
+++ b/services/cron/tasks.go
@@ -19,10 +19,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/services/forms/repo_form_test.go b/services/forms/repo_form_test.go
index 4f65d59ca6..198437f7ea 100644
--- a/services/forms/repo_form_test.go
+++ b/services/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/services/gitdiff/csv.go b/services/gitdiff/csv.go
index 0e56ff3150..642c9937dd 100644
--- a/services/gitdiff/csv.go
+++ b/services/gitdiff/csv.go
@@ -12,9 +12,11 @@ import (
"code.gitea.io/gitea/modules/util"
)
-const unmappedColumn = -1
-const maxRowsToInspect int = 10
-const minRatioToMatch float32 = 0.8
+const (
+ unmappedColumn = -1
+ maxRowsToInspect int = 10
+ minRatioToMatch float32 = 0.8
+)
// TableDiffCellType represents the type of a TableDiffCell.
type TableDiffCellType uint8
@@ -172,7 +174,7 @@ func createCsvDiff(diffFile *DiffFile, baseReader, headReader *csv.Reader) ([]*T
// createDiffTableRow takes the row # of the `a` line and `b` line of a diff (starting from 1), 0 if the line doesn't exist (undefined)
// in the base or head respectively.
// Returns a TableDiffRow which has the row index
- createDiffTableRow := func(aLineNum int, bLineNum int) (*TableDiffRow, error) {
+ createDiffTableRow := func(aLineNum, bLineNum int) (*TableDiffRow, error) {
// diffTableCells is a row of the diff table. It will have a cells for added, deleted, changed, and unchanged content, thus either
// the same size as the head table or bigger
diffTableCells := make([]*TableDiffCell, numDiffTableCols)
diff --git a/services/gitdiff/csv_test.go b/services/gitdiff/csv_test.go
index 90d24d1c80..2c15b42d91 100644
--- a/services/gitdiff/csv_test.go
+++ b/services/gitdiff/csv_test.go
@@ -16,7 +16,7 @@ import (
)
func TestCSVDiff(t *testing.T) {
- var cases = []struct {
+ cases := []struct {
diff string
base string
head string
@@ -35,7 +35,8 @@ func TestCSVDiff(t *testing.T) {
a,a`,
cells: [][]TableDiffCellType{
{TableDiffCellAdd, TableDiffCellAdd},
- {TableDiffCellAdd, TableDiffCellAdd}},
+ {TableDiffCellAdd, TableDiffCellAdd},
+ },
},
// case 1 - adding 1 row at end
{
@@ -53,7 +54,8 @@ a,a`,
a,a
b,b`,
cells: [][]TableDiffCellType{
- {TableDiffCellUnchanged, TableDiffCellUnchanged}, {TableDiffCellUnchanged, TableDiffCellUnchanged},
+ {TableDiffCellUnchanged, TableDiffCellUnchanged},
+ {TableDiffCellUnchanged, TableDiffCellUnchanged},
{TableDiffCellAdd, TableDiffCellAdd},
},
},
@@ -72,7 +74,8 @@ b,b`,
head: `col1,col2
b,b`,
cells: [][]TableDiffCellType{
- {TableDiffCellUnchanged, TableDiffCellUnchanged}, {TableDiffCellDel, TableDiffCellDel},
+ {TableDiffCellUnchanged, TableDiffCellUnchanged},
+ {TableDiffCellDel, TableDiffCellDel},
{TableDiffCellUnchanged, TableDiffCellUnchanged},
},
},
diff --git a/services/gitdiff/gitdiff.go b/services/gitdiff/gitdiff.go
index 43af2deb4b..25d5e139d9 100644
--- a/services/gitdiff/gitdiff.go
+++ b/services/gitdiff/gitdiff.go
@@ -190,9 +190,11 @@ var (
codeTagSuffix = []byte(`</span>`)
)
-var unfinishedtagRegex = regexp.MustCompile(`<[^>]*$`)
-var trailingSpanRegex = regexp.MustCompile(`<span\s*[[:alpha:]="]*?[>]?$`)
-var entityRegex = regexp.MustCompile(`&[#]*?[0-9[:alpha:]]*$`)
+var (
+ unfinishedtagRegex = regexp.MustCompile(`<[^>]*$`)
+ trailingSpanRegex = regexp.MustCompile(`<span\s*[[:alpha:]="]*?[>]?$`)
+ entityRegex = regexp.MustCompile(`&[#]*?[0-9[:alpha:]]*$`)
+)
// shouldWriteInline represents combinations where we manually write inline changes
func shouldWriteInline(diff diffmatchpatch.Diff, lineType DiffLineType) bool {
@@ -206,7 +208,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))
@@ -658,10 +659,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 {
@@ -942,8 +943,8 @@ parsingLoop:
// TODO: There are numerous issues with this:
// - we might want to consider detecting encoding while parsing but...
// - we're likely to fail to get the correct encoding here anyway as we won't have enough information
- var diffLineTypeBuffers = make(map[DiffLineType]*bytes.Buffer, 3)
- var diffLineTypeDecoders = make(map[DiffLineType]*encoding.Decoder, 3)
+ diffLineTypeBuffers := make(map[DiffLineType]*bytes.Buffer, 3)
+ diffLineTypeDecoders := make(map[DiffLineType]*encoding.Decoder, 3)
diffLineTypeBuffers[DiffLinePlain] = new(bytes.Buffer)
diffLineTypeBuffers[DiffLineAdd] = new(bytes.Buffer)
diffLineTypeBuffers[DiffLineDel] = new(bytes.Buffer)
@@ -1539,7 +1540,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 57cbb74b22..d57a3e2aba 100644
--- a/services/gitdiff/gitdiff_test.go
+++ b/services/gitdiff/gitdiff_test.go
@@ -504,7 +504,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
@@ -594,7 +594,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 @@
@@ -611,7 +611,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 @@
@@ -628,7 +628,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 @@
@@ -665,6 +665,7 @@ func setupDefaultDiff() *Diff {
},
}
}
+
func TestDiff_LoadComments(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
diff --git a/services/issue/issue.go b/services/issue/issue.go
index ef2894b929..8b6262c571 100644
--- a/services/issue/issue.go
+++ b/services/issue/issue.go
@@ -162,8 +162,8 @@ func AddAssigneeIfNotAssigned(issue *models.Issue, doer *user_model.User, assign
// 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 fc94749bdb..73e30e894f 100644
--- a/services/issue/label_test.go
+++ b/services/issue/label_test.go
@@ -15,7 +15,7 @@ import (
)
func TestIssue_AddLabels(t *testing.T) {
- var tests = []struct {
+ tests := []struct {
issueID int64
labelIDs []int64
doerID int64
@@ -41,7 +41,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/lfs/locks.go b/services/lfs/locks.go
index c2ede20b7c..3839119b27 100644
--- a/services/lfs/locks.go
+++ b/services/lfs/locks.go
@@ -80,7 +80,7 @@ func GetListLockHandler(ctx *context.Context) {
limit = 0
}
id := ctx.FormString("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(http.StatusBadRequest, api.LFSLockError{
@@ -97,7 +97,7 @@ func GetListLockHandler(ctx *context.Context) {
}
path := ctx.FormString("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)
@@ -106,7 +106,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/services/lfs/server.go b/services/lfs/server.go
index 25882928a2..cdce0046b3 100644
--- a/services/lfs/server.go
+++ b/services/lfs/server.go
@@ -440,7 +440,7 @@ func buildObjectResponse(rc *requestContext, pointer lfs_module.Pointer, downloa
if download {
rep.Actions["download"] = &lfs_module.Link{Href: rc.DownloadLink(pointer), Header: header}
if setting.LFS.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.LFS.URL(pointer.RelativePath(), pointer.Oid)
if u != nil && err == nil {
rep.Actions["download"] = &lfs_module.Link{Href: u.String(), Header: header}
diff --git a/services/mailer/mail_issue.go b/services/mailer/mail_issue.go
index 1df8332116..bd5008f076 100644
--- a/services/mailer/mail_issue.go
+++ b/services/mailer/mail_issue.go
@@ -40,7 +40,6 @@ const (
// 1. Repository watchers (except for WIP pull requests) 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 []*user_model.User) 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 6a175337ad..07690063cd 100644
--- a/services/mailer/mail_test.go
+++ b/services/mailer/mail_test.go
@@ -44,7 +44,7 @@ const bodyTpl = `
func prepareMailerTest(t *testing.T) (doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment) {
assert.NoError(t, unittest.PrepareTestDatabase())
- var mailService = setting.Mailer{
+ mailService := setting.Mailer{
From: "test@gitea.com",
}
@@ -67,8 +67,10 @@ func TestComposeIssueCommentMessage(t *testing.T) {
InitMailRender(stpl, btpl)
recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}, {Name: "Test2", Email: "test2@gitea.com"}}
- msgs, err := composeIssueCommentMessages(&mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue,
- Content: "test body", Comment: comment}, "en-US", recipients, false, "issue comment")
+ msgs, err := composeIssueCommentMessages(&mailCommentContext{
+ Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue,
+ Content: "test body", Comment: comment,
+ }, "en-US", recipients, false, "issue comment")
assert.NoError(t, err)
assert.Len(t, msgs, 2)
gomailMsg := msgs[0].ToMessage()
@@ -94,8 +96,10 @@ func TestComposeIssueMessage(t *testing.T) {
InitMailRender(stpl, btpl)
recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}, {Name: "Test2", Email: "test2@gitea.com"}}
- msgs, err := composeIssueCommentMessages(&mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue,
- Content: "test body"}, "en-US", recipients, false, "issue create")
+ msgs, err := composeIssueCommentMessages(&mailCommentContext{
+ Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue,
+ Content: "test body",
+ }, "en-US", recipients, false, "issue create")
assert.NoError(t, err)
assert.Len(t, msgs, 2)
@@ -138,22 +142,30 @@ func TestTemplateSelection(t *testing.T) {
assert.Contains(t, wholemsg, expBody)
}
- msg := testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue,
- Content: "test body"}, recipients, false, "TestTemplateSelection")
+ msg := testComposeIssueCommentMessage(t, &mailCommentContext{
+ Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue,
+ Content: "test body",
+ }, recipients, false, "TestTemplateSelection")
expect(t, msg, "issue/new/subject", "issue/new/body")
- msg = testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue,
- Content: "test body", Comment: comment}, recipients, false, "TestTemplateSelection")
+ msg = testComposeIssueCommentMessage(t, &mailCommentContext{
+ Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue,
+ Content: "test body", Comment: comment,
+ }, recipients, false, "TestTemplateSelection")
expect(t, msg, "issue/default/subject", "issue/default/body")
pull := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2, Repo: repo, Poster: doer}).(*models.Issue)
comment = unittest.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}, recipients, false, "TestTemplateSelection")
+ msg = testComposeIssueCommentMessage(t, &mailCommentContext{
+ Issue: pull, Doer: doer, ActionType: models.ActionCommentPull,
+ Content: "test body", Comment: comment,
+ }, recipients, 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}, recipients, false, "TestTemplateSelection")
+ msg = testComposeIssueCommentMessage(t, &mailCommentContext{
+ Issue: issue, Doer: doer, ActionType: models.ActionCloseIssue,
+ Content: "test body", Comment: comment,
+ }, recipients, false, "TestTemplateSelection")
expect(t, msg, "Re: [user2/repo1] issue1 (#1)", "issue/close/body")
}
@@ -162,15 +174,17 @@ func TestTemplateServices(t *testing.T) {
assert.NoError(t, issue.LoadRepo())
expect := func(t *testing.T, issue *models.Issue, comment *models.Comment, doer *user_model.User,
- actionType models.ActionType, fromMention bool, tplSubject, tplBody, expSubject, expBody string) {
-
+ 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)
recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}}
- msg := testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: actionType,
- Content: "test body", Comment: comment}, recipients, fromMention, "TestTemplateServices")
+ msg := testComposeIssueCommentMessage(t, &mailCommentContext{
+ Issue: issue, Doer: doer, ActionType: actionType,
+ Content: "test body", Comment: comment,
+ }, recipients, fromMention, "TestTemplateServices")
subject := msg.ToMessage().GetHeader("Subject")
msgbuf := new(bytes.Buffer)
diff --git a/services/mailer/mailer.go b/services/mailer/mailer.go
index e5e6272f10..eeb98b5879 100644
--- a/services/mailer/mailer.go
+++ b/services/mailer/mailer.go
@@ -141,8 +141,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 {
@@ -254,8 +253,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 {
@@ -280,7 +278,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
}
@@ -314,8 +311,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/migrations/codebase.go b/services/migrations/codebase.go
index 395bc6152e..13e9327c33 100644
--- a/services/migrations/codebase.go
+++ b/services/migrations/codebase.go
@@ -30,8 +30,7 @@ func init() {
}
// CodebaseDownloaderFactory defines a downloader factory
-type CodebaseDownloaderFactory struct {
-}
+type CodebaseDownloaderFactory struct{}
// New returns a downloader related to this factory according MigrateOptions
func (f *CodebaseDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
@@ -88,7 +87,7 @@ func (d *CodebaseDownloader) SetContext(ctx context.Context) {
func NewCodebaseDownloader(ctx context.Context, projectURL *url.URL, project, repoName, username, password string) *CodebaseDownloader {
baseURL, _ := url.Parse("https://api3.codebasehq.com")
- var downloader = &CodebaseDownloader{
+ downloader := &CodebaseDownloader{
ctx: ctx,
baseURL: baseURL,
projectURL: projectURL,
@@ -206,7 +205,7 @@ func (d *CodebaseDownloader) GetMilestones() ([]*base.Milestone, error) {
return nil, err
}
- var milestones = make([]*base.Milestone, 0, len(rawMilestones.TicketingMilestone))
+ milestones := make([]*base.Milestone, 0, len(rawMilestones.TicketingMilestone))
for _, milestone := range rawMilestones.TicketingMilestone {
var deadline *time.Time
if len(milestone.Deadline.Value) > 0 {
@@ -256,7 +255,7 @@ func (d *CodebaseDownloader) GetLabels() ([]*base.Label, error) {
return nil, err
}
- var labels = make([]*base.Label, 0, len(rawTypes.TicketingType))
+ labels := make([]*base.Label, 0, len(rawTypes.TicketingType))
for _, label := range rawTypes.TicketingType {
labels = append(labels, &base.Label{
Name: label.Name,
@@ -400,7 +399,8 @@ func (d *CodebaseDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool,
Created: issue.CreatedAt.Value,
Updated: issue.UpdatedAt.Value,
Labels: []*base.Label{
- {Name: issue.Type.Name}},
+ {Name: issue.Type.Name},
+ },
Context: codebaseIssueContext{
foreignID: issue.TicketID.Value,
localID: issue.TicketID.Value,
diff --git a/services/migrations/dump.go b/services/migrations/dump.go
index f4e797b357..01a946673e 100644
--- a/services/migrations/dump.go
+++ b/services/migrations/dump.go
@@ -27,9 +27,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 {
@@ -403,7 +401,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)
}
@@ -532,7 +530,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)
}
@@ -611,7 +609,7 @@ func RestoreRepository(ctx context.Context, baseDir, ownerName, repoName string,
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
@@ -622,7 +620,7 @@ func RestoreRepository(ctx context.Context, baseDir, ownerName, repoName string,
}
tp, _ := strconv.Atoi(opts["service_type"])
- var migrateOpts = base.MigrateOptions{
+ migrateOpts := base.MigrateOptions{
GitServiceType: structs.GitServiceType(tp),
}
updateOptionsUnits(&migrateOpts, units)
diff --git a/services/migrations/error.go b/services/migrations/error.go
index b90d1b6577..3b3f975012 100644
--- a/services/migrations/error.go
+++ b/services/migrations/error.go
@@ -11,10 +11,8 @@ import (
"github.com/google/go-github/v39/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/services/migrations/git.go b/services/migrations/git.go
index 37ffb674c5..3198f934ca 100644
--- a/services/migrations/git.go
+++ b/services/migrations/git.go
@@ -10,9 +10,7 @@ import (
base "code.gitea.io/gitea/modules/migration"
)
-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/services/migrations/gitbucket.go b/services/migrations/gitbucket.go
index 27ed584aa2..c4fb0df93a 100644
--- a/services/migrations/gitbucket.go
+++ b/services/migrations/gitbucket.go
@@ -23,8 +23,7 @@ func init() {
}
// GitBucketDownloaderFactory defines a GitBucket downloader factory
-type GitBucketDownloaderFactory struct {
-}
+type GitBucketDownloaderFactory struct{}
// New returns a Downloader related to this factory according MigrateOptions
func (f *GitBucketDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
diff --git a/services/migrations/gitea_downloader.go b/services/migrations/gitea_downloader.go
index 258f030726..a712b65a22 100644
--- a/services/migrations/gitea_downloader.go
+++ b/services/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) {
@@ -159,7 +158,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
@@ -224,7 +223,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
@@ -304,7 +303,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
@@ -379,7 +378,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},
@@ -391,7 +390,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]))
}
@@ -444,7 +443,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err
// GetComments returns comments according issueNumber
func (g *GiteaDownloader) GetComments(opts base.GetCommentOptions) ([]*base.Comment, bool, 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
@@ -496,7 +495,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{
@@ -514,7 +513,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]))
}
@@ -620,7 +619,7 @@ func (g *GiteaDownloader) GetReviews(context base.IssueContext) ([]*base.Review,
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/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go
index e939046e90..6e823031ed 100644
--- a/services/migrations/gitea_uploader.go
+++ b/services/migrations/gitea_uploader.go
@@ -33,9 +33,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 {
@@ -159,7 +157,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 {
@@ -182,7 +180,7 @@ func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) err
milestone.Updated = &milestone.Created
}
- var ms = models.Milestone{
+ ms := models.Milestone{
RepoID: g.repo.ID,
Name: milestone.Title,
Content: milestone.Description,
@@ -210,7 +208,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,
@@ -232,7 +230,7 @@ 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 {
if release.Created.IsZero() {
if !release.Published.IsZero() {
@@ -242,7 +240,7 @@ func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error {
}
}
- var rel = models.Release{
+ rel := models.Release{
RepoID: g.repo.ID,
TagName: release.TagName,
LowerTagName: strings.ToLower(release.TagName),
@@ -297,7 +295,7 @@ func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error {
asset.Created = release.Created
}
}
- var attach = repo_model.Attachment{
+ attach := repo_model.Attachment{
UUID: gouuid.New().String(),
Name: asset.Name,
DownloadCount: int64(*asset.DownloadCount),
@@ -348,7 +346,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 {
@@ -381,7 +379,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,
@@ -433,7 +431,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(),
}
@@ -464,7 +462,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 issue *models.Issue
issueInter, ok := g.issues.Load(comment.IssueIndex)
@@ -528,7 +526,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(),
}
@@ -553,7 +551,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 {
@@ -652,7 +650,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
@@ -723,7 +721,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullR
pr.Updated = pr.Created
}
- var issue = models.Issue{
+ issue := models.Issue{
RepoID: g.repo.ID,
Repo: g.repo,
Title: pr.Title,
@@ -773,7 +771,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(),
}
@@ -787,7 +785,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,
@@ -830,7 +828,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 issue *models.Issue
issueInter, ok := g.issues.Load(review.IssueIndex)
@@ -862,7 +860,7 @@ func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error {
review.CreatedAt = time.Unix(int64(issue.CreatedUnix), 0)
}
- var cm = models.Review{
+ cm := models.Review{
Type: convertReviewState(review.State),
IssueID: issue.ID,
Content: review.Content,
@@ -926,7 +924,7 @@ func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error {
comment.UpdatedAt = comment.CreatedAt
}
- var c = models.Comment{
+ c := models.Comment{
Type: models.CommentTypeCode,
PosterID: comment.PosterID,
IssueID: issue.ID,
diff --git a/services/migrations/github.go b/services/migrations/github.go
index b360b05061..a946177c90 100644
--- a/services/migrations/github.go
+++ b/services/migrations/github.go
@@ -37,8 +37,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) {
@@ -80,7 +79,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,
@@ -96,7 +95,7 @@ func NewGithubDownloaderV3(ctx context.Context, baseURL, userName, password, tok
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
- var client = &http.Client{
+ client := &http.Client{
Transport: &oauth2.Transport{
Base: NewMigrationHTTPTransport(),
Source: oauth2.ReuseTokenSource(nil, ts),
@@ -106,12 +105,12 @@ func NewGithubDownloaderV3(ctx context.Context, baseURL, userName, password, tok
downloader.addClient(client, baseURL)
}
} else {
- var transport = NewMigrationHTTPTransport()
+ transport := NewMigrationHTTPTransport()
transport.Proxy = func(req *http.Request) (*url.URL, error) {
req.SetBasicAuth(userName, password)
return proxy.Proxy()(req)
}
- var client = &http.Client{
+ client := &http.Client{
Transport: transport,
}
downloader.addClient(client, baseURL)
@@ -218,8 +217,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.waitAndPickClient()
ms, resp, err := g.getClient().Issues.ListMilestones(g.ctx, g.repoOwner, g.repoName,
@@ -228,14 +227,15 @@ func (g *GithubDownloaderV3) GetMilestones() ([]*base.Milestone, error) {
ListOptions: github.ListOptions{
Page: i,
PerPage: perPage,
- }})
+ },
+ })
if err != nil {
return nil, err
}
g.setRate(&resp.Rate)
for _, m := range ms {
- var state = "open"
+ state := "open"
if m.State != nil {
state = *m.State
}
@@ -266,8 +266,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.waitAndPickClient()
ls, resp, err := g.getClient().Issues.ListLabels(g.ctx, g.repoOwner, g.repoName,
@@ -311,7 +311,7 @@ func (g *GithubDownloaderV3) convertGithubRelease(rel *github.RepositoryRelease)
httpClient := NewMigrationHTTPClient()
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.GetID(),
Name: asset.GetName(),
@@ -357,8 +357,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.waitAndPickClient()
ls, resp, err := g.getClient().Repositories.ListReleases(g.ctx, g.repoOwner, g.repoName,
@@ -396,7 +396,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.waitAndPickClient()
issues, resp, err := g.getClient().Issues.ListByRepo(g.ctx, g.repoOwner, g.repoName, opt)
if err != nil {
@@ -409,7 +409,7 @@ func (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool,
continue
}
- 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))
}
@@ -573,7 +573,7 @@ func (g *GithubDownloaderV3) GetAllComments(page, perPage int) ([]*base.Comment,
if err != nil {
return nil, false, fmt.Errorf("error while listing repos: %v", err)
}
- var isEnd = resp.NextPage == 0
+ isEnd := resp.NextPage == 0
log.Trace("Request get comments %d/%d, but in fact get %d, next page is %d", perPage, page, len(comments), resp.NextPage)
g.setRate(&resp.Rate)
@@ -634,7 +634,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.waitAndPickClient()
prs, resp, err := g.getClient().PullRequests.List(g.ctx, g.repoOwner, g.repoName, opt)
if err != nil {
@@ -643,7 +643,7 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReq
log.Trace("Request get pull requests %d/%d, but in fact get %d", perPage, page, len(prs))
g.setRate(&resp.Rate)
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, convertGithubLabel(l))
}
@@ -729,7 +729,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
@@ -776,7 +776,7 @@ func (g *GithubDownloaderV3) convertGithubReviewComments(cs []*github.PullReques
// GetReviews returns pull requests review
func (g *GithubDownloaderV3) GetReviews(context base.IssueContext) ([]*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/services/migrations/gitlab.go b/services/migrations/gitlab.go
index 4eb7e3e47c..a9856739c2 100644
--- a/services/migrations/gitlab.go
+++ b/services/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) {
@@ -184,16 +183,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
}
@@ -203,7 +203,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
@@ -255,8 +255,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,
@@ -327,8 +327,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,
@@ -381,7 +381,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 {
@@ -389,7 +389,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,
@@ -402,7 +402,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 {
@@ -456,9 +456,9 @@ func (g *GitlabDownloader) GetComments(opts base.GetCommentOptions) ([]*base.Com
return nil, false, fmt.Errorf("unexpected context: %+v", opts.Context)
}
- var allComments = make([]*base.Comment, 0, g.maxPerPage)
+ allComments := make([]*base.Comment, 0, g.maxPerPage)
- var page = 1
+ page := 1
for {
var comments []*gitlab.Discussion
@@ -503,7 +503,6 @@ func (g *GitlabDownloader) GetComments(opts base.GetCommentOptions) ([]*base.Com
Created: *c.CreatedAt,
})
}
-
}
if resp.NextPage == 0 {
break
@@ -526,7 +525,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque
},
}
- 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 {
@@ -534,7 +533,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,
@@ -547,12 +546,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
}
@@ -568,7 +567,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 {
@@ -641,7 +640,7 @@ func (g *GitlabDownloader) GetReviews(context base.IssueContext) ([]*base.Review
return nil, err
}
- var reviews = make([]*base.Review, 0, len(approvals.ApprovedBy))
+ reviews := make([]*base.Review, 0, len(approvals.ApprovedBy))
for _, user := range approvals.ApprovedBy {
reviews = append(reviews, &base.Review{
IssueIndex: context.LocalID(),
diff --git a/services/migrations/gogs.go b/services/migrations/gogs.go
index e103ef996e..9280427cd7 100644
--- a/services/migrations/gogs.go
+++ b/services/migrations/gogs.go
@@ -30,8 +30,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) {
@@ -81,7 +80,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,
@@ -95,7 +94,7 @@ func NewGogsDownloader(ctx context.Context, baseURL, userName, password, token,
client = gogs.NewClient(baseURL, token)
downloader.userName = token
} else {
- var transport = NewMigrationHTTPTransport()
+ transport := NewMigrationHTTPTransport()
transport.Proxy = func(req *http.Request) (*url.URL, error) {
req.SetBasicAuth(userName, password)
return proxy.Proxy()(req)
@@ -139,8 +138,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 {
@@ -162,8 +161,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
@@ -203,7 +202,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,
@@ -225,7 +224,7 @@ func (g *GogsDownloader) getIssues(page int, state string) ([]*base.Issue, bool,
// GetComments returns comments according issueNumber
func (g *GogsDownloader) GetComments(opts base.GetCommentOptions) ([]*base.Comment, bool, error) {
- var allComments = make([]*base.Comment, 0, 100)
+ allComments := make([]*base.Comment, 0, 100)
comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, opts.Context.ForeignID())
if err != nil {
@@ -276,7 +275,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/services/migrations/migrate.go b/services/migrations/migrate.go
index 65ecceddbe..7bca128ac5 100644
--- a/services/migrations/migrate.go
+++ b/services/migrations/migrate.go
@@ -123,7 +123,7 @@ func MigrateRepository(ctx context.Context, doer *user_model.User, ownerName str
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, messenger); err != nil {
@@ -305,7 +305,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts
if opts.Issues {
log.Trace("migrating issues and comments")
messenger("repo.migrate.migrating_issues")
- var issueBatchSize = uploader.MaxBatchInsertSize("issue")
+ issueBatchSize := uploader.MaxBatchInsertSize("issue")
for i := 1; ; i++ {
issues, isEnd, err := downloader.GetIssues(i, issueBatchSize)
@@ -322,7 +322,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts
}
if opts.Comments && !supportAllComments {
- 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(base.GetCommentOptions{
@@ -362,7 +362,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts
if opts.PullRequests {
log.Trace("migrating pull requests and comments")
messenger("repo.migrate.migrating_pulls")
- var prBatchSize = uploader.MaxBatchInsertSize("pullrequest")
+ prBatchSize := uploader.MaxBatchInsertSize("pullrequest")
for i := 1; ; i++ {
prs, isEnd, err := downloader.GetPullRequests(i, prBatchSize)
if err != nil {
@@ -380,7 +380,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts
if opts.Comments {
if !supportAllComments {
// 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(base.GetCommentOptions{
@@ -410,7 +410,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 {
reviews, err := downloader.GetReviews(pr.Context)
if err != nil {
diff --git a/services/migrations/onedev.go b/services/migrations/onedev.go
index bb676131f3..c8253e8947 100644
--- a/services/migrations/onedev.go
+++ b/services/migrations/onedev.go
@@ -29,8 +29,7 @@ func init() {
}
// OneDevDownloaderFactory defines a downloader factory
-type OneDevDownloaderFactory struct {
-}
+type OneDevDownloaderFactory struct{}
// New returns a downloader related to this factory according MigrateOptions
func (f *OneDevDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
@@ -90,7 +89,7 @@ func (d *OneDevDownloader) SetContext(ctx context.Context) {
// NewOneDevDownloader creates a new downloader
func NewOneDevDownloader(ctx context.Context, baseURL *url.URL, username, password, repoName string) *OneDevDownloader {
- var downloader = &OneDevDownloader{
+ downloader := &OneDevDownloader{
ctx: ctx,
baseURL: baseURL,
repoName: repoName,
@@ -195,7 +194,7 @@ func (d *OneDevDownloader) GetMilestones() ([]*base.Milestone, error) {
endpoint := fmt.Sprintf("/api/projects/%d/milestones", d.repoID)
- var milestones = make([]*base.Milestone, 0, 100)
+ milestones := make([]*base.Milestone, 0, 100)
offset := 0
for {
err := d.callAPI(
@@ -583,7 +582,7 @@ func (d *OneDevDownloader) GetReviews(context base.IssueContext) ([]*base.Review
return nil, err
}
- var reviews = make([]*base.Review, 0, len(rawReviews))
+ reviews := make([]*base.Review, 0, len(rawReviews))
for _, review := range rawReviews {
state := base.ReviewStatePending
content := ""
diff --git a/services/migrations/restore.go b/services/migrations/restore.go
index 357e995423..4499f78701 100644
--- a/services/migrations/restore.go
+++ b/services/migrations/restore.go
@@ -59,7 +59,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
@@ -91,7 +91,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"`
}{}
@@ -109,7 +109,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 {
@@ -133,7 +133,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 {
@@ -164,7 +164,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 {
@@ -188,7 +188,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 {
@@ -215,7 +215,7 @@ func (r *RepositoryRestorer) GetIssues(page, perPage int) ([]*base.Issue, bool,
// GetComments returns comments according issueNumber
func (r *RepositoryRestorer) GetComments(opts base.GetCommentOptions) ([]*base.Comment, bool, error) {
- var comments = make([]*base.Comment, 0, 10)
+ comments := make([]*base.Comment, 0, 10)
p := filepath.Join(r.commentDir(), fmt.Sprintf("%d.yml", opts.Context.ForeignID()))
_, err := os.Stat(p)
if err != nil {
@@ -239,7 +239,7 @@ func (r *RepositoryRestorer) GetComments(opts base.GetCommentOptions) ([]*base.C
// 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 {
@@ -267,7 +267,7 @@ func (r *RepositoryRestorer) GetPullRequests(page, perPage int) ([]*base.PullReq
// GetReviews returns pull requests review
func (r *RepositoryRestorer) GetReviews(context base.IssueContext) ([]*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", context.ForeignID()))
_, err := os.Stat(p)
if err != nil {
diff --git a/services/mirror/mirror_pull.go b/services/mirror/mirror_pull.go
index b9333c77f3..36cd71aa6e 100644
--- a/services/mirror/mirror_pull.go
+++ b/services/mirror/mirror_pull.go
@@ -150,8 +150,8 @@ func pruneBrokenReferences(ctx context.Context,
timeout time.Duration,
stdoutBuilder, stderrBuilder *strings.Builder,
sanitizer *strings.Replacer,
- isWiki bool) error {
-
+ isWiki bool,
+) error {
wiki := ""
if isWiki {
wiki = "Wiki "
diff --git a/services/pull/commit_status.go b/services/pull/commit_status.go
index d605f8e301..be8df0c9b1 100644
--- a/services/pull/commit_status.go
+++ b/services/pull/commit_status.go
@@ -26,7 +26,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 2a67507a87..d2196b22d5 100644
--- a/services/pull/merge.go
+++ b/services/pull/merge.go
@@ -165,13 +165,13 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User
}
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 := os.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil {
+ if err := os.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 0db3168895..25eef78d97 100644
--- a/services/pull/review.go
+++ b/services/pull/review.go
@@ -24,7 +24,6 @@ import (
// CreateCodeComment creates a comment on the code line
func CreateCodeComment(ctx context.Context, doer *user_model.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 140403172c..fa3bb2f4bb 100644
--- a/services/pull/temp_repo.go
+++ b/services/pull/temp_repo.go
@@ -70,7 +70,7 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e
// 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 09cf1ce52e..f32dfad2ca 100644
--- a/services/pull/update.go
+++ b/services/pull/update.go
@@ -26,7 +26,7 @@ func Update(ctx context.Context, pull *models.PullRequest, doer *user_model.User
pr = pull
style = repo_model.MergeStyleRebaseUpdate
} else {
- //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/release/release.go b/services/release/release.go
index aebf79edc3..8e6f9e1734 100644
--- a/services/release/release.go
+++ b/services/release/release.go
@@ -210,7 +210,7 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *models.R
return fmt.Errorf("AddReleaseAttachments: %v", err)
}
- var deletedUUIDsMap = make(map[string]bool)
+ deletedUUIDsMap := make(map[string]bool)
if len(delAttachmentUUIDs) > 0 {
// Check attachments
attachments, err := repo_model.GetAttachmentsByUUIDs(ctx, delAttachmentUUIDs)
@@ -230,7 +230,7 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *models.R
}
if len(editAttachments) > 0 {
- var updateAttachmentsList = make([]string, 0, len(editAttachments))
+ updateAttachmentsList := make([]string, 0, len(editAttachments))
for k := range editAttachments {
updateAttachmentsList = append(updateAttachmentsList, k)
}
diff --git a/services/release/release_test.go b/services/release/release_test.go
index 4dc45c06e9..413a56116b 100644
--- a/services/release/release_test.go
+++ b/services/release/release_test.go
@@ -112,7 +112,7 @@ func TestRelease_Create(t *testing.T) {
}, strings.NewReader("testtest"))
assert.NoError(t, err)
- var release = models.Release{
+ release := models.Release{
RepoID: repo.ID,
Repo: repo,
PublisherID: user.ID,
diff --git a/services/repository/adopt.go b/services/repository/adopt.go
index adc5942a3c..46337254b2 100644
--- a/services/repository/adopt.go
+++ b/services/repository/adopt.go
@@ -252,7 +252,8 @@ func checkUnadoptedRepositories(userName string, repoNamesToCheck []string, unad
ListOptions: db.ListOptions{
Page: 1,
PageSize: len(repoNamesToCheck),
- }, LowerNames: repoNamesToCheck})
+ }, LowerNames: repoNamesToCheck,
+ })
if err != nil {
return err
}
diff --git a/services/repository/adopt_test.go b/services/repository/adopt_test.go
index 2053151106..685bfe9bc4 100644
--- a/services/repository/adopt_test.go
+++ b/services/repository/adopt_test.go
@@ -69,7 +69,7 @@ func TestListUnadoptedRepositories_ListOptions(t *testing.T) {
username := "user2"
unadoptedList := []string{path.Join(username, "unadopted1"), path.Join(username, "unadopted2")}
for _, unadopted := range unadoptedList {
- _ = os.Mkdir(path.Join(setting.RepoRootPath, unadopted+".git"), 0755)
+ _ = os.Mkdir(path.Join(setting.RepoRootPath, unadopted+".git"), 0o755)
}
opts := db.ListOptions{Page: 1, PageSize: 1}
diff --git a/services/repository/archiver/archiver.go b/services/repository/archiver/archiver.go
index 93ec8bcca2..f982e2ef7b 100644
--- a/services/repository/archiver/archiver.go
+++ b/services/repository/archiver/archiver.go
@@ -172,7 +172,7 @@ func doArchive(r *ArchiveRequest) (*repo_model.RepoArchiver, error) {
w.Close()
rd.Close()
}()
- var done = make(chan error)
+ done := make(chan error)
repo, err := repo_model.GetRepositoryByID(archiver.RepoID)
if err != nil {
return nil, fmt.Errorf("archiver.LoadRepo failed: %v", err)
diff --git a/services/repository/archiver/archiver_test.go b/services/repository/archiver/archiver_test.go
index 2c0b46d3d4..b7fb6cb0ca 100644
--- a/services/repository/archiver/archiver_test.go
+++ b/services/repository/archiver/archiver_test.go
@@ -128,6 +128,6 @@ func TestArchive_Basic(t *testing.T) {
}
func TestErrUnknownArchiveFormat(t *testing.T) {
- var err = ErrUnknownArchiveFormat{RequestFormat: "master"}
+ err := ErrUnknownArchiveFormat{RequestFormat: "master"}
assert.True(t, errors.Is(err, ErrUnknownArchiveFormat{}))
}
diff --git a/services/repository/push.go b/services/repository/push.go
index 62e2104432..518ad04157 100644
--- a/services/repository/push.go
+++ b/services/repository/push.go
@@ -312,7 +312,7 @@ func pushUpdateAddTags(ctx context.Context, repo *repo_model.Repository, gitRepo
sig = commit.Committer
}
var author *user_model.User
- var createdAt = time.Unix(1, 0)
+ createdAt := time.Unix(1, 0)
if sig != nil {
var ok bool
diff --git a/services/task/task.go b/services/task/task.go
index 4994be87dd..376fe1dce1 100644
--- a/services/task/task.go
+++ b/services/task/task.go
@@ -92,7 +92,7 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*mod
return nil, err
}
- var task = &models.Task{
+ task := &models.Task{
DoerID: doer.ID,
OwnerID: u.ID,
Type: structs.TaskTypeMigrateRepo,
diff --git a/services/webhook/deliver.go b/services/webhook/deliver.go
index 36169baad4..88b709cb41 100644
--- a/services/webhook/deliver.go
+++ b/services/webhook/deliver.go
@@ -64,7 +64,7 @@ func Deliver(t *webhook_model.HookTask) error {
req.Header.Set("Content-Type", "application/json")
case webhook_model.ContentTypeForm:
- var forms = url.Values{
+ forms := url.Values{
"payload": []string{t.PayloadContent},
}
@@ -255,7 +255,6 @@ func DeliverHooks(ctx context.Context) {
}
}
}
-
}
var (
diff --git a/services/webhook/deliver_test.go b/services/webhook/deliver_test.go
index 551c957c8d..8d1d587c38 100644
--- a/services/webhook/deliver_test.go
+++ b/services/webhook/deliver_test.go
@@ -19,7 +19,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 a949b073a5..642cf6f2fd 100644
--- a/services/webhook/dingtalk.go
+++ b/services/webhook/dingtalk.go
@@ -23,9 +23,7 @@ type (
DingtalkPayload dingtalk.Payload
)
-var (
- _ PayloadConvertor = &DingtalkPayload{}
-)
+var _ PayloadConvertor = &DingtalkPayload{}
// JSONPayload Marshals the DingtalkPayload to json
func (d *DingtalkPayload) JSONPayload() ([]byte, error) {
@@ -135,7 +133,6 @@ func (d *DingtalkPayload) Review(p *api.PullRequestPayload, event webhook_model.
title = fmt.Sprintf("[%s] Pull request review %s : #%d %s", p.Repository.FullName, action, p.Index, p.PullRequest.Title)
text = p.Review.Content
-
}
return createDingtalkPayload(title, title+"\r\n\r\n"+text, "view pull request", p.PullRequest.HTMLURL), nil
diff --git a/services/webhook/discord.go b/services/webhook/discord.go
index 587d2098eb..ae5460b9a7 100644
--- a/services/webhook/discord.go
+++ b/services/webhook/discord.go
@@ -106,9 +106,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 18858c0994..5b20c7dda7 100644
--- a/services/webhook/feishu.go
+++ b/services/webhook/feishu.go
@@ -44,9 +44,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) {
@@ -80,7 +78,7 @@ func (f *FeishuPayload) Push(p *api.PushPayload) (api.Payloader, error) {
commitDesc string
)
- var text = fmt.Sprintf("[%s:%s] %s\r\n", p.Repo.FullName, branchName, commitDesc)
+ text := fmt.Sprintf("[%s:%s] %s\r\n", p.Repo.FullName, branchName, commitDesc)
// for each commit, generate attachment text
for i, commit := range p.Commits {
var authorName string
diff --git a/services/webhook/matrix.go b/services/webhook/matrix.go
index 72392debe9..a42ab2a93e 100644
--- a/services/webhook/matrix.go
+++ b/services/webhook/matrix.go
@@ -53,9 +53,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 {
diff --git a/services/webhook/msteams.go b/services/webhook/msteams.go
index ae5af8d9b6..59e2e93493 100644
--- a/services/webhook/msteams.go
+++ b/services/webhook/msteams.go
@@ -65,9 +65,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 a67fe6a762..11e1d3c081 100644
--- a/services/webhook/slack.go
+++ b/services/webhook/slack.go
@@ -96,9 +96,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 93c464fe73..64211493ec 100644
--- a/services/webhook/telegram.go
+++ b/services/webhook/telegram.go
@@ -40,9 +40,7 @@ func GetTelegramHook(w *webhook_model.Webhook) *TelegramMeta {
return s
}
-var (
- _ PayloadConvertor = &TelegramPayload{}
-)
+var _ PayloadConvertor = &TelegramPayload{}
// JSONPayload Marshals the TelegramPayload to json
func (t *TelegramPayload) JSONPayload() ([]byte, error) {
diff --git a/services/webhook/webhook.go b/services/webhook/webhook.go
index f284a20c30..bb7a9692d1 100644
--- a/services/webhook/webhook.go
+++ b/services/webhook/webhook.go
@@ -25,42 +25,40 @@ type webhook struct {
payloadCreator func(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error)
}
-var (
- webhooks = map[webhook_model.HookType]*webhook{
- webhook_model.SLACK: {
- name: webhook_model.SLACK,
- payloadCreator: GetSlackPayload,
- },
- webhook_model.DISCORD: {
- name: webhook_model.DISCORD,
- payloadCreator: GetDiscordPayload,
- },
- webhook_model.DINGTALK: {
- name: webhook_model.DINGTALK,
- payloadCreator: GetDingtalkPayload,
- },
- webhook_model.TELEGRAM: {
- name: webhook_model.TELEGRAM,
- payloadCreator: GetTelegramPayload,
- },
- webhook_model.MSTEAMS: {
- name: webhook_model.MSTEAMS,
- payloadCreator: GetMSTeamsPayload,
- },
- webhook_model.FEISHU: {
- name: webhook_model.FEISHU,
- payloadCreator: GetFeishuPayload,
- },
- webhook_model.MATRIX: {
- name: webhook_model.MATRIX,
- payloadCreator: GetMatrixPayload,
- },
- webhook_model.WECHATWORK: {
- name: webhook_model.WECHATWORK,
- payloadCreator: GetWechatworkPayload,
- },
- }
-)
+var webhooks = map[webhook_model.HookType]*webhook{
+ webhook_model.SLACK: {
+ name: webhook_model.SLACK,
+ payloadCreator: GetSlackPayload,
+ },
+ webhook_model.DISCORD: {
+ name: webhook_model.DISCORD,
+ payloadCreator: GetDiscordPayload,
+ },
+ webhook_model.DINGTALK: {
+ name: webhook_model.DINGTALK,
+ payloadCreator: GetDingtalkPayload,
+ },
+ webhook_model.TELEGRAM: {
+ name: webhook_model.TELEGRAM,
+ payloadCreator: GetTelegramPayload,
+ },
+ webhook_model.MSTEAMS: {
+ name: webhook_model.MSTEAMS,
+ payloadCreator: GetMSTeamsPayload,
+ },
+ webhook_model.FEISHU: {
+ name: webhook_model.FEISHU,
+ payloadCreator: GetFeishuPayload,
+ },
+ webhook_model.MATRIX: {
+ name: webhook_model.MATRIX,
+ payloadCreator: GetMatrixPayload,
+ },
+ webhook_model.WECHATWORK: {
+ name: webhook_model.WECHATWORK,
+ payloadCreator: GetWechatworkPayload,
+ },
+}
// RegisterWebhook registers a webhook
func RegisterWebhook(name string, webhook *webhook) {
diff --git a/services/webhook/wechatwork.go b/services/webhook/wechatwork.go
index e8ab07aaa0..de8b777066 100644
--- a/services/webhook/wechatwork.go
+++ b/services/webhook/wechatwork.go
@@ -52,9 +52,7 @@ func newWechatworkMarkdownPayload(title string) *WechatworkPayload {
}
}
-var (
- _ PayloadConvertor = &WechatworkPayload{}
-)
+var _ PayloadConvertor = &WechatworkPayload{}
// Create implements PayloadConvertor Create method
func (f *WechatworkPayload) Create(p *api.CreatePayload) (api.Payloader, error) {
@@ -72,12 +70,10 @@ func (f *WechatworkPayload) Delete(p *api.DeletePayload) (api.Payloader, error)
title := fmt.Sprintf("[%s] %s %s deleted", p.Repo.FullName, p.RefType, refName)
return newWechatworkMarkdownPayload(title), nil
-
}
// Fork implements PayloadConvertor Fork method
func (f *WechatworkPayload) Fork(p *api.ForkPayload) (api.Payloader, error) {
-
title := fmt.Sprintf("%s is forked to %s", p.Forkee.FullName, p.Repo.FullName)
return newWechatworkMarkdownPayload(title), nil
@@ -110,7 +106,6 @@ func (f *WechatworkPayload) Push(p *api.PushPayload) (api.Payloader, error) {
}
}
return newWechatworkMarkdownPayload(title + "\r\n\r\n" + text), nil
-
}
// Issue implements PayloadConvertor Issue method
@@ -120,7 +115,6 @@ func (f *WechatworkPayload) Issue(p *api.IssuePayload) (api.Payloader, error) {
content += fmt.Sprintf(" ><font color=\"info\">%s</font>\n >%s \n ><font color=\"warning\"> %s</font> \n [%s](%s)", text, attachmentText, issueTitle, p.Issue.HTMLURL, p.Issue.HTMLURL)
return newWechatworkMarkdownPayload(content), nil
-
}
// IssueComment implements PayloadConvertor IssueComment method
@@ -130,7 +124,6 @@ func (f *WechatworkPayload) IssueComment(p *api.IssueCommentPayload) (api.Payloa
content += fmt.Sprintf(" ><font color=\"info\">%s</font>\n >%s \n ><font color=\"warning\">%s</font> \n [%s](%s)", text, p.Comment.Body, issueTitle, p.Comment.HTMLURL, p.Comment.HTMLURL)
return newWechatworkMarkdownPayload(content), nil
-
}
// PullRequest implements PayloadConvertor PullRequest method
@@ -140,7 +133,6 @@ func (f *WechatworkPayload) PullRequest(p *api.PullRequestPayload) (api.Payloade
text, issueTitle, attachmentText)
return newWechatworkMarkdownPayload(pr), nil
-
}
// Review implements PayloadConvertor Review method
@@ -157,7 +149,6 @@ func (f *WechatworkPayload) Review(p *api.PullRequestPayload, event webhook_mode
}
return newWechatworkMarkdownPayload("# " + title + "\r\n\r\n >" + text), nil
-
}
// Repository implements PayloadConvertor Repository method
diff --git a/tools/fuzz.go b/tools/fuzz.go
index d629096ed6..64fda17b5d 100644
--- a/tools/fuzz.go
+++ b/tools/fuzz.go
@@ -24,16 +24,14 @@ import (
// (for example, the input is lexically correct and was parsed successfully).
// -1 if the input must not be added to corpus even if gives new coverage and 0 otherwise.
-var (
- renderContext = markup.RenderContext{
- Ctx: context.Background(),
- URLPrefix: "https://example.com/go-gitea/gitea",
- Metas: map[string]string{
- "user": "go-gitea",
- "repo": "gitea",
- },
- }
-)
+var renderContext = markup.RenderContext{
+ Ctx: context.Background(),
+ URLPrefix: "https://example.com/go-gitea/gitea",
+ Metas: map[string]string{
+ "user": "go-gitea",
+ "repo": "gitea",
+ },
+}
func FuzzMarkdownRenderRaw(data []byte) int {
setting.AppURL = "http://localhost:3000/"