From 64133126cdb842a047b2cd104c2f177f6e83f79a Mon Sep 17 00:00:00 2001
From: kolaente <k@knt.li>
Date: Sun, 11 Oct 2020 22:27:20 +0200
Subject: [PATCH] Update golangci-lint to version 1.31.0 (#13102)

This PR updates golangci-lint to the latest version 1.31.0.

The upgrade introduced a new check for which I've fixed or disabled most cases.

Signed-off-by: kolaente <k@knt.li>
---
 .golangci.yml                          |  6 ++++++
 Makefile                               |  2 +-
 main.go                                |  2 +-
 models/migrations/migrations.go        |  2 +-
 modules/git/hook.go                    |  2 +-
 modules/log/stack.go                   |  2 +-
 modules/markup/html.go                 |  6 +++---
 modules/markup/html_test.go            |  4 ++--
 modules/repository/check.go            |  2 +-
 modules/setting/repository.go          |  2 +-
 modules/setting/setting.go             |  6 +++---
 modules/structs/hook.go                |  2 +-
 modules/upload/upload.go               |  6 +++---
 modules/util/sanitize.go               |  2 +-
 modules/webhook/slack.go               | 12 ++++++------
 routers/install.go                     |  6 +++---
 routers/repo/download.go               |  2 +-
 routers/repo/editor.go                 |  2 +-
 routers/repo/http.go                   |  2 +-
 routers/repo/view.go                   |  8 ++++----
 routers/user/setting/security_twofa.go |  2 +-
 routers/utils/utils.go                 |  2 +-
 services/wiki/wiki.go                  |  6 +++---
 23 files changed, 47 insertions(+), 41 deletions(-)

diff --git a/.golangci.yml b/.golangci.yml
index a4f959e18a..95ad5f308a 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -101,3 +101,9 @@ issues:
     - path: cmd/dump.go
       linters:
         - dupl
+    - text: "commentFormatting: put a space between `//` and comment text"
+      linters:
+        - gocritic
+    - text: "exitAfterDefer:"
+      linters:
+        - gocritic
diff --git a/Makefile b/Makefile
index 3e992f15e1..25ebf78eb8 100644
--- a/Makefile
+++ b/Makefile
@@ -697,7 +697,7 @@ pr\#%: clean-all
 golangci-lint:
 	@hash golangci-lint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
 		export BINARY="golangci-lint"; \
-		curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.30.0; \
+		curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.31.0; \
 	fi
 	golangci-lint run --timeout 5m
 
diff --git a/main.go b/main.go
index 74e6911bb6..429314acc1 100644
--- a/main.go
+++ b/main.go
@@ -189,5 +189,5 @@ func formatBuiltWith() string {
 		return " built with " + version
 	}
 
-	return " built with " + version + " : " + strings.Replace(Tags, " ", ", ", -1)
+	return " built with " + version + " : " + strings.ReplaceAll(Tags, " ", ", ")
 }
diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go
index ea1bf59649..d36b984d93 100644
--- a/models/migrations/migrations.go
+++ b/models/migrations/migrations.go
@@ -680,7 +680,7 @@ func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
 			cols += "`" + strings.ToLower(col) + "`"
 		}
 		sql := fmt.Sprintf("SELECT Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('%[1]s') AND PARENT_COLUMN_ID IN (SELECT column_id FROM sys.columns WHERE lower(NAME) IN (%[2]s) AND object_id = OBJECT_ID('%[1]s'))",
-			tableName, strings.Replace(cols, "`", "'", -1))
+			tableName, strings.ReplaceAll(cols, "`", "'"))
 		constraints := make([]string, 0)
 		if err := sess.SQL(sql).Find(&constraints); err != nil {
 			return fmt.Errorf("Find constraints: %v", err)
diff --git a/modules/git/hook.go b/modules/git/hook.go
index 2b9f90efd3..2de36dbdef 100644
--- a/modules/git/hook.go
+++ b/modules/git/hook.go
@@ -96,7 +96,7 @@ func (h *Hook) Update() error {
 		return err
 	}
 
-	err := ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm)
+	err := ioutil.WriteFile(h.path, []byte(strings.ReplaceAll(h.Content, "\r", "")), os.ModePerm)
 	if err != nil {
 		return err
 	}
