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 //primary & activated + // User2 //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 //secondary and not activated + // User2 //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 \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 + // Import key + // User1 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": { `; rel="next"`, `; 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 == `` { @@ -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": "
1a
", "1,2": "
112
", "1;2\n3;4": "
112
234
", 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") + sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d" + repo := TestRepoURL + commit := util.URLJoin(repo, "commit", sha) + 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" + 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, `

65f1bf27bc

`) test(sha[:7], `

65f1bf2

`) @@ -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) { `

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

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

:gitea:

`) @@ -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+")", `

`+title+`

`) - } 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), "