diff --git a/modules/log/stack.go b/modules/log/stack.go
index ffe9aa67cc..568c10cd00 100644
--- a/modules/log/stack.go
+++ b/modules/log/stack.go
@@ -69,7 +69,7 @@ func functionName(programCounter uintptr) []byte {
 		name = name[period+1:]
 	}
 	// And we should just replace the interpunct with a dot
-	name = bytes.Replace(name, []byte("·"), []byte("."), -1)
+	name = bytes.ReplaceAll(name, []byte("·"), []byte("."))
 	return name
 }
 
diff --git a/modules/markup/html.go b/modules/markup/html.go
index bef6269a69..f5f811b59b 100644
--- a/modules/markup/html.go
+++ b/modules/markup/html.go
@@ -683,9 +683,9 @@ func shortLinkProcessorFull(ctx *postProcessCtx, node *html.Node, noLink bool) {
 	absoluteLink := isLinkStr(link)
 	if !absoluteLink {
 		if image {
-			link = strings.Replace(link, " ", "+", -1)
+			link = strings.ReplaceAll(link, " ", "+")
 		} else {
-			link = strings.Replace(link, " ", "-", -1)
+			link = strings.ReplaceAll(link, " ", "-")
 		}
 		if !strings.Contains(link, "/") {
 			link = url.PathEscape(link)
@@ -902,7 +902,7 @@ func emojiShortCodeProcessor(ctx *postProcessCtx, node *html.Node) {
 	}
 
 	alias := node.Data[m[0]:m[1]]
-	alias = strings.Replace(alias, ":", "", -1)
+	alias = strings.ReplaceAll(alias, ":", "")
 	converted := emoji.FromAlias(alias)
 	if converted == nil {
 		// check if this is a custom reaction
diff --git a/modules/markup/html_test.go b/modules/markup/html_test.go
index 7f820d3990..a018d74840 100644
--- a/modules/markup/html_test.go
+++ b/modules/markup/html_test.go
@@ -35,7 +35,7 @@ func TestRender_Commits(t *testing.T) {
 	var sha = "65f1bf27bc3bf70f64657658635e66094edbcb4d"
 	var commit = util.URLJoin(AppSubURL, "commit", sha)
 	var subtree = util.URLJoin(commit, "src")
-	var tree = strings.Replace(subtree, "/commit/", "/tree/", -1)
+	var tree = strings.ReplaceAll(subtree, "/commit/", "/tree/")
 
 	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>`)
@@ -235,7 +235,7 @@ func TestRender_emoji(t *testing.T) {
 	setting.StaticURLPrefix = AppURL
 
 	test := func(input, expected string) {
-		expected = strings.Replace(expected, "&", "&amp;", -1)
+		expected = strings.ReplaceAll(expected, "&", "&amp;")
 		buffer := RenderString("a.md", input, setting.AppSubURL, nil)
 		assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer))
 	}
diff --git a/modules/repository/check.go b/modules/repository/check.go
index 90186d6a29..274576c348 100644
--- a/modules/repository/check.go
+++ b/modules/repository/check.go
@@ -120,7 +120,7 @@ func gatherMissingRepoRecords(ctx context.Context) ([]*models.Repository, error)
 			return nil
 		},
 	); err != nil {
-		if strings.HasPrefix("Aborted gathering missing repo", err.Error()) {
+		if strings.HasPrefix(err.Error(), "Aborted gathering missing repo") {
 			return nil, err
 		}
 		if err2 := models.CreateRepositoryNotice("gatherMissingRepoRecords: %v", err); err2 != nil {
diff --git a/modules/setting/repository.go b/modules/setting/repository.go
index 96159e2f4a..0bb10199a8 100644
--- a/modules/setting/repository.go
+++ b/modules/setting/repository.go
@@ -253,7 +253,7 @@ func newRepository() {
 	if err != nil {
 		log.Fatal("Failed to get home directory: %v", err)
 	}
-	homeDir = strings.Replace(homeDir, "\\", "/", -1)
+	homeDir = strings.ReplaceAll(homeDir, "\\", "/")
 
 	// Determine and create root git repository path.
 	sec := Cfg.Section("repository")
diff --git a/modules/setting/setting.go b/modules/setting/setting.go
index 8088cffcdf..69f0080f64 100644
--- a/modules/setting/setting.go
+++ b/modules/setting/setting.go
@@ -405,7 +405,7 @@ func getAppPath() (string, error) {
 	}
 	// Note: we don't use path.Dir here because it does not handle case
 	//	which path starts with two "/" in Windows: "//psf/Home/..."
-	return strings.Replace(appPath, "\\", "/", -1), err
+	return strings.ReplaceAll(appPath, "\\", "/"), err
 }
 
 func getWorkPath(appPath string) string {
@@ -422,7 +422,7 @@ func getWorkPath(appPath string) string {
 			workPath = appPath[:i]
 		}
 	}
-	return strings.Replace(workPath, "\\", "/", -1)
+	return strings.ReplaceAll(workPath, "\\", "/")
 }
 
 func init() {
@@ -524,7 +524,7 @@ func NewContext() {
 	if err != nil {
 		log.Fatal("Failed to get home directory: %v", err)
 	}
-	homeDir = strings.Replace(homeDir, "\\", "/", -1)
+	homeDir = strings.ReplaceAll(homeDir, "\\", "/")
 
 	LogLevel = getLogLevel(Cfg.Section("log"), "LEVEL", "Info")
 	StacktraceLogLevel = getStacktraceLogLevel(Cfg.Section("log"), "STACKTRACE_LEVEL", "None")
diff --git a/modules/structs/hook.go b/modules/structs/hook.go
index a10dd4281c..45ae94f985 100644
--- a/modules/structs/hook.go
+++ b/modules/structs/hook.go
@@ -338,7 +338,7 @@ func ParsePushHook(raw []byte) (*PushPayload, error) {
 
 // Branch returns branch name from a payload
 func (p *PushPayload) Branch() string {
-	return strings.Replace(p.Ref, "refs/heads/", "", -1)
+	return strings.ReplaceAll(p.Ref, "refs/heads/", "")
 }
 
 // .___
diff --git a/modules/upload/upload.go b/modules/upload/upload.go
index 97f0df0542..e430a5d8b3 100644
--- a/modules/upload/upload.go
+++ b/modules/upload/upload.go
@@ -76,7 +76,7 @@ func AddUploadContext(ctx *context.Context, uploadType string) {
 		ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/releases/attachments"
 		ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/releases/attachments/remove"
 		ctx.Data["UploadLinkUrl"] = ctx.Repo.RepoLink + "/releases/attachments"
-		ctx.Data["UploadAccepts"] = strings.Replace(setting.Repository.Release.AllowedTypes, "|", ",", -1)
+		ctx.Data["UploadAccepts"] = strings.ReplaceAll(setting.Repository.Release.AllowedTypes, "|", ",")
 		ctx.Data["UploadMaxFiles"] = setting.Attachment.MaxFiles
 		ctx.Data["UploadMaxSize"] = setting.Attachment.MaxSize
 	} else if uploadType == "comment" {
@@ -87,14 +87,14 @@ func AddUploadContext(ctx *context.Context, uploadType string) {
 		} else {
 			ctx.Data["UploadLinkUrl"] = ctx.Repo.RepoLink + "/issues/attachments"
 		}
-		ctx.Data["UploadAccepts"] = strings.Replace(setting.Attachment.AllowedTypes, "|", ",", -1)
+		ctx.Data["UploadAccepts"] = strings.ReplaceAll(setting.Attachment.AllowedTypes, "|", ",")
 		ctx.Data["UploadMaxFiles"] = setting.Attachment.MaxFiles
 		ctx.Data["UploadMaxSize"] = setting.Attachment.MaxSize
 	} else if uploadType == "repo" {
 		ctx.Data["UploadUrl"] = ctx.Repo.RepoLink + "/upload-file"
 		ctx.Data["UploadRemoveUrl"] = ctx.Repo.RepoLink + "/upload-remove"
 		ctx.Data["UploadLinkUrl"] = ctx.Repo.RepoLink + "/upload-file"
-		ctx.Data["UploadAccepts"] = strings.Replace(setting.Repository.Upload.AllowedTypes, "|", ",", -1)
+		ctx.Data["UploadAccepts"] = strings.ReplaceAll(setting.Repository.Upload.AllowedTypes, "|", ",")
 		ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles
 		ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize
 	}
diff --git a/modules/util/sanitize.go b/modules/util/sanitize.go
index b1c17b29cf..a4f5479dfb 100644
--- a/modules/util/sanitize.go
+++ b/modules/util/sanitize.go
@@ -28,7 +28,7 @@ func URLSanitizedError(err error, unsanitizedURL string) error {
 // SanitizeMessage sanitizes a message which may contains a sensitive URL
 func SanitizeMessage(message, unsanitizedURL string) string {
 	sanitizedURL := SanitizeURLCredentials(unsanitizedURL, true)
-	return strings.Replace(message, unsanitizedURL, sanitizedURL, -1)
+	return strings.ReplaceAll(message, unsanitizedURL, sanitizedURL)
 }
 
 // SanitizeURLCredentials sanitizes a url, either removing user credentials
diff --git a/modules/webhook/slack.go b/modules/webhook/slack.go
index 4c0b50ecab..aaecad6c67 100644
--- a/modules/webhook/slack.go
+++ b/modules/webhook/slack.go
@@ -71,9 +71,9 @@ func (s *SlackPayload) JSONPayload() ([]byte, error) {
 // see: https://api.slack.com/docs/formatting
 func SlackTextFormatter(s string) string {
 	// replace & < >
-	s = strings.Replace(s, "&", "&amp;", -1)
-	s = strings.Replace(s, "<", "&lt;", -1)
-	s = strings.Replace(s, ">", "&gt;", -1)
+	s = strings.ReplaceAll(s, "&", "&amp;")
+	s = strings.ReplaceAll(s, "<", "&lt;")
+	s = strings.ReplaceAll(s, ">", "&gt;")
 	return s
 }
 
@@ -81,9 +81,9 @@ func SlackTextFormatter(s string) string {
 func SlackShortTextFormatter(s string) string {
 	s = strings.Split(s, "\n")[0]
 	// replace & < >
-	s = strings.Replace(s, "&", "&amp;", -1)
-	s = strings.Replace(s, "<", "&lt;", -1)
-	s = strings.Replace(s, ">", "&gt;", -1)
+	s = strings.ReplaceAll(s, "&", "&amp;")
+	s = strings.ReplaceAll(s, "<", "&lt;")
+	s = strings.ReplaceAll(s, ">", "&gt;")
 	return s
 }
 
diff --git a/routers/install.go b/routers/install.go
index a136cf44b2..a7fe557748 100644
--- a/routers/install.go
+++ b/routers/install.go
@@ -172,7 +172,7 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
 	}
 
 	// Test repository root path.
-	form.RepoRootPath = strings.Replace(form.RepoRootPath, "\\", "/", -1)
+	form.RepoRootPath = strings.ReplaceAll(form.RepoRootPath, "\\", "/")
 	if err = os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil {
 		ctx.Data["Err_RepoRootPath"] = true
 		ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), tplInstall, &form)
@@ -181,7 +181,7 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
 
 	// Test LFS root path if not empty, empty meaning disable LFS
 	if form.LFSRootPath != "" {
-		form.LFSRootPath = strings.Replace(form.LFSRootPath, "\\", "/", -1)
+		form.LFSRootPath = strings.ReplaceAll(form.LFSRootPath, "\\", "/")
 		if err := os.MkdirAll(form.LFSRootPath, os.ModePerm); err != nil {
 			ctx.Data["Err_LFSRootPath"] = true
 			ctx.RenderWithErr(ctx.Tr("install.invalid_lfs_path", err), tplInstall, &form)
@@ -190,7 +190,7 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
 	}
 
 	// Test log root path.
-	form.LogRootPath = strings.Replace(form.LogRootPath, "\\", "/", -1)
+	form.LogRootPath = strings.ReplaceAll(form.LogRootPath, "\\", "/")
 	if err = os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil {
 		ctx.Data["Err_LogRootPath"] = true
 		ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), tplInstall, &form)
diff --git a/routers/repo/download.go b/routers/repo/download.go
index 326f097cbc..2f1f2d3c47 100644
--- a/routers/repo/download.go
+++ b/routers/repo/download.go
@@ -34,7 +34,7 @@ func ServeData(ctx *context.Context, name string, reader io.Reader) error {
 	name = path.Base(name)
 
 	// Google Chrome dislike commas in filenames, so let's change it to a space
-	name = strings.Replace(name, ",", " ", -1)
+	name = strings.ReplaceAll(name, ",", " ")
 
 	if base.IsTextFile(buf) || ctx.QueryBool("render") {
 		cs, err := charset.DetectEncoding(buf)
diff --git a/routers/repo/editor.go b/routers/repo/editor.go
index aa10bd146a..a08c7193f8 100644
--- a/routers/repo/editor.go
+++ b/routers/repo/editor.go
@@ -238,7 +238,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
 		FromTreePath: ctx.Repo.TreePath,
 		TreePath:     form.TreePath,
 		Message:      message,
-		Content:      strings.Replace(form.Content, "\r", "", -1),
+		Content:      strings.ReplaceAll(form.Content, "\r", ""),
 		IsNewFile:    isNewFile,
 	}); err != nil {
 		// This is where we handle all the errors thrown by repofiles.CreateOrUpdateRepoFile
diff --git a/routers/repo/http.go b/routers/repo/http.go
index 0d5aa2e3e2..23f2665dfd 100644
--- a/routers/repo/http.go
+++ b/routers/repo/http.go
@@ -497,7 +497,7 @@ func getGitConfig(option, dir string) string {
 }
 
 func getConfigSetting(service, dir string) bool {
-	service = strings.Replace(service, "-", "", -1)
+	service = strings.ReplaceAll(service, "-", "")
 	setting := getGitConfig("http."+service, dir)
 
 	if service == "uploadpack" {
diff --git a/routers/repo/view.go b/routers/repo/view.go
index 3e2a57415d..2df5b30ce8 100644
--- a/routers/repo/view.go
+++ b/routers/repo/view.go
@@ -332,8 +332,8 @@ func renderDirectory(ctx *context.Context, treeLink string) {
 					ctx.Data["FileContent"] = string(markup.Render(readmeFile.name, buf, readmeTreelink, ctx.Repo.Repository.ComposeDocumentMetas()))
 				} else {
 					ctx.Data["IsRenderedHTML"] = true
-					ctx.Data["FileContent"] = strings.Replace(
-						gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
+					ctx.Data["FileContent"] = strings.ReplaceAll(
+						gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`,
 					)
 				}
 			}
@@ -471,8 +471,8 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
 			ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeDocumentMetas()))
 		} else if readmeExist {
 			ctx.Data["IsRenderedHTML"] = true
-			ctx.Data["FileContent"] = strings.Replace(
-				gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
+			ctx.Data["FileContent"] = strings.ReplaceAll(
+				gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`,
 			)
 		} else {
 			buf = charset.ToUTF8WithFallback(buf)
diff --git a/routers/user/setting/security_twofa.go b/routers/user/setting/security_twofa.go
index ed87f00436..4ee698e15e 100644
--- a/routers/user/setting/security_twofa.go
+++ b/routers/user/setting/security_twofa.go
@@ -93,7 +93,7 @@ func twofaGenerateSecretAndQr(ctx *context.Context) bool {
 		}
 	}
 	// Filter unsafe character ':' in issuer
-	issuer := strings.Replace(setting.AppName+" ("+setting.Domain+")", ":", "", -1)
+	issuer := strings.ReplaceAll(setting.AppName+" ("+setting.Domain+")", ":", "")
 	if otpKey == nil {
 		otpKey, err = totp.Generate(totp.GenerateOpts{
 			SecretSize:  40,
diff --git a/routers/utils/utils.go b/routers/utils/utils.go
index 7c845f8763..d8060ff077 100644
--- a/routers/utils/utils.go
+++ b/routers/utils/utils.go
@@ -47,7 +47,7 @@ func SanitizeFlashErrorString(x string) string {
 		x = "..." + string(runes[len(runes)-512:])
 	}
 
-	return strings.Replace(html.EscapeString(x), "\n", "<br>", -1)
+	return strings.ReplaceAll(html.EscapeString(x), "\n", "<br>")
 }
 
 // IsExternalURL checks if rawURL points to an external URL like http://example.com
diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go
index fab02bae0c..5f7d26a045 100644
--- a/services/wiki/wiki.go
+++ b/services/wiki/wiki.go
@@ -37,17 +37,17 @@ func nameAllowed(name string) error {
 
 // NameToSubURL converts a wiki name to its corresponding sub-URL.
 func NameToSubURL(name string) string {
-	return url.QueryEscape(strings.Replace(name, " ", "-", -1))
+	return url.QueryEscape(strings.ReplaceAll(name, " ", "-"))
 }
 
 // NormalizeWikiName normalizes a wiki name
 func NormalizeWikiName(name string) string {
-	return strings.Replace(name, "-", " ", -1)
+	return strings.ReplaceAll(name, "-", " ")
 }
 
 // NameToFilename converts a wiki name to its corresponding filename.
 func NameToFilename(name string) string {
-	name = strings.Replace(name, " ", "-", -1)
+	name = strings.ReplaceAll(name, " ", "-")
 	return url.QueryEscape(name) + ".md"
 }