Changes
423 changed files (+1586/-1759)
-
-
@@ -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:
-
-
-
@@ -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:
-
-
-
@@ -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...)
-
-
-
@@ -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 }
-
-
-
@@ -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) }
-
-
-
@@ -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 (
-
-
-
@@ -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) }
-
-
-
@@ -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) }
-
-
-
@@ -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") }
-
-
-
@@ -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 }
-
-
-
@@ -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", }, },
-
-
-
@@ -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) }
-
-
-
@@ -121,7 +121,6 @@ func runRecreateTable(ctx *cli.Context) error {} return recreateTables(x) }) } func runDoctor(ctx *cli.Context) error {
-
-
-
@@ -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) } }
-
-
-
@@ -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"),
-
-
-
@@ -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 } }
-
-
-
@@ -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", },
-
-
-
@@ -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))
-
-
-
@@ -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) }
-
-
-
@@ -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) }
-
-
-
@@ -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)
-
-
-
@@ -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:]...)
-
-
-
@@ -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",
-
-
-
@@ -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()
-
-
-
@@ -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())
-
-
-
@@ -28,15 +28,18 @@ func TestGPGKeys(t *testing.T) {token string results []int }{ {name: "NoLogin", makeRequest: MakeRequest, token: "", { name: "NoLogin", makeRequest: MakeRequest, token: "", results: []int{http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized}, }, {name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated}}, { name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated}, }, } for _, tc := range tt { //Basic test on result code // Basic test on result code t.Run(tc.name, func(t *testing.T) { t.Run("ViewOwnGPGKeys", func(t *testing.T) { testViewOwnGPGKeys(t, tc.makeRequest, tc.token, tc.results[0])
-
@@ -66,28 +69,27 @@ func TestGPGKeys(t *testing.T) {}) } //Check state after basic add // Check state after basic add t.Run("CheckState", func(t *testing.T) { var keys []*api.GPGKey req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) //GET all keys req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) // GET all keys resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &keys) assert.Len(t, keys, 1) primaryKey1 := keys[0] //Primary key 1 primaryKey1 := keys[0] // Primary key 1 assert.EqualValues(t, "38EA3BCED732982C", primaryKey1.KeyID) assert.Len(t, primaryKey1.Emails, 1) assert.EqualValues(t, "user2@example.com", primaryKey1.Emails[0].Email) assert.True(t, primaryKey1.Emails[0].Verified) subKey := primaryKey1.SubsKey[0] //Subkey of 38EA3BCED732982C subKey := primaryKey1.SubsKey[0] // Subkey of 38EA3BCED732982C assert.EqualValues(t, "70D7C694D17D03AD", subKey.KeyID) assert.Empty(t, subKey.Emails) var key api.GPGKey req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) //Primary key 1 req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) // Primary key 1 resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "38EA3BCED732982C", key.KeyID)
-
@@ -95,14 +97,14 @@ func TestGPGKeys(t *testing.T) {assert.EqualValues(t, "user2@example.com", key.Emails[0].Email) assert.True(t, key.Emails[0].Verified) req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) //Subkey of 38EA3BCED732982C req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) // Subkey of 38EA3BCED732982C resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID) assert.Empty(t, key.Emails) }) //Check state after basic add // Check state after basic add t.Run("CheckCommits", func(t *testing.T) { t.Run("NotSigned", func(t *testing.T) { var branch api.Branch
-
@@ -182,7 +184,7 @@ INx/MmBfmtCq05FqNclvU+sj2R3N1JJOtBOjZrJHQbJhzoILou8AkxeX1A+q9OAz} func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { //User2 <user2@example.com> //primary & activated // User2 <user2@example.com> //primary & activated testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW
-
@@ -216,7 +218,7 @@ uy6MA3VSB99SK9ducGmE1Jv8mcziREroz2TEGr0zPs6h} func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { //User2 <user2-2@example.com> //secondary and not activated // User2 <user2-2@example.com> //secondary and not activated testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQGNBGC2K2cBDAC1+Xgk+8UfhASVgRngQi4rnQ8k0t+bWsBz4Czd26+cxVDRwlTT
-
-
-
@@ -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) }
-
-
-
@@ -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
-
-
-
@@ -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)
-
-
-
@@ -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()
-
-
-
@@ -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)
-
-
-
@@ -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)
-
-
-
@@ -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)
-
-
-
@@ -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) }) }
-
-
-
@@ -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
-
-
-
@@ -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
-
-
-
@@ -130,7 +130,6 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) {assert.EqualValues(t, "From f27c2b2b03dcab38beaf89b0ab4ff61f6de63441 Mon Sep 17 00:00:00 2001\nFrom: User2 <user2@example.com>\nDate: Sun, 6 Aug 2017 19:55:01 +0200\nSubject: [PATCH] good signed commit\n\n---\n readme.md | 1 +\n 1 file changed, 1 insertion(+)\n create mode 100644 readme.md\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n", resp.Body.String()) } func TestGetFileHistory(t *testing.T) {
-
-
-
@@ -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{})
-
-
-
@@ -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)
-
-
-
@@ -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) }
-
-
-
@@ -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()
-
-
-
@@ -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)
-
-
-
@@ -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) })
-
-
-
@@ -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)
-
-
-
@@ -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 }) }
-
-
-
@@ -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))
-
-
-
@@ -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)
-
-
-
@@ -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)
-
-
-
@@ -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",
-
-
-
@@ -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 }{
-
-
-
@@ -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 strinreturn "", 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, headBt.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 }
-
-
-
@@ -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) }
-
-
-
@@ -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) *TestSessionreturn 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) } } }
-
-
-
@@ -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) {
-
-
-
@@ -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
-
-
-
@@ -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",
-
-
-
@@ -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) }) } }
-
-
-
@@ -210,5 +210,4 @@ func TestNonasciiBranches(t *testing.T) {} setDefaultBranch(t, session, user, repo, "master") }
-
-
-
@@ -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"
-
-
-
@@ -65,7 +65,7 @@ func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum strfunc 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)
-
-
-
@@ -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.Pulassert.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-",
-
-
-
@@ -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)
-
-
-
@@ -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)
-
-
-
@@ -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)
-
-
-
@@ -77,7 +77,6 @@ func TestSettingShowUserEmailProfile(t *testing.T) {htmlDoc.doc.Find(".user.profile").Text(), "user2@example.com", ) } func TestSettingLandingPage(t *testing.T) {
-
-
-
@@ -28,7 +28,7 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testinfunc 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))
-
-
-
@@ -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 }
-
-
-
@@ -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")
-
-
-
@@ -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")
-
-
-
@@ -119,15 +119,15 @@ func TestRenameReservedUsername(t *testing.T) {func TestExportUserGPGKeys(t *testing.T) { defer prepareTestEnv(t)() //Export empty key list // Export empty key list testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK----- =twTO -----END PGP PUBLIC KEY BLOCK----- `) //Import key //User1 <user1@example.com> // Import key // User1 <user1@example.com> session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK-----
-
@@ -161,7 +161,7 @@ GrE0MHOxUbc9tbtyk0F1SuzREUBH=DDXw -----END PGP PUBLIC KEY BLOCK----- `) //Export new key // Export new key testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK----- xsBNBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo
-
@@ -200,6 +200,6 @@ func testExportUserGPGKeys(t *testing.T, user, expected string) {t.Logf("Testing username %s export gpg keys", user) req := NewRequest(t, "GET", "/"+user+".gpg") resp := session.MakeRequest(t, req, http.StatusOK) //t.Log(resp.Body.String()) // t.Log(resp.Body.String()) assert.Equal(t, expected, resp.Body.String()) }
-
-
-
@@ -186,7 +186,7 @@ DEFAULT CONFIGURATION:} func formatBuiltWith() string { var version = runtime.Version() version := runtime.Version() if len(MakeVersion) > 0 { version = MakeVersion + ", " + runtime.Version() }
-
-
-
@@ -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) (WebAuthnCredenreturn 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 {
-
-
-
@@ -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) }
-
-
-
@@ -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 }
-
-
-
@@ -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...) }
-
-
-
@@ -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) {
-
-
-
@@ -155,7 +155,6 @@ func FetchIssueContentHistoryList(dbCtx context.Context, issueID, commentID int6Where(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
-
-
-
@@ -209,7 +209,7 @@ func LFSAutoAssociate(metas []*LFSMetaObject, user *user_model.User, repoID int6func 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 {
-
-
-
@@ -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, }
-
-
-
@@ -219,10 +219,10 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.Enassert.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) } }
-
-
-
@@ -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 }
-
-
-
@@ -124,5 +124,4 @@ func Test_removeInvalidLabels(t *testing.T) {t.Errorf("IssueLabel[%d] was deleted but should have remained", id) } } }
-
-
-
@@ -85,5 +85,4 @@ func Test_deleteOrphanedIssueLabels(t *testing.T) {pre := preMigration[id] assert.Equal(t, pre, post, "migration changed issueLabel %d", id) } }
-
-
-
@@ -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)
-
-
-
@@ -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)
-
-
-
@@ -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) } } }
-
-
-
@@ -11,7 +11,6 @@ import () func alterIssueAndCommentTextFieldsToLongText(x *xorm.Engine) error { sess := x.NewSession() defer sess.Close() if err := sess.Begin(); err != nil {
-
-
-
@@ -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)
-
-
-
@@ -16,7 +16,6 @@ import () func addWebAuthnCred(x *xorm.Engine) error { // Create webauthnCredential table type webauthnCredential struct { ID int64 `xorm:"pk autoincr"`
-
-
-
@@ -12,7 +12,6 @@ import () func useBase32HexForCredIDInWebAuthnCredential(x *xorm.Engine) error { // Create webauthnCredential table type webauthnCredential struct { ID int64 `xorm:"pk autoincr"`
-
-
-
@@ -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()) }
-
-
-
@@ -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").
-
-
-
@@ -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 {
-
-
-
@@ -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 {
-
-
-
@@ -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 {
-
-
-
@@ -199,5 +199,4 @@ func TestDismissReview(t *testing.T) {assert.False(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.True(t, approveReviewExample.Dismissed) }
-
-
-
@@ -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) } }
-
-
-
@@ -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 {
-
-
-
@@ -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) {
-
-
-
@@ -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 {
-
-
-
@@ -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 {
-
-
-
@@ -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) {
-
-
-
@@ -27,7 +27,6 @@ func Auth(serviceName, userName, passwd string) (string, error) {} return "", errors.New("Unrecognized PAM message style") }) if err != nil { return "", err }
-
-
-
@@ -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 {
-
-
-
@@ -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
-
-
-
@@ -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)
-
-
-
@@ -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{
-
-
-
@@ -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()
-
-
-
@@ -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)
-
-
-
@@ -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)
-
-
-
@@ -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
-
-
-
@@ -16,7 +16,7 @@ import (func TestGenAPILinks(t *testing.T) { setting.AppURL = "http://localhost:3000/" var kases = map[string][]string{ kases := map[string][]string{ "api/v1/repos/jerrykan/example-repo/issues?state=all": { `<http://localhost:3000/api/v1/repos/jerrykan/example-repo/issues?page=2&state=all>; rel="next"`, `<http://localhost:3000/api/v1/repos/jerrykan/example-repo/issues?page=5&state=all>; rel="last"`,
-
-
-
@@ -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 {
-
-
-
@@ -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,
-
-
-
@@ -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
-
-
-
@@ -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 {
-
-
-
@@ -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 }
-
-
-
@@ -17,9 +17,7 @@ type ResponseWriter interface {Size() int } var ( _ ResponseWriter = &Response{} ) var _ ResponseWriter = &Response{} // Response represents a response type Response struct {
-
-
-
@@ -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)) }
-
-
-
@@ -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())
-
-
-
@@ -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
-
-
-
@@ -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 }
-
-
-
@@ -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
-
-
-
@@ -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
-
-
-
@@ -296,7 +296,6 @@ func fixBrokenRepoUnits16961(ctx context.Context, logger log.Logger, autofix booreturn repo_model.UpdateRepoUnit(repoUnit) }, ) if err != nil { logger.Critical("Unable to iterate across repounits to fix the broken units: Error %v", err) return err
-
-
-
@@ -119,7 +119,6 @@ func checkEnablePushOptions(ctx context.Context, logger log.Logger, autofix boollogger.Info("Enabled push options for %d repositories.", numRepos) } else { logger.Info("Checked %d repositories, %d need updates.", numRepos, numNeedUpdate) } return nil
-
-
-
@@ -27,7 +27,7 @@ func checkConfigurationFile(logger log.Logger, autofix bool, fileOpts configuratfi, 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) }
-
-
-
@@ -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,
-
-
-
@@ -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.
-
-
-
@@ -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.
-
-
-
@@ -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 {
-
-
-
@@ -104,7 +104,7 @@ func getLastCommitForPathsByCache(ctx context.Context, commitID, treePath stringdefer 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 {
-
-
-
@@ -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)
-
-
-
@@ -234,5 +234,4 @@ func TestParseCommitFileStatus(t *testing.T) {assert.Equal(t, kase.removed, fileStatus.Removed) assert.Equal(t, kase.modified, fileStatus.Modified) } }
-
-
-
@@ -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"
-
-
-
@@ -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) }
-
-
-
@@ -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)
-
-
-
@@ -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 {
-
-
-
@@ -14,7 +14,6 @@ import () func TestParseTreeEntries(t *testing.T) { testCases := []struct { Input string Expected []*TreeEntry
-
-
-
@@ -146,7 +146,7 @@ func CloneWithArgs(ctx context.Context, from, to string, args []string, opts Cloopts.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,
-
-
-
@@ -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])
-
-
-
@@ -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: "))
-
-
-
@@ -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 }
-
-
-
@@ -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)
-
-
-
@@ -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 )
-
-
-
@@ -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 }
-
-
-
@@ -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 {
-
-
-
@@ -11,7 +11,7 @@ import () func TestGetRefURL(t *testing.T) { var kases = []struct { kases := []struct { refURL string prefixURL string parentPath string
-
-
-
@@ -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 {
-
-
-
@@ -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,
-
-
-
@@ -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
-
-
-
@@ -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:")
-
-
-
@@ -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]
-
-
-
@@ -190,6 +190,7 @@ func (g *Manager) RunAtHammer(hammer func()) {hammer() }) } func (g *Manager) doShutdown() { if !g.setStateTransition(stateRunning, stateShuttingDown) { return
-
-
-
@@ -83,7 +83,7 @@ func Code(fileName, language, code string) string {if lexer == nil { if val, ok := highlightMapping[filepath.Ext(fileName)]; ok { //use mapped value to find lexer // use mapped value to find lexer lexer = lexers.Get(val) } }
-
@@ -198,7 +198,7 @@ func File(numLines int, fileName, language string, code []byte) []string {m := make([]string, 0, numLines) for _, v := range strings.SplitN(htmlbuf.String(), "\n", numLines) { content := string(v) //need to keep lines that are only \n so copy/paste works properly in browser // need to keep lines that are only \n so copy/paste works properly in browser if content == "" { content = "\n" } else if content == `</span><span class="w">` {
-
@@ -220,7 +220,7 @@ func plainText(code string, numLines int) []string {m := make([]string, 0, numLines) for _, v := range strings.SplitN(string(code), "\n", numLines) { content := string(v) //need to keep lines that are only \n so copy/paste works properly in browser // need to keep lines that are only \n so copy/paste works properly in browser if content == "" { content = "\n" }
-
-
-
@@ -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) }
-
-
-
@@ -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")) }
-
-
-
@@ -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) }
-
-
-
@@ -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) {
-
-
-
@@ -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)
-
-
-
@@ -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)
-
-
-
@@ -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() {
-
-
-
@@ -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 {
-
-
-
@@ -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) }
-
-
-
@@ -7,8 +7,7 @@ package issuesimport "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) (*Searif err != nil { return nil, err } var result = SearchResult{ result := SearchResult{ Total: total, Hits: make([]Match, 0, limit), }
-
-
-
@@ -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, stquery := 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) }
-
-
-
@@ -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) {
-
-
-
@@ -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 {
-
-
-
@@ -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
-
-
-
@@ -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 }{
-
-
-
@@ -51,7 +51,6 @@ func SearchPointerBlobs(ctx context.Context, repo *git.Repository, pointerChan creturn nil }) }() if err != nil { select { case <-ctx.Done():
-
-
-
@@ -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) *ColoreresetBytes: &resetBytes, Value: value, } } // NewColoredValueBytes creates a value from the provided value with color bytes
-
-
-
@@ -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()
-
-
-
@@ -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) }
-
-
-
@@ -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++ {
-
-
-
@@ -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) {
-
-
-
@@ -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
-
-
-
@@ -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
-
-
-
@@ -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] }
-
-
-
@@ -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.Conreturn 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
-
-
-
@@ -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?://")
-
-
-
@@ -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.Contvar 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{}
-
-
-
@@ -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)
-
-
-
@@ -15,7 +15,7 @@ import (func TestRenderCSV(t *testing.T) { var render Renderer var kases = map[string]string{ kases := map[string]string{ "a": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>a</th></tr></table>", "1,2": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>1</th><th>2</th></tr></table>", "1;2\n3;4": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>1</th><th>2</th></tr><tr><td class=\"line-num\">2</td><td>3</td><td>4</td></tr></table>",
-
-
-
@@ -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()
-
-
-
@@ -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 {
-
-
-
@@ -38,17 +38,17 @@ func TestRender_Commits(t *testing.T) {assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } var sha = "65f1bf27bc3bf70f64657658635e66094edbcb4d" var repo = TestRepoURL var commit = util.URLJoin(repo, "commit", sha) var tree = util.URLJoin(repo, "tree", sha, "src") var file = util.URLJoin(repo, "commit", sha, "example.txt") var fileWithExtra = file + ":" var fileWithHash = file + "#L2" var fileWithHasExtra = file + "#L2:" var commitCompare = util.URLJoin(repo, "compare", sha+"..."+sha) var commitCompareWithHash = commitCompare + "#L2" sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d" repo := TestRepoURL commit := util.URLJoin(repo, "commit", sha) tree := util.URLJoin(repo, "tree", sha, "src") file := util.URLJoin(repo, "commit", sha, "example.txt") fileWithExtra := file + ":" fileWithHash := file + "#L2" fileWithHasExtra := file + "#L2:" commitCompare := util.URLJoin(repo, "compare", sha+"..."+sha) commitCompareWithHash := commitCompare + "#L2" test(sha, `<p><a href="`+commit+`" rel="nofollow"><code>65f1bf27bc</code></a></p>`) test(sha[:7], `<p><a href="`+commit[:len(commit)-(40-7)]+`" rel="nofollow"><code>65f1bf2</code></a></p>`)
-
@@ -102,8 +102,8 @@ func TestRender_CrossReferences(t *testing.T) {func TestMisc_IsSameDomain(t *testing.T) { setting.AppURL = TestAppURL var sha = "b6dd6210eaebc915fd5be5579c58cce4da2e2579" var commit = util.URLJoin(TestRepoURL, "commit", sha) sha := "b6dd6210eaebc915fd5be5579c58cce4da2e2579" commit := util.URLJoin(TestRepoURL, "commit", sha) assert.True(t, IsSameDomain(commit)) assert.False(t, IsSameDomain("http://google.com/ncr"))
-
@@ -291,7 +291,7 @@ func TestRender_emoji(t *testing.T) {`<p><span class="emoji" aria-label="`+emoji.GemojiData[i].Description+`">`+emoji.GemojiData[i].Emoji+`</span></p>`) } //Text that should be turned into or recognized as emoji // Text that should be turned into or recognized as emoji test( ":gitea:", `<p><span class="emoji" aria-label="gitea"><img alt=":gitea:" src="`+setting.StaticURLPrefix+`/assets/img/emoji/gitea.png"/></span></p>`)
-
@@ -472,7 +472,7 @@ func TestRender_RelativeImages(t *testing.T) {func Test_ParseClusterFuzz(t *testing.T) { setting.AppURL = TestAppURL var localMetas = map[string]string{ localMetas := map[string]string{ "user": "go-gitea", "repo": "gitea", }
-
@@ -502,7 +502,7 @@ func Test_ParseClusterFuzz(t *testing.T) {func TestIssue16020(t *testing.T) { setting.AppURL = TestAppURL var localMetas = map[string]string{ localMetas := map[string]string{ "user": "go-gitea", "repo": "gitea", }
-
-
-
@@ -42,7 +42,7 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pametaData := meta.GetItems(pc) firstChild := node.FirstChild() createTOC := false var toc = []Header{} toc := []Header{} rc := &RenderConfig{ Meta: "table", Icon: "table",
-
-
-
@@ -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) errorreturn 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{})
-
-
-
@@ -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( "[]("+href+")", `<p><a href="`+href+`" rel="nofollow"><img src="`+result+`" alt="`+title+`"/></a></p>`) } func testAnswers(baseURLContent, baseURLImages string) []string {
-
-
-
@@ -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
-
-
-
@@ -52,7 +52,8 @@ A HIDDEN ` + "`" + `GHOST` + "`" + ` IN THIS LINE.}, []string{ "link", }}, }, }, { "Simply closes: #29 yes", []string{
-
-
-
@@ -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 {
-
-
-
@@ -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
-
-
-
@@ -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",
-
-
-
@@ -59,5 +59,4 @@ func TestSanitizeNonEscape(t *testing.T) {if strings.Contains(string(output), "<script>") { t.Errorf("un-escaped <script> in output: %q", output) } }
-
-
-
@@ -47,7 +47,6 @@ type Collector struct {// NewCollector returns a new Collector with all prometheus.Desc initialized func NewCollector() Collector { return Collector{ Accesses: prometheus.NewDesc( namespace+"accesses",
-
-
-
@@ -10,12 +10,9 @@ import () // NullDownloader implements a blank downloader type NullDownloader struct { } type NullDownloader struct{} var ( _ Downloader = &NullDownloader{} ) var _ Downloader = &NullDownloader{} // SetContext set context func (n NullDownloader) SetContext(_ context.Context) {}
-
-
-
@@ -9,9 +9,7 @@ import ("time" ) var ( _ Downloader = &RetryDownloader{} ) var _ Downloader = &RetryDownloader{} // RetryDownloader retry the downloads type RetryDownloader struct {
-
-
-
@@ -45,7 +45,6 @@ func ToRedisURI(connection string) *url.URL {if len(fields) == 1 { // It's a comma delimited string, then... fields = strings.Split(connection, ",") } for _, f := range fields { items := strings.SplitN(f, "=", 2)
-
-
-
@@ -25,9 +25,7 @@ type actionNotifier struct {base.NullNotifier } var ( _ base.Notifier = &actionNotifier{} ) var _ base.Notifier = &actionNotifier{} // NewNotifier create a new actionNotifier notifier func NewNotifier() base.Notifier {
-
@@ -220,7 +218,7 @@ func (a *actionNotifier) NotifyPullRequestReview(pr *models.PullRequest, reviewreturn } var actions = make([]*models.Action, 0, 10) actions := make([]*models.Action, 0, 10) for _, lines := range review.CodeComments { for _, comments := range lines { for _, comm := range comments {
-
-
-
@@ -14,14 +14,12 @@ import (// Notifier defines an interface to notify receiver type Notifier interface { Run() NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) NotifyNewIssue(issue *models.Issue, mentions []*user_model.User) NotifyIssueChangeStatus(*user_model.User, *models.Issue, *models.Comment, bool) NotifyIssueChangeMilestone(doer *user_model.User, issue *models.Issue, oldMilestoneID int64)
-
@@ -32,8 +30,7 @@ type Notifier interface {NotifyIssueChangeTitle(doer *user_model.User, issue *models.Issue, oldTitle string) NotifyIssueChangeRef(doer *user_model.User, issue *models.Issue, oldRef string) NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, addedLabels []*models.Label, removedLabels []*models.Label) addedLabels, removedLabels []*models.Label) NotifyNewPullRequest(pr *models.PullRequest, mentions []*user_model.User) NotifyMergePullRequest(*models.PullRequest, *user_model.User) NotifyPullRequestSynchronized(doer *user_model.User, pr *models.PullRequest)
-
@@ -42,23 +39,18 @@ type Notifier interface {NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *models.PullRequest, oldBranch string) NotifyPullRequestPushCommits(doer *user_model.User, pr *models.PullRequest, comment *models.Comment) NotifyPullRevieweDismiss(doer *user_model.User, review *models.Review, comment *models.Comment) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) NotifyUpdateComment(*user_model.User, *models.Comment, string) NotifyDeleteComment(*user_model.User, *models.Comment) NotifyNewRelease(rel *models.Release) NotifyUpdateRelease(doer *user_model.User, rel *models.Release) NotifyDeleteRelease(doer *user_model.User, rel *models.Release) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) }
-
-
-
@@ -12,12 +12,9 @@ import () // NullNotifier implements a blank notifier type NullNotifier struct { } type NullNotifier struct{} var ( _ Notifier = &NullNotifier{} ) var _ Notifier = &NullNotifier{} // Run places a place holder function func (*NullNotifier) Run() {
-
@@ -118,7 +115,7 @@ func (*NullNotifier) NotifyIssueChangeRef(doer *user_model.User, issue *models.I// NotifyIssueChangeLabels places a place holder function func (*NullNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, addedLabels []*models.Label, removedLabels []*models.Label) { addedLabels, removedLabels []*models.Label) { } // NotifyCreateRepository places a place holder function
-
-
-
@@ -22,9 +22,7 @@ type indexerNotifier struct {base.NullNotifier } var ( _ base.Notifier = &indexerNotifier{} ) var _ base.Notifier = &indexerNotifier{} // NewNotifier create a new indexerNotifier notifier func NewNotifier() base.Notifier {
-
-
-
@@ -21,9 +21,7 @@ type mailNotifier struct {base.NullNotifier } var ( _ base.Notifier = &mailNotifier{} ) var _ base.Notifier = &mailNotifier{} // NewNotifier create a new mailNotifier notifier func NewNotifier() base.Notifier {
-
-
-
@@ -18,9 +18,7 @@ import ("code.gitea.io/gitea/modules/setting" ) var ( notifiers []base.Notifier ) var notifiers []base.Notifier // RegisterNotifier providers method to receive notify messages func RegisterNotifier(notifier base.Notifier) {
-
@@ -203,7 +201,7 @@ func NotifyIssueChangeRef(doer *user_model.User, issue *models.Issue, oldRef str// NotifyIssueChangeLabels notifies change labels to notifiers func NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, addedLabels []*models.Label, removedLabels []*models.Label) { addedLabels, removedLabels []*models.Label) { for _, notifier := range notifiers { notifier.NotifyIssueChangeLabels(doer, issue, addedLabels, removedLabels) }
-
-
-
@@ -29,9 +29,7 @@ type (} ) var ( _ base.Notifier = ¬ificationService{} ) var _ base.Notifier = ¬ificationService{} // NewNotifier create a new notificationService notifier func NewNotifier() base.Notifier {
-
@@ -55,7 +53,7 @@ func (ns *notificationService) Run() {func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { var opts = issueNotificationOpts{ opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, }
-
@@ -64,7 +62,7 @@ func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, r} _ = ns.issueQueue.Push(opts) for _, mention := range mentions { var opts = issueNotificationOpts{ opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: mention.ID,
-
@@ -153,7 +151,7 @@ func (ns *notificationService) NotifyNewPullRequest(pr *models.PullRequest, ment} func (ns *notificationService) NotifyPullRequestReview(pr *models.PullRequest, r *models.Review, c *models.Comment, mentions []*user_model.User) { var opts = issueNotificationOpts{ opts := issueNotificationOpts{ IssueID: pr.Issue.ID, NotificationAuthorID: r.Reviewer.ID, }
-
@@ -162,7 +160,7 @@ func (ns *notificationService) NotifyPullRequestReview(pr *models.PullRequest, r} _ = ns.issueQueue.Push(opts) for _, mention := range mentions { var opts = issueNotificationOpts{ opts := issueNotificationOpts{ IssueID: pr.Issue.ID, NotificationAuthorID: r.Reviewer.ID, ReceiverID: mention.ID,
-
@@ -186,7 +184,7 @@ func (ns *notificationService) NotifyPullRequestCodeComment(pr *models.PullReque} func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.User, pr *models.PullRequest, comment *models.Comment) { var opts = issueNotificationOpts{ opts := issueNotificationOpts{ IssueID: pr.IssueID, NotificationAuthorID: doer.ID, CommentID: comment.ID,
-
@@ -195,7 +193,7 @@ func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.Use} func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, review *models.Review, comment *models.Comment) { var opts = issueNotificationOpts{ opts := issueNotificationOpts{ IssueID: review.IssueID, NotificationAuthorID: doer.ID, CommentID: comment.ID,
-
@@ -205,7 +203,7 @@ func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, rfunc (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User, issue *models.Issue, assignee *user_model.User, removed bool, comment *models.Comment) { if !removed { var opts = issueNotificationOpts{ opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: assignee.ID,
-
@@ -221,7 +219,7 @@ func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User,func (ns *notificationService) NotifyPullReviewRequest(doer *user_model.User, issue *models.Issue, reviewer *user_model.User, isRequest bool, comment *models.Comment) { if isRequest { var opts = issueNotificationOpts{ opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: reviewer.ID,
-
-
-
@@ -29,9 +29,7 @@ type webhookNotifier struct {base.NullNotifier } var ( _ base.Notifier = &webhookNotifier{} ) var _ base.Notifier = &webhookNotifier{} // NewNotifier create a new webhookNotifier notifier func NewNotifier() base.Notifier {
-
@@ -497,11 +495,10 @@ func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *moif err != nil { log.Error("PrepareWebhooks [comment_id: %d]: %v", comment.ID, err) } } func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, addedLabels []*models.Label, removedLabels []*models.Label) { addedLabels, removedLabels []*models.Label) { ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeLabels User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) defer finished()
-
-
-
@@ -17,9 +17,7 @@ import ("code.gitea.io/gitea/modules/util" ) var ( directories = make(directorySet) ) var directories = make(directorySet) // Dir returns all files from static or custom directory. func Dir(name string) ([]string, error) {
-
@@ -27,9 +25,7 @@ func Dir(name string) ([]string, error) {return directories.Get(name), nil } var ( result []string ) var result []string customDir := path.Join(setting.CustomPath, "options", name)
-
@@ -39,7 +35,6 @@ func Dir(name string) ([]string, error) {} if isDir { files, err := util.StatDir(customDir, true) if err != nil { return []string{}, fmt.Errorf("Failed to read custom directory. %v", err) }
-
@@ -55,7 +50,6 @@ func Dir(name string) ([]string, error) {} if isDir { files, err := util.StatDir(staticDir, true) if err != nil { return []string{}, fmt.Errorf("Failed to read static directory. %v", err) }
-
-
-
@@ -18,9 +18,7 @@ import ("code.gitea.io/gitea/modules/util" ) var ( directories = make(directorySet) ) var directories = make(directorySet) // Dir returns all files from bindata or custom directory. func Dir(name string) ([]string, error) {
-
@@ -28,9 +26,7 @@ func Dir(name string) ([]string, error) {return directories.Get(name), nil } var ( result []string ) var result []string customDir := path.Join(setting.CustomPath, "options", name) isDir, err := util.IsDir(customDir)
-
@@ -39,7 +35,6 @@ func Dir(name string) ([]string, error) {} if isDir { files, err := util.StatDir(customDir, true) if err != nil { return []string{}, fmt.Errorf("Failed to read custom directory. %v", err) }
-
@@ -48,7 +43,6 @@ func Dir(name string) ([]string, error) {} files, err := AssetDir(name) if err != nil { return []string{}, fmt.Errorf("Failed to read embedded directory. %v", err) }
-
@@ -69,7 +63,7 @@ func AssetDir(dirName string) ([]string, error) {if err != nil { return nil, err } var results = make([]string, 0, len(files)) results := make([]string, 0, len(files)) for _, file := range files { results = append(results, file.Name()) }
-
@@ -133,7 +127,7 @@ func Asset(name string) ([]byte, error) {func AssetNames() []string { realFS := Assets.(vfsgen۰FS) var results = make([]string, 0, len(realFS)) results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) }
-
-
-
@@ -50,7 +50,7 @@ func SendEmail(ctx context.Context, subject, message string, to []string) (int,return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error()) } var users = fmt.Sprintf("%d", len(to)) users := fmt.Sprintf("%d", len(to)) if len(to) == 0 { users = "all" }
-
-
-
@@ -170,7 +170,6 @@ func AddLogger(ctx context.Context, group, name, mode string, config map[string]} return http.StatusOK, "Added" } // RemoveLogger removes a logger
-
-
-
@@ -44,7 +44,7 @@ func RestoreRepo(ctx context.Context, repoDir, ownerName, repoName string, unitsdefer resp.Body.Close() if resp.StatusCode != 200 { var ret = struct { ret := struct { Err string `json:"err"` }{} body, err := io.ReadAll(resp.Body)
-
-
-
@@ -106,5 +106,4 @@ func ServCommand(ctx context.Context, keyID int64, ownerName, repoName string, mreturn nil, err } return &results, nil }
-
-
-
@@ -260,7 +260,6 @@ func (pm *Manager) ExecDirEnvStdIn(ctx context.Context, timeout time.Duration, d} err := cmd.Wait() if err != nil { err = &Error{ PID: GetPID(ctx),
-
-
-
@@ -90,7 +90,6 @@ func TestManager_Remove(t *testing.T) {} func TestExecTimeoutNever(t *testing.T) { // TODO Investigate how to improve the time elapsed per round. maxLoops := 10 for i := 1; i < maxLoops; i++ {
-
@@ -102,7 +101,6 @@ func TestExecTimeoutNever(t *testing.T) {} func TestExecTimeoutAlways(t *testing.T) { maxLoops := 100 for i := 1; i < maxLoops; i++ { _, stderr, err := GetManager().ExecTimeout(100*time.Microsecond, "ExecTimeout", "sleep", "5")
-
-
-
@@ -28,7 +28,7 @@ const AssetsURLPathPrefix = "/assets/"// AssetsHandlerFunc implements the static handler for serving custom or original assets. func AssetsHandlerFunc(opts *Options) http.HandlerFunc { var custPath = filepath.Join(setting.CustomPath, "public") custPath := filepath.Join(setting.CustomPath, "public") if !filepath.IsAbs(custPath) { custPath = filepath.Join(setting.AppWorkPath, custPath) }
-
@@ -85,7 +85,7 @@ func AssetsHandlerFunc(opts *Options) http.HandlerFunc {// parseAcceptEncoding parse Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5 as compress methods func parseAcceptEncoding(val string) map[string]bool { parts := strings.Split(val, ";") var types = make(map[string]bool) types := make(map[string]bool) for _, v := range strings.Split(parts[0], ",") { types[strings.TrimSpace(v)] = true }
-
-
-
@@ -11,7 +11,7 @@ import () func TestParseAcceptEncoding(t *testing.T) { var kases = []struct { kases := []struct { Header string Expected map[string]bool }{
-
-
-
@@ -41,7 +41,7 @@ func Asset(name string) ([]byte, error) {func AssetNames() []string { realFS := Assets.(vfsgen۰FS) var results = make([]string, 0, len(realFS)) results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) }
-
-
-
@@ -109,8 +109,8 @@ func GetManager() *Manager {func (m *Manager) Add(managed interface{}, t Type, configuration, exemplar interface{}) int64 { exemplar interface{}, ) int64 { cfg, _ := json.Marshal(configuration) mq := &ManagedQueue{ Type: t,
-
@@ -141,7 +141,6 @@ func (m *Manager) Remove(qid int64) {delete(m.Queues, qid) m.mutex.Unlock() log.Trace("Queue Manager removed: QID: %d", qid) } // GetManagedQueue by qid
-
@@ -225,7 +224,6 @@ func (m *Manager) FlushAll(baseCtx context.Context, timeout time.Duration) errorwg.Wait() } return nil } // ManagedQueues returns the managed queues
-
-
-
@@ -39,7 +39,7 @@ type Data interface{}type HandlerFunc func(...Data) // NewQueueFunc is a function that creates a queue type NewQueueFunc func(handler HandlerFunc, config interface{}, exemplar interface{}) (Queue, error) type NewQueueFunc func(handler HandlerFunc, config, exemplar interface{}) (Queue, error) // Shutdownable represents a queue that can be shutdown type Shutdownable interface {
-
@@ -70,8 +70,7 @@ func NewDummyQueue(handler HandlerFunc, opts, exemplar interface{}) (Queue, erro} // DummyQueue represents an empty queue type DummyQueue struct { } type DummyQueue struct{} // Run does nothing func (*DummyQueue) Run(_, _ func(func())) {}
-
-
-
@@ -195,9 +195,11 @@ loop:} } var errQueueEmpty = fmt.Errorf("empty queue") var errEmptyBytes = fmt.Errorf("empty bytes") var errUnmarshal = fmt.Errorf("failed to unmarshal") var ( errQueueEmpty = fmt.Errorf("empty queue") errEmptyBytes = fmt.Errorf("empty bytes") errUnmarshal = fmt.Errorf("failed to unmarshal") ) func (q *ByteFIFOQueue) doPop() error { q.lock.Lock()
-
-
-
@@ -173,7 +173,6 @@ func (q *PersistableChannelQueue) Run(atShutdown, atTerminate func(func())) {q.internal.(*LevelQueue).Shutdown() GetManager().Remove(q.internal.(*LevelQueue).qid) } } // Flush flushes the queue and blocks till the queue is empty
-
-
-
@@ -188,5 +188,4 @@ func TestPersistableChannelQueue(t *testing.T) {for _, callback := range callbacks { callback() } }
-
-
-
@@ -55,7 +55,7 @@ func (q *delayedStarter) setInternal(atShutdown func(func()), handle HandlerFuncfor q.internal == nil { select { case <-ctx.Done(): var cfg = q.cfg cfg := q.cfg if s, ok := cfg.([]byte); ok { cfg = string(s) }
-
-
-
@@ -197,7 +197,6 @@ func (q *PersistableChannelUniqueQueue) Run(atShutdown, atTerminate func(func())q.internal.(*LevelUniqueQueue).Shutdown() GetManager().Remove(q.internal.(*LevelUniqueQueue).qid) } } // Flush flushes the queue
-
-
-
@@ -341,7 +341,7 @@ func (p *WorkerPool) FlushWithContext(ctx context.Context) error {func (p *WorkerPool) doWork(ctx context.Context) { delay := time.Millisecond * 300 var data = make([]Data, 0, p.batchLength) data := make([]Data, 0, p.batchLength) for { select { case <-ctx.Done():
-
-
-
@@ -371,7 +371,6 @@ func FindRenderizableReferenceAlphanumeric(content string) (bool, *RenderizableR// FindAllIssueReferencesBytes returns a list of unvalidated references found in a byte slice. func findAllIssueReferencesBytes(content []byte, links []string) []*rawReference { ret := make([]*rawReference, 0, 10) pos := 0
-
-
-
@@ -51,7 +51,6 @@ owner/repo!123456789} func TestFindAllIssueReferences(t *testing.T) { fixtures := []testFixture{ { "Simply closes: #29 yes",
-
-
-
@@ -62,7 +62,7 @@ func generateExpansion(src string, templateRepo, generateRepo *repo_model.Reposi{Name: "TEMPLATE_SSH_URL", Value: templateRepo.CloneLink().SSH, Transformers: nil}, } var expansionMap = make(map[string]string) expansionMap := make(map[string]string) for _, e := range expansions { expansionMap[e.Name] = e.Value for _, tr := range e.Transformers {
-
@@ -159,7 +159,7 @@ func generateRepoCommit(ctx context.Context, repo, templateRepo, generateRepo *rif err := os.WriteFile(path, []byte(generateExpansion(string(content), templateRepo, generateRepo)), 0644); err != nil { 0o644); err != nil { return err } break
-
-
-
@@ -129,7 +129,7 @@ func createDelegateHooks(repoPath string) (err error) {if err = util.Remove(oldHookPath); err != nil && !os.IsNotExist(err) { return fmt.Errorf("unable to pre-remove old hook file '%s' prior to rewriting: %v ", oldHookPath, err) } if err = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil { if err = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0o777); err != nil { return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err) }
-
@@ -140,7 +140,7 @@ func createDelegateHooks(repoPath string) (err error) {if err = util.Remove(newHookPath); err != nil && !os.IsNotExist(err) { return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %v", newHookPath, err) } if err = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil { if err = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0o777); err != nil { return fmt.Errorf("write new hook file '%s': %v", newHookPath, err) }
-
@@ -157,7 +157,7 @@ func checkExecutable(filename string) bool {if err != nil { return false } return (fileInfo.Mode() & 0100) > 0 return (fileInfo.Mode() & 0o100) > 0 } func ensureExecutable(filename string) error {
-
@@ -165,10 +165,10 @@ func ensureExecutable(filename string) error {if err != nil { return err } if (fileInfo.Mode() & 0100) > 0 { if (fileInfo.Mode() & 0o100) > 0 { return nil } mode := fileInfo.Mode() | 0100 mode := fileInfo.Mode() | 0o100 return os.Chmod(filename, mode) }
-
-
-
@@ -62,7 +62,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir,"OwnerName": repo.OwnerName, } if err = os.WriteFile(filepath.Join(tmpDir, "README.md"), []byte(com.Expand(string(data), match)), 0644); err != nil { []byte(com.Expand(string(data), match)), 0o644); err != nil { return fmt.Errorf("write README.md: %v", err) }
-
@@ -81,7 +81,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir,} if buf.Len() > 0 { if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil { if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0o644); err != nil { return fmt.Errorf("write .gitignore: %v", err) } }
-
@@ -94,7 +94,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir,return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err) } if err = os.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil { if err = os.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0o644); err != nil { return fmt.Errorf("write LICENSE: %v", err) } }
-
-
-
@@ -310,7 +310,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagN} var author *user_model.User var createdAt = time.Unix(1, 0) createdAt := time.Unix(1, 0) if sig != nil { author, err = user_model.GetUserByEmail(sig.Email)
-
@@ -325,7 +325,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagNreturn fmt.Errorf("CommitsCount: %v", err) } var rel = models.Release{ rel := models.Release{ RepoID: repo.ID, TagName: tagName, LowerTagName: strings.ToLower(tagName),
-
-
-
@@ -135,7 +135,6 @@ func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err errs, err := auth.RegenerateSession(oldsid, sid) if err != nil { return nil, err } var kv map[interface{}]interface{}
-
-
-
@@ -4,24 +4,22 @@package setting var ( // Attachment settings Attachment = struct { Storage AllowedTypes string MaxSize int64 MaxFiles int Enabled bool }{ Storage: Storage{ ServeDirect: false, }, AllowedTypes: "image/jpeg,image/png,application/zip,application/gzip", MaxSize: 4, MaxFiles: 5, Enabled: true, } ) // Attachment settings var Attachment = struct { Storage AllowedTypes string MaxSize int64 MaxFiles int Enabled bool }{ Storage: Storage{ ServeDirect: false, }, AllowedTypes: "image/jpeg,image/png,application/zip,application/gzip", MaxSize: 4, MaxFiles: 5, Enabled: true, } func newAttachmentService() { sec := Cfg.Section("attachment")
-
-
-
@@ -20,34 +20,32 @@ type Cache struct {TTL time.Duration `ini:"ITEM_TTL"` } var ( // CacheService the global cache CacheService = struct { Cache `ini:"cache"` // CacheService the global cache var CacheService = struct { Cache `ini:"cache"` LastCommit struct { Enabled bool TTL time.Duration `ini:"ITEM_TTL"` CommitsCount int64 } `ini:"cache.last_commit"` LastCommit struct { Enabled bool TTL time.Duration `ini:"ITEM_TTL"` CommitsCount int64 } `ini:"cache.last_commit"` }{ Cache: Cache{ Enabled: true, Adapter: "memory", Interval: 60, TTL: 16 * time.Hour, }, LastCommit: struct { Enabled bool TTL time.Duration `ini:"ITEM_TTL"` CommitsCount int64 }{ Cache: Cache{ Enabled: true, Adapter: "memory", Interval: 60, TTL: 16 * time.Hour, }, LastCommit: struct { Enabled bool TTL time.Duration `ini:"ITEM_TTL"` CommitsCount int64 }{ Enabled: true, TTL: 8760 * time.Hour, CommitsCount: 1000, }, } ) Enabled: true, TTL: 8760 * time.Hour, CommitsCount: 1000, }, } // MemcacheMaxTTL represents the maximum memcache TTL const MemcacheMaxTTL = 30 * 24 * time.Hour
-
-
-
@@ -10,23 +10,21 @@ import ("code.gitea.io/gitea/modules/log" ) var ( // CORSConfig defines CORS settings CORSConfig = struct { Enabled bool Scheme string AllowDomain []string AllowSubdomain bool Methods []string MaxAge time.Duration AllowCredentials bool XFrameOptions string }{ Enabled: false, MaxAge: 10 * time.Minute, XFrameOptions: "SAMEORIGIN", } ) // CORSConfig defines CORS settings var CORSConfig = struct { Enabled bool Scheme string AllowDomain []string AllowSubdomain bool Methods []string MaxAge time.Duration AllowCredentials bool XFrameOptions string }{ Enabled: false, MaxAge: 10 * time.Minute, XFrameOptions: "SAMEORIGIN", } func newCORSService() { sec := Cfg.Section("cors")
-
-
-
@@ -12,7 +12,6 @@ import () func Test_GetCronSettings(t *testing.T) { type BaseStruct struct { Base bool Second string
-
@@ -43,5 +42,4 @@ Extend = trueassert.True(t, extended.Base) assert.EqualValues(t, extended.Second, "white rabbit") assert.True(t, extended.Extend) }
-
-
-
@@ -102,7 +102,7 @@ func InitDBConfig() {// DBConnStr returns database connection string func DBConnStr() (string, error) { connStr := "" var Param = "?" Param := "?" if strings.Contains(Database.Name, Param) { Param = "&" }
-
-
-
@@ -10,63 +10,61 @@ import ("code.gitea.io/gitea/modules/log" ) var ( // Git settings Git = struct { Path string DisableDiffHighlight bool MaxGitDiffLines int MaxGitDiffLineCharacters int MaxGitDiffFiles int CommitsRangeSize int // CommitsRangeSize the default commits range size BranchesRangeSize int // BranchesRangeSize the default branches range size VerbosePush bool VerbosePushDelay time.Duration GCArgs []string `ini:"GC_ARGS" delim:" "` EnableAutoGitWireProtocol bool PullRequestPushMessage bool LargeObjectThreshold int64 DisableCoreProtectNTFS bool DisablePartialClone bool Timeout struct { Default int Migrate int Mirror int Clone int Pull int GC int `ini:"GC"` } `ini:"git.timeout"` // Git settings var Git = struct { Path string DisableDiffHighlight bool MaxGitDiffLines int MaxGitDiffLineCharacters int MaxGitDiffFiles int CommitsRangeSize int // CommitsRangeSize the default commits range size BranchesRangeSize int // BranchesRangeSize the default branches range size VerbosePush bool VerbosePushDelay time.Duration GCArgs []string `ini:"GC_ARGS" delim:" "` EnableAutoGitWireProtocol bool PullRequestPushMessage bool LargeObjectThreshold int64 DisableCoreProtectNTFS bool DisablePartialClone bool Timeout struct { Default int Migrate int Mirror int Clone int Pull int GC int `ini:"GC"` } `ini:"git.timeout"` }{ DisableDiffHighlight: false, MaxGitDiffLines: 1000, MaxGitDiffLineCharacters: 5000, MaxGitDiffFiles: 100, CommitsRangeSize: 50, BranchesRangeSize: 20, VerbosePush: true, VerbosePushDelay: 5 * time.Second, GCArgs: []string{}, EnableAutoGitWireProtocol: true, PullRequestPushMessage: true, LargeObjectThreshold: 1024 * 1024, DisablePartialClone: false, Timeout: struct { Default int Migrate int Mirror int Clone int Pull int GC int `ini:"GC"` }{ DisableDiffHighlight: false, MaxGitDiffLines: 1000, MaxGitDiffLineCharacters: 5000, MaxGitDiffFiles: 100, CommitsRangeSize: 50, BranchesRangeSize: 20, VerbosePush: true, VerbosePushDelay: 5 * time.Second, GCArgs: []string{}, EnableAutoGitWireProtocol: true, PullRequestPushMessage: true, LargeObjectThreshold: 1024 * 1024, DisablePartialClone: false, Timeout: struct { Default int Migrate int Mirror int Clone int Pull int GC int `ini:"GC"` }{ Default: 360, Migrate: 600, Mirror: 300, Clone: 300, Pull: 300, GC: 60, }, } ) Default: 360, Migrate: 600, Mirror: 300, Clone: 300, Pull: 300, GC: 60, }, } func newGit() { if err := Cfg.Section("git").MapTo(&Git); err != nil {
-
-
-
@@ -14,39 +14,37 @@ import ("github.com/gobwas/glob" ) var ( // Indexer settings Indexer = struct { IssueType string IssuePath string IssueConnStr string IssueIndexerName string StartupTimeout time.Duration // Indexer settings var Indexer = struct { IssueType string IssuePath string IssueConnStr string IssueIndexerName string StartupTimeout time.Duration RepoIndexerEnabled bool RepoType string RepoPath string RepoConnStr string RepoIndexerName string MaxIndexerFileSize int64 IncludePatterns []glob.Glob ExcludePatterns []glob.Glob ExcludeVendored bool }{ IssueType: "bleve", IssuePath: "indexers/issues.bleve", IssueConnStr: "", IssueIndexerName: "gitea_issues", RepoIndexerEnabled bool RepoType string RepoPath string RepoConnStr string RepoIndexerName string MaxIndexerFileSize int64 IncludePatterns []glob.Glob ExcludePatterns []glob.Glob ExcludeVendored bool }{ IssueType: "bleve", IssuePath: "indexers/issues.bleve", IssueConnStr: "", IssueIndexerName: "gitea_issues", RepoIndexerEnabled: false, RepoType: "bleve", RepoPath: "indexers/repos.bleve", RepoConnStr: "", RepoIndexerName: "gitea_codes", MaxIndexerFileSize: 1024 * 1024, ExcludeVendored: true, } ) RepoIndexerEnabled: false, RepoType: "bleve", RepoPath: "indexers/repos.bleve", RepoConnStr: "", RepoIndexerName: "gitea_codes", MaxIndexerFileSize: 1024 * 1024, ExcludeVendored: true, } func newIndexerService() { sec := Cfg.Section("indexer")
-
-
-
@@ -16,7 +16,6 @@ type indexerMatchList struct {} func Test_newIndexerGlobSettings(t *testing.T) { checkGlobMatch(t, "", []indexerMatchList{}) checkGlobMatch(t, " ", []indexerMatchList{}) checkGlobMatch(t, "data, */data, */data/*, **/data/*, **/data/**", []indexerMatchList{
-
-
-
@@ -36,7 +36,7 @@ func newLFSService() {storageType := lfsSec.Key("STORAGE_TYPE").MustString("") // Specifically default PATH to LFS_CONTENT_PATH //FIXME: DEPRECATED to be removed in v1.18.0 // FIXME: DEPRECATED to be removed in v1.18.0 deprecatedSetting("server", "LFS_CONTENT_PATH", "lfs", "PATH") lfsSec.Key("PATH").MustString( sec.Key("LFS_CONTENT_PATH").String())
-
-
-
@@ -19,9 +19,11 @@ import (ini "gopkg.in/ini.v1" ) var filenameSuffix = "" var descriptionLock = sync.RWMutex{} var logDescriptions = make(map[string]*LogDescription) var ( filenameSuffix = "" descriptionLock = sync.RWMutex{} logDescriptions = make(map[string]*LogDescription) ) // GetLogDescriptions returns a race safe set of descriptions func GetLogDescriptions() map[string]*LogDescription {
-
@@ -86,7 +88,7 @@ func RemoveSubLogDescription(key, name string) bool {type defaultLogOptions struct { levelName string // LogLevel flags string filename string //path.Join(LogRootPath, "gitea.log") filename string // path.Join(LogRootPath, "gitea.log") bufferLength int64 disableConsole bool }
-
-
-
@@ -43,10 +43,8 @@ type Mailer struct {SendmailConvertCRLF bool } var ( // MailService the global mailer MailService *Mailer ) // MailService the global mailer var MailService *Mailer func newMailService() { sec := Cfg.Section("mailer")
-
-
-
@@ -123,7 +123,7 @@ func newMarkupRenderer(name string, sec *ini.Section) {extensionReg := regexp.MustCompile(`\.\w`) extensions := sec.Key("FILE_EXTENSIONS").Strings(",") var exts = make([]string, 0, len(extensions)) exts := make([]string, 0, len(extensions)) for _, extension := range extensions { if !extensionReg.MatchString(extension) { log.Warn(sec.Name() + " file extension " + extension + " is invalid. Extension ignored")
-
-
-
@@ -4,20 +4,18 @@package setting var ( // Migrations settings Migrations = struct { MaxAttempts int RetryBackoff int AllowedDomains string BlockedDomains string AllowLocalNetworks bool SkipTLSVerify bool }{ MaxAttempts: 3, RetryBackoff: 3, } ) // Migrations settings var Migrations = struct { MaxAttempts int RetryBackoff int AllowedDomains string BlockedDomains string AllowLocalNetworks bool SkipTLSVerify bool }{ MaxAttempts: 3, RetryBackoff: 3, } func newMigrationsService() { sec := Cfg.Section("migrations")
-
-
-
@@ -6,16 +6,14 @@ package settingimport "strings" var ( // MimeTypeMap defines custom mime type mapping settings MimeTypeMap = struct { Enabled bool Map map[string]string }{ Enabled: false, Map: map[string]string{}, } ) // MimeTypeMap defines custom mime type mapping settings var MimeTypeMap = struct { Enabled bool Map map[string]string }{ Enabled: false, Map: map[string]string{}, } func newMimeTypeMap() { sec := Cfg.Section("repository.mimetype_mapping")
-
-
-
@@ -10,22 +10,20 @@ import ("code.gitea.io/gitea/modules/log" ) var ( // Mirror settings Mirror = struct { Enabled bool DisableNewPull bool DisableNewPush bool DefaultInterval time.Duration MinInterval time.Duration }{ Enabled: true, DisableNewPull: false, DisableNewPush: false, MinInterval: 10 * time.Minute, DefaultInterval: 8 * time.Hour, } ) // Mirror settings var Mirror = struct { Enabled bool DisableNewPull bool DisableNewPush bool DefaultInterval time.Duration MinInterval time.Duration }{ Enabled: true, DisableNewPull: false, DisableNewPush: false, MinInterval: 10 * time.Minute, DefaultInterval: 8 * time.Hour, } func newMirror() { // Handle old configuration through `[repository]` `DISABLE_MIRRORS`
-
-
-
@@ -10,19 +10,17 @@ import ("code.gitea.io/gitea/modules/log" ) var ( // Proxy settings Proxy = struct { Enabled bool ProxyURL string ProxyURLFixed *url.URL ProxyHosts []string }{ Enabled: false, ProxyURL: "", ProxyHosts: []string{}, } ) // Proxy settings var Proxy = struct { Enabled bool ProxyURL string ProxyURLFixed *url.URL ProxyHosts []string }{ Enabled: false, ProxyURL: "", ProxyHosts: []string{}, } func newProxyService() { sec := Cfg.Section("proxy")
-
-
-
@@ -14,33 +14,31 @@ import ("code.gitea.io/gitea/modules/log" ) var ( // SessionConfig defines Session settings SessionConfig = struct { Provider string // Provider configuration, it's corresponding to provider. ProviderConfig string // Cookie name to save session ID. Default is "MacaronSession". CookieName string // Cookie path to store. Default is "/". CookiePath string // GC interval time in seconds. Default is 3600. Gclifetime int64 // Max life time in seconds. Default is whatever GC interval time is. Maxlifetime int64 // Use HTTPS only. Default is false. Secure bool // Cookie domain name. Default is empty. Domain string // SameSite declares if your cookie should be restricted to a first-party or same-site context. Valid strings are "none", "lax", "strict". Default is "lax" SameSite http.SameSite }{ CookieName: "i_like_gitea", Gclifetime: 86400, Maxlifetime: 86400, SameSite: http.SameSiteLaxMode, } ) // SessionConfig defines Session settings var SessionConfig = struct { Provider string // Provider configuration, it's corresponding to provider. ProviderConfig string // Cookie name to save session ID. Default is "MacaronSession". CookieName string // Cookie path to store. Default is "/". CookiePath string // GC interval time in seconds. Default is 3600. Gclifetime int64 // Max life time in seconds. Default is whatever GC interval time is. Maxlifetime int64 // Use HTTPS only. Default is false. Secure bool // Cookie domain name. Default is empty. Domain string // SameSite declares if your cookie should be restricted to a first-party or same-site context. Valid strings are "none", "lax", "strict". Default is "lax" SameSite http.SameSite }{ CookieName: "i_like_gitea", Gclifetime: 86400, Maxlifetime: 86400, SameSite: http.SameSiteLaxMode, } func newSessionService() { sec := Cfg.Section("session")
-
-
-
@@ -644,7 +644,7 @@ func loadFromConf(allowEmpty bool, extraConfig string) {} UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666") UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32) if err != nil || UnixSocketPermissionParsed > 0777 { if err != nil || UnixSocketPermissionParsed > 0o777 { log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw) }
-
@@ -800,16 +800,16 @@ func loadFromConf(allowEmpty bool, extraConfig string) {SSH.AuthorizedPrincipalsAllow, SSH.AuthorizedPrincipalsEnabled = parseAuthorizedPrincipalsAllow(sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").Strings(",")) if !SSH.Disabled && !SSH.StartBuiltinServer { if err := os.MkdirAll(SSH.RootPath, 0700); err != nil { if err := os.MkdirAll(SSH.RootPath, 0o700); err != nil { log.Fatal("Failed to create '%s': %v", SSH.RootPath, err) } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil { } else if err = os.MkdirAll(SSH.KeyTestPath, 0o644); err != nil { log.Fatal("Failed to create '%s': %v", SSH.KeyTestPath, err) } if len(trustedUserCaKeys) > 0 && SSH.AuthorizedPrincipalsEnabled { fname := sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem")) if err := os.WriteFile(fname, []byte(strings.Join(trustedUserCaKeys, "\n")), 0600); err != nil { []byte(strings.Join(trustedUserCaKeys, "\n")), 0o600); err != nil { log.Fatal("Failed to create '%s': %v", fname, err) } }
-
@@ -1080,7 +1080,7 @@ func loadInternalToken(sec *ini.Section) string {} switch tempURI.Scheme { case "file": fp, err := os.OpenFile(tempURI.RequestURI(), os.O_RDWR, 0600) fp, err := os.OpenFile(tempURI.RequestURI(), os.O_RDWR, 0o600) if err != nil { log.Fatal("Failed to open InternalTokenURI (%s): %v", uri, err) }
-
@@ -1173,7 +1173,6 @@ func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte {}, }, }) if err != nil { log.Error("unable to marshal manifest JSON. Error: %v", err) return make([]byte, 0)
-
-
-
@@ -10,27 +10,25 @@ import ("code.gitea.io/gitea/modules/log" ) var ( // Webhook settings Webhook = struct { QueueLength int DeliverTimeout int SkipTLSVerify bool AllowedHostList string Types []string PagingNum int ProxyURL string ProxyURLFixed *url.URL ProxyHosts []string }{ QueueLength: 1000, DeliverTimeout: 5, SkipTLSVerify: false, PagingNum: 10, ProxyURL: "", ProxyHosts: []string{}, } ) // Webhook settings var Webhook = struct { QueueLength int DeliverTimeout int SkipTLSVerify bool AllowedHostList string Types []string PagingNum int ProxyURL string ProxyURLFixed *url.URL ProxyHosts []string }{ QueueLength: 1000, DeliverTimeout: 5, SkipTLSVerify: false, PagingNum: 10, ProxyURL: "", ProxyHosts: []string{}, } func newWebhookService() { sec := Cfg.Section("webhook")
-
-
-
@@ -342,7 +342,6 @@ func Listen(host string, port int, ciphers, keyExchanges, macs []string) {srv.HostSigners = signers go listen(&srv) } // wrapSigner wraps a signer and overrides its public key type with the provided algorithm
-
@@ -387,7 +386,7 @@ func GenKeyPair(keyPath string) error {} privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)} f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err }
-
@@ -408,7 +407,7 @@ func GenKeyPair(keyPath string) error {} public := gossh.MarshalAuthorizedKey(pub) p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err }
-
-
-
@@ -27,7 +27,6 @@ func listen(server *ssh.Server) {} } log.Info("SSH Listener: %s Closed", server.Addr) } // Unused informs our cleanup routine that we will not be using a ssh port
-
-
-
@@ -15,9 +15,7 @@ import ("code.gitea.io/gitea/modules/util" ) var ( _ ObjectStorage = &LocalStorage{} ) var _ ObjectStorage = &LocalStorage{} // LocalStorageType is the type descriptor for local storage const LocalStorageType Type = "local"
-
-
-
@@ -122,7 +122,7 @@ func (m *MinioStorage) buildMinioPath(p string) string {// Open open a file func (m *MinioStorage) Open(path string) (Object, error) { var opts = minio.GetObjectOptions{} opts := minio.GetObjectOptions{} object, err := m.client.GetObject(m.ctx, m.bucket, m.buildMinioPath(path), opts) if err != nil { return nil, convertMinioErr(err)
-
@@ -206,7 +206,7 @@ func (m *MinioStorage) URL(path, name string) (*url.URL, error) {// IterateObjects iterates across the objects in the miniostorage func (m *MinioStorage) IterateObjects(fn func(path string, obj Object) error) error { var opts = minio.GetObjectOptions{} opts := minio.GetObjectOptions{} lobjectCtx, cancel := context.WithCancel(m.ctx) defer cancel() for mObjInfo := range m.client.ListObjects(lobjectCtx, m.bucket, minio.ListObjectsOptions{
-
-
-
@@ -16,10 +16,8 @@ import ("code.gitea.io/gitea/modules/setting" ) var ( // ErrURLNotSupported represents url is not supported ErrURLNotSupported = errors.New("url method not supported") ) // ErrURLNotSupported represents url is not supported var ErrURLNotSupported = errors.New("url method not supported") // ErrInvalidConfiguration is called when there is invalid configuration for a storage type ErrInvalidConfiguration struct {
-
-
-
@@ -13,10 +13,8 @@ import ("code.gitea.io/gitea/modules/json" ) var ( // ErrInvalidReceiveHook FIXME ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") ) // ErrInvalidReceiveHook FIXME var ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") // Hook a hook is a web hook when one repository changed type Hook struct {
-
-
-
@@ -326,19 +326,17 @@ func (gt GitServiceType) TokenAuth() bool {return false } var ( // SupportedFullGitService represents all git services supported to migrate issues/labels/prs and etc. // TODO: add to this list after new git service added SupportedFullGitService = []GitServiceType{ GithubService, GitlabService, GiteaService, GogsService, OneDevService, GitBucketService, CodebaseService, } ) // SupportedFullGitService represents all git services supported to migrate issues/labels/prs and etc. // TODO: add to this list after new git service added var SupportedFullGitService = []GitServiceType{ GithubService, GitlabService, GiteaService, GogsService, OneDevService, GitBucketService, CodebaseService, } // RepoTransfer represents a pending repo transfer type RepoTransfer struct {
-
-
-
@@ -29,7 +29,7 @@ func (vars Vars) Merge(another map[string]interface{}) Vars {// BaseVars returns all basic vars func BaseVars() Vars { var startTime = time.Now() startTime := time.Now() return map[string]interface{}{ "IsLandingPageHome": setting.LandingPageURL == setting.LandingPageHome, "IsLandingPageExplore": setting.LandingPageURL == setting.LandingPageExplore,
-
-
-
@@ -71,7 +71,6 @@ func Mailer() (*texttmpl.Template, *template.Template) {} content, err := os.ReadFile(path.Join(staticDir, filePath)) if err != nil { log.Warn("Failed to read static %s template. %v", filePath, err) continue
-
@@ -100,7 +99,6 @@ func Mailer() (*texttmpl.Template, *template.Template) {} content, err := os.ReadFile(path.Join(customDir, filePath)) if err != nil { log.Warn("Failed to read custom %s template. %v", filePath, err) continue
-
-
-
@@ -213,7 +213,7 @@ func NewFuncMap() []template.FuncMap {} return path }, "DiffStatsWidth": func(adds int, dels int) string { "DiffStatsWidth": func(adds, dels int) string { return fmt.Sprintf("%f", float64(adds)/(float64(adds)+float64(dels))*100) }, "Json": func(in interface{}) string {
-
@@ -286,7 +286,7 @@ func NewFuncMap() []template.FuncMap {return util.MergeInto(dict, values...) }, "percentage": func(n int, values ...int) float32 { var sum = 0 sum := 0 for i := 0; i < len(values); i++ { sum += values[i] }
-
@@ -302,7 +302,7 @@ func NewFuncMap() []template.FuncMap {"EventSourceUpdateTime": int(setting.UI.Notification.EventSourceUpdateTime / time.Millisecond), } }, "containGeneric": func(arr interface{}, v interface{}) bool { "containGeneric": func(arr, v interface{}) bool { arrV := reflect.ValueOf(arr) if arrV.Kind() == reflect.String && reflect.ValueOf(v).Kind() == reflect.String { return strings.Contains(arr.(string), v.(string))
-
@@ -478,7 +478,7 @@ func NewTextFuncMap() []texttmpl.FuncMap {return dict, nil }, "percentage": func(n int, values ...int) float32 { var sum = 0 sum := 0 for i := 0; i < len(values); i++ { sum += values[i] }
-
@@ -502,8 +502,10 @@ func NewTextFuncMap() []texttmpl.FuncMap {}} } var widthRe = regexp.MustCompile(`width="[0-9]+?"`) var heightRe = regexp.MustCompile(`height="[0-9]+?"`) var ( widthRe = regexp.MustCompile(`width="[0-9]+?"`) heightRe = regexp.MustCompile(`height="[0-9]+?"`) ) func parseOthers(defaultSize int, defaultClass string, others ...interface{}) (int, string) { size := defaultSize
-
@@ -741,7 +743,7 @@ func RenderEmoji(text string) template.HTML {return template.HTML(renderedText) } //ReactionToEmoji renders emoji for use in reactions // ReactionToEmoji renders emoji for use in reactions func ReactionToEmoji(reaction string) template.HTML { val := emoji.FromCode(reaction) if val != nil {
-
-
-
@@ -47,7 +47,7 @@ func GetAsset(name string) ([]byte, error) {// GetAssetNames only for chi func GetAssetNames() []string { realFS := Assets.(vfsgen۰FS) var tmpls = make([]string, 0, len(realFS)) tmpls := make([]string, 0, len(realFS)) for k := range realFS { tmpls = append(tmpls, "templates/"+k[1:]) }
-
@@ -76,7 +76,6 @@ func Mailer() (*texttmpl.Template, *template.Template) {} content, err := Asset(assetPath) if err != nil { log.Warn("Failed to read embedded %s template. %v", assetPath, err) continue
-
@@ -111,7 +110,6 @@ func Mailer() (*texttmpl.Template, *template.Template) {} content, err := os.ReadFile(path.Join(customDir, filePath)) if err != nil { log.Warn("Failed to read custom %s template. %v", filePath, err) continue
-
@@ -142,7 +140,7 @@ func Asset(name string) ([]byte, error) {func AssetNames() []string { realFS := Assets.(vfsgen۰FS) var results = make([]string, 0, len(realFS)) results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) }
-
-
-
@@ -29,8 +29,8 @@ import (// MockContext mock context for unit tests func MockContext(t *testing.T, path string) *context.Context { var resp = &mockResponseWriter{} var ctx = context.Context{ resp := &mockResponseWriter{} ctx := context.Context{ Render: &mockRender{}, Data: make(map[string]interface{}), Flash: &middleware.Flash{
-
@@ -42,7 +42,7 @@ func MockContext(t *testing.T, path string) *context.Context {requestURL, err := url.Parse(path) assert.NoError(t, err) var req = &http.Request{ req := &http.Request{ URL: requestURL, Form: url.Values{}, }
-
@@ -133,8 +133,7 @@ func (rw *mockResponseWriter) Push(target string, opts *http.PushOptions) errorreturn nil } type mockRender struct { } type mockRender struct{} func (tr *mockRender) TemplateLookup(tmpl string) *template.Template { return nil
-
-
-
@@ -13,8 +13,10 @@ import ("code.gitea.io/gitea/modules/log" ) var executablModTime = time.Now() var executablModTimeOnce sync.Once var ( executablModTime = time.Now() executablModTimeOnce sync.Once ) // GetExecutableModTime get executable file modified time of current process. func GetExecutableModTime() time.Time {
-
-
-
@@ -10,13 +10,11 @@ import ("code.gitea.io/gitea/modules/setting" ) var ( langTimeFormats = map[string]string{ "zh-CN": "2006年01月02日 15时04分05秒", "en-US": time.RFC1123, "lv-LV": "02.01.2006. 15:04:05", } ) var langTimeFormats = map[string]string{ "zh-CN": "2006年01月02日 15时04分05秒", "en-US": time.RFC1123, "lv-LV": "02.01.2006. 15:04:05", } // GetLangTimeFormat represents the default time format for the language func GetLangTimeFormat(lang string) string {
-
-
-
@@ -20,8 +20,10 @@ const sniffLen = 1024// SvgMimeType MIME type of SVG images. const SvgMimeType = "image/svg+xml" var svgTagRegex = regexp.MustCompile(`(?si)\A\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`) var svgTagInXMLRegex = regexp.MustCompile(`(?si)\A<\?xml\b.*?\?>\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`) var ( svgTagRegex = regexp.MustCompile(`(?si)\A\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`) svgTagInXMLRegex = regexp.MustCompile(`(?si)\A<\?xml\b.*?\?>\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`) ) // SniffedType contains information about a blobs type. type SniffedType struct {
-
-
-
@@ -60,7 +60,6 @@ func GiteaUpdateChecker(httpEndpoint string) error {} return UpdateRemoteVersion(respData.Latest.Version) } // UpdateRemoteVersion updates the latest available version of Gitea
-
-
-
@@ -36,7 +36,7 @@ func TestPaginateSlice(t *testing.T) {Val int } var testVar = []*Test{{Val: 2}, {Val: 3}, {Val: 4}} testVar := []*Test{{Val: 2}, {Val: 3}, {Val: 4}} testVar, ok = PaginateSlice(testVar, 1, 50).([]*Test) assert.True(t, ok) assert.EqualValues(t, []*Test{{Val: 2}, {Val: 3}, {Val: 4}}, testVar)
-
-
-
@@ -13,7 +13,7 @@ import () func TestFileURLToPath(t *testing.T) { var cases = []struct { cases := []struct { url string expected string haserror bool
-
-
-
@@ -9,8 +9,10 @@ import ("strings" ) const userPlaceholder = "sanitized-credential" const unparsableURL = "(unparsable url)" const ( userPlaceholder = "sanitized-credential" unparsableURL = "(unparsable url)" ) type sanitizedError struct { err error
-
-
-
@@ -16,7 +16,7 @@ func TestNewSanitizedError(t *testing.T) {err2 := NewSanitizedError(err) assert.Equal(t, err.Error(), err2.Error()) var cases = []struct { cases := []struct { input error oldnew []string expected string
-
@@ -43,7 +43,7 @@ func TestNewSanitizedError(t *testing.T) {} func TestNewStringURLSanitizer(t *testing.T) { var cases = []struct { cases := []struct { input string placeholder bool expected string
-
@@ -101,7 +101,7 @@ func TestNewStringURLSanitizer(t *testing.T) {} func TestNewStringURLSanitizedError(t *testing.T) { var cases = []struct { cases := []struct { input string placeholder bool expected string
-
-
-
@@ -41,9 +41,11 @@ const (needsSingleQuote = "!\n" ) var doubleQuoteEscaper = strings.NewReplacer(`$`, `\$`, "`", "\\`", `"`, `\"`, `\`, `\\`) var singleQuoteEscaper = strings.NewReplacer(`'`, `'\''`) var singleQuoteCoalescer = strings.NewReplacer(`''\'`, `\'`, `\'''`, `\'`) var ( doubleQuoteEscaper = strings.NewReplacer(`$`, `\$`, "`", "\\`", `"`, `\"`, `\`, `\\`) singleQuoteEscaper = strings.NewReplacer(`'`, `'\''`) singleQuoteCoalescer = strings.NewReplacer(`''\'`, `\'`, `\'''`, `\'`) ) // ShellEscape will escape the provided string. // We can't just use go-shellquote here because our preferences for escaping differ from those in that we want:
-
-
-
@@ -7,8 +7,10 @@ package utilimport "unicode/utf8" // in UTF8 "…" is 3 bytes so doesn't really gain us anything... const utf8Ellipsis = "…" const asciiEllipsis = "..." const ( utf8Ellipsis = "…" asciiEllipsis = "..." ) // SplitStringAtByteN splits a string at byte n accounting for rune boundaries. (Combining characters are not accounted for.) func SplitStringAtByteN(input string, n int) (left, right string) {
-
-
-
@@ -46,7 +46,6 @@ func TestURLJoin(t *testing.T) {} func TestIsEmptyString(t *testing.T) { cases := []struct { s string expected bool
-
-
-
@@ -24,16 +24,13 @@ const (ErrRegexPattern = "RegexPattern" ) var ( // GitRefNamePatternInvalid is regular expression with unallowed characters in git reference name // They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon : anywhere. // They cannot have question-mark ?, asterisk *, or open bracket [ anywhere GitRefNamePatternInvalid = regexp.MustCompile(`[\000-\037\177 \\~^:?*[]+`) ) // GitRefNamePatternInvalid is regular expression with unallowed characters in git reference name // They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon : anywhere. // They cannot have question-mark ?, asterisk *, or open bracket [ anywhere var GitRefNamePatternInvalid = regexp.MustCompile(`[\000-\037\177 \\~^:?*[]+`) // CheckGitRefAdditionalRulesValid check name is valid on additional rules func CheckGitRefAdditionalRulesValid(name string) bool { // Additional rules as described at https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html if strings.HasPrefix(name, "/") || strings.HasSuffix(name, "/") || strings.HasSuffix(name, ".") || strings.Contains(name, "..") ||
-
-
-
@@ -14,10 +14,8 @@ const (InfoFlash = "InfoMsg" ) var ( // FlashNow FIXME: FlashNow bool ) // FlashNow FIXME: var FlashNow bool // Flash represents a one time data transfer between two requests. type Flash struct {
-
-
-
@@ -18,7 +18,7 @@ import (func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { // 1. Check URL arguments. lang := req.URL.Query().Get("lang") var changeLang = lang != "" changeLang := lang != "" // 2. Get language information from cookies. if len(lang) == 0 {
-
-
-
@@ -20,7 +20,7 @@ import (// Bind binding an obj to a handler func Bind(obj interface{}) http.HandlerFunc { var tp = reflect.TypeOf(obj) tp := reflect.TypeOf(obj) if tp.Kind() == reflect.Ptr { tp = tp.Elem() }
-
@@ -28,7 +28,7 @@ func Bind(obj interface{}) http.HandlerFunc {panic("Only structs are allowed to bind") } return Wrap(func(ctx *context.Context) { var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly binding.Bind(ctx.Req, theObj) SetForm(ctx, theObj) middleware.AssignForm(theObj, ctx.Data)
-
@@ -86,8 +86,8 @@ func (r *Route) Use(middlewares ...interface{}) {// Group mounts a sub-Router along a `pattern` string. func (r *Route) Group(pattern string, fn func(), middlewares ...interface{}) { var previousGroupPrefix = r.curGroupPrefix var previousMiddlewares = r.curMiddlewares previousGroupPrefix := r.curGroupPrefix previousMiddlewares := r.curMiddlewares r.curGroupPrefix += pattern r.curMiddlewares = append(r.curMiddlewares, middlewares...)
-
@@ -110,7 +110,7 @@ func (r *Route) getPattern(pattern string) string {// Mount attaches another Route along ./pattern/* func (r *Route) Mount(pattern string, subR *Route) { var middlewares = make([]interface{}, len(r.curMiddlewares)) middlewares := make([]interface{}, len(r.curMiddlewares)) copy(middlewares, r.curMiddlewares) subR.Use(middlewares...) r.R.Mount(r.getPattern(pattern), subR.R)
-
@@ -118,7 +118,7 @@ func (r *Route) Mount(pattern string, subR *Route) {// Any delegate requests for all methods func (r *Route) Any(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.HandleFunc(r.getPattern(pattern), Wrap(middlewares...)) }
-
@@ -126,7 +126,7 @@ func (r *Route) Any(pattern string, h ...interface{}) {func (r *Route) Route(pattern, methods string, h ...interface{}) { p := r.getPattern(pattern) ms := strings.Split(methods, ",") var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) for _, method := range ms { r.R.MethodFunc(strings.TrimSpace(method), p, Wrap(middlewares...)) }
-
@@ -134,12 +134,12 @@ func (r *Route) Route(pattern, methods string, h ...interface{}) {// Delete delegate delete method func (r *Route) Delete(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Delete(r.getPattern(pattern), Wrap(middlewares...)) } func (r *Route) getMiddlewares(h []interface{}) []interface{} { var middlewares = make([]interface{}, len(r.curMiddlewares), len(r.curMiddlewares)+len(h)) middlewares := make([]interface{}, len(r.curMiddlewares), len(r.curMiddlewares)+len(h)) copy(middlewares, r.curMiddlewares) middlewares = append(middlewares, h...) return middlewares
-
@@ -147,51 +147,51 @@ func (r *Route) getMiddlewares(h []interface{}) []interface{} {// Get delegate get method func (r *Route) Get(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Get(r.getPattern(pattern), Wrap(middlewares...)) } // Options delegate options method func (r *Route) Options(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Options(r.getPattern(pattern), Wrap(middlewares...)) } // GetOptions delegate get and options method func (r *Route) GetOptions(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Get(r.getPattern(pattern), Wrap(middlewares...)) r.R.Options(r.getPattern(pattern), Wrap(middlewares...)) } // PostOptions delegate post and options method func (r *Route) PostOptions(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Post(r.getPattern(pattern), Wrap(middlewares...)) r.R.Options(r.getPattern(pattern), Wrap(middlewares...)) } // Head delegate head method func (r *Route) Head(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Head(r.getPattern(pattern), Wrap(middlewares...)) } // Post delegate post method func (r *Route) Post(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Post(r.getPattern(pattern), Wrap(middlewares...)) } // Put delegate put method func (r *Route) Put(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Put(r.getPattern(pattern), Wrap(middlewares...)) } // Patch delegate patch method func (r *Route) Patch(pattern string, h ...interface{}) { var middlewares = r.getMiddlewares(h) middlewares := r.getMiddlewares(h) r.R.Patch(r.getPattern(pattern), Wrap(middlewares...)) }
-
-
-
@@ -13,7 +13,7 @@ type contextKeyType struct{}var contextKey contextKeyType //UpdateFuncInfo updates a context's func info // UpdateFuncInfo updates a context's func info func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) { record, ok := ctx.Value(contextKey).(*requestRecord) if !ok {
-
@@ -23,7 +23,6 @@ func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) {record.lock.Lock() record.funcInfo = funcInfo record.lock.Unlock() } // MarkLongPolling marks the reuqest is a long-polling request, and the logger may output different message for it
-
@@ -38,7 +37,7 @@ func MarkLongPolling(resp http.ResponseWriter, req *http.Request) {record.lock.Unlock() } //UpdatePanicError updates a context's error info, a panic may be recovered by other middlewares, but we still need to know that. // UpdatePanicError updates a context's error info, a panic may be recovered by other middlewares, but we still need to know that. func UpdatePanicError(ctx context.Context, err interface{}) { record, ok := ctx.Value(contextKey).(*requestRecord) if !ok {
-
-
-
@@ -12,9 +12,11 @@ import ("sync" ) var funcInfoMap = map[uintptr]*FuncInfo{} var funcInfoNameMap = map[string]*FuncInfo{} var funcInfoMapMu sync.RWMutex var ( funcInfoMap = map[uintptr]*FuncInfo{} funcInfoNameMap = map[string]*FuncInfo{} funcInfoMapMu sync.RWMutex ) // FuncInfo contains information about the function to be logged by the router log type FuncInfo struct {
-
-
-
@@ -17,13 +17,13 @@ import (type Event int const ( //StartEvent at the beginning of a request // StartEvent at the beginning of a request StartEvent Event = iota //StillExecutingEvent the request is still executing // StillExecutingEvent the request is still executing StillExecutingEvent //EndEvent the request has ended (either completed or failed) // EndEvent the request has ended (either completed or failed) EndEvent )
-
-
-
@@ -87,7 +87,7 @@ func convertHandler(handler interface{}) wrappedHandlerFunc {} case func(http.Handler) http.Handler: return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { var next = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) if len(others) > 0 { next = wrapInternal(others) }
-
-
-
@@ -82,7 +82,7 @@ func CreateOrg(ctx *context.APIContext) {ctx.JSON(http.StatusCreated, convert.ToOrganization(org)) } //GetAllOrgs API for getting information of all the organizations // GetAllOrgs API for getting information of all the organizations func GetAllOrgs(ctx *context.APIContext) { // swagger:operation GET /admin/orgs admin adminGetAllOrgs // ---
-
-
-
@@ -403,7 +403,7 @@ func DeleteUserPublicKey(ctx *context.APIContext) {ctx.Status(http.StatusNoContent) } //GetAllUsers API for getting information of all the users // GetAllUsers API for getting information of all the users func GetAllUsers(ctx *context.APIContext) { // swagger:operation GET /admin/users admin adminGetAllUsers // ---
-
-
-
@@ -333,7 +333,7 @@ func reqTeamMembership() func(ctx *context.APIContext) {return } var orgID = ctx.Org.Team.OrgID orgID := ctx.Org.Team.OrgID isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err)
-
@@ -545,12 +545,12 @@ func mustNotBeArchived(ctx *context.APIContext) {// bind binding an obj to a func(ctx *context.APIContext) func bind(obj interface{}) http.HandlerFunc { var tp = reflect.TypeOf(obj) tp := reflect.TypeOf(obj) for tp.Kind() == reflect.Ptr { tp = tp.Elem() } return web.Wrap(func(ctx *context.APIContext) { var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly errs := binding.Bind(ctx.Req, theObj) if len(errs) > 0 { ctx.Error(http.StatusUnprocessableEntity, "validationError", fmt.Sprintf("%s: %s", errs[0].FieldNames, errs[0].Error()))
-
@@ -562,16 +562,16 @@ func bind(obj interface{}) http.HandlerFunc {// Routes registers all v1 APIs routes to web application. func Routes(sessioner func(http.Handler) http.Handler) *web.Route { var m = web.NewRoute() m := web.NewRoute() m.Use(sessioner) m.Use(securityHeaders()) if setting.CORSConfig.Enabled { m.Use(cors.Handler(cors.Options{ //Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option AllowedOrigins: setting.CORSConfig.AllowDomain, //setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option AllowedMethods: setting.CORSConfig.Methods, AllowCredentials: setting.CORSConfig.AllowCredentials, AllowedHeaders: []string{"Authorization", "X-CSRFToken", "X-Gitea-OTP"},
-
-
-
@@ -22,12 +22,14 @@ import ("github.com/stretchr/testify/assert" ) const AppURL = "http://localhost:3000/" const Repo = "gogits/gogs" const AppSubURL = AppURL + Repo + "/" const ( AppURL = "http://localhost:3000/" Repo = "gogits/gogs" AppSubURL = AppURL + Repo + "/" ) func createContext(req *http.Request) (*context.Context, *httptest.ResponseRecorder) { var rnd = templates.HTMLRenderer() rnd := templates.HTMLRenderer() resp := httptest.NewRecorder() c := &context.Context{ Req: req,
-
-
-
@@ -123,7 +123,7 @@ func CreateHook(ctx *context.APIContext) {// "$ref": "#/responses/Hook" form := web.GetForm(ctx).(*api.CreateHookOption) //TODO in body params // TODO in body params if !utils.CheckCreateHookOption(ctx, form) { return }
-
@@ -161,7 +161,7 @@ func EditHook(ctx *context.APIContext) {form := web.GetForm(ctx).(*api.EditHookOption) //TODO in body params // TODO in body params hookID := ctx.ParamsInt64(":id") utils.EditOrgHook(ctx, form, hookID) }
-
-
-
@@ -25,7 +25,7 @@ func listUserOrgs(ctx *context.APIContext, u *user_model.User) {listOptions := utils.GetListOptions(ctx) showPrivate := ctx.IsSigned && (ctx.User.IsAdmin || ctx.User.ID == u.ID) var opts = models.FindOrgOptions{ opts := models.FindOrgOptions{ ListOptions: listOptions, UserID: u.ID, IncludePrivate: showPrivate,
-
@@ -357,7 +357,7 @@ func Edit(ctx *context.APIContext) {ctx.JSON(http.StatusOK, convert.ToOrganization(org)) } //Delete an organization // Delete an organization func Delete(ctx *context.APIContext) { // swagger:operation DELETE /orgs/{org} organization orgDelete // ---
-
-
-
@@ -177,23 +177,18 @@ func CreateBranch(ctx *context.APIContext) {} err := repo_service.CreateNewBranch(ctx, ctx.User, ctx.Repo.Repository, opt.OldBranchName, opt.BranchName) if err != nil { if models.IsErrBranchDoesNotExist(err) { ctx.Error(http.StatusNotFound, "", "The old branch does not exist") } if models.IsErrTagAlreadyExists(err) { ctx.Error(http.StatusConflict, "", "The branch with the same tag already exists.") } else if models.IsErrBranchAlreadyExists(err) || git.IsErrPushOutOfDate(err) { ctx.Error(http.StatusConflict, "", "The branch already exists.") } else if models.IsErrBranchNameConflict(err) { ctx.Error(http.StatusConflict, "", "The branch with the same name already exists.") } else { ctx.Error(http.StatusInternalServerError, "CreateRepoBranch", err) } return }
-
@@ -532,7 +527,6 @@ func CreateBranchProtection(ctx *context.APIContext) {} ctx.JSON(http.StatusCreated, convert.ToBranchProtection(bp)) } // EditBranchProtection edits a branch protection for a repo
-
-
-
@@ -149,6 +149,6 @@ func CreateFork(ctx *context.APIContext) {return } //TODO change back to 201 // TODO change back to 201 ctx.JSON(http.StatusAccepted, convert.ToRepo(fork, perm.AccessModeOwner)) }
-
-
-
@@ -599,7 +599,7 @@ func CreateIssue(ctx *context.APIContext) {DeadlineUnix: deadlineUnix, } var assigneeIDs = make([]int64, 0) assigneeIDs := make([]int64, 0) var err error if ctx.Repo.CanWrite(unit.TypeIssues) { issue.MilestoneID = form.Milestone
-
-
-
@@ -225,7 +225,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOpctx.Error(http.StatusInternalServerError, "DeleteCommentReaction", err) return } //ToDo respond 204 // ToDo respond 204 ctx.Status(http.StatusOK) } }
-
@@ -435,7 +435,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, ictx.Error(http.StatusInternalServerError, "DeleteIssueReaction", err) return } //ToDo respond 204 // ToDo respond 204 ctx.Status(http.StatusOK) } }
-
-
-
@@ -127,7 +127,7 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) {return } //only admin and user for itself can change subscription // only admin and user for itself can change subscription if user.ID != ctx.User.ID && !ctx.User.IsAdmin { ctx.Error(http.StatusForbidden, "User", fmt.Errorf("%s is not permitted to change subscriptions for %s", ctx.User.Name, user.Name)) return
-
@@ -269,7 +269,7 @@ func GetIssueSubscribers(ctx *context.APIContext) {return } var userIDs = make([]int64, 0, len(iwl)) userIDs := make([]int64, 0, len(iwl)) for _, iw := range iwl { userIDs = append(userIDs, iw.UserID) }
-
-
-
@@ -201,7 +201,7 @@ func AddTime(ctx *context.APIContext) {user := ctx.User if form.User != "" { if (ctx.IsUserRepoAdmin() && ctx.User.Name != form.User) || ctx.User.IsAdmin { //allow only RepoAdmin, Admin and User to add time // allow only RepoAdmin, Admin and User to add time user, err = user_model.GetUserByName(form.User) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
-
@@ -365,7 +365,7 @@ func DeleteTime(ctx *context.APIContext) {} if !ctx.User.IsAdmin && time.UserID != ctx.User.ID { //Only Admin and User itself can delete their time // Only Admin and User itself can delete their time ctx.Status(http.StatusForbidden) return }
-
-
-
@@ -56,7 +56,7 @@ func Migrate(ctx *context.APIContext) {form := web.GetForm(ctx).(*api.MigrateRepoOptions) //get repoOwner // get repoOwner var ( repoOwner *user_model.User err error
-
@@ -137,7 +137,7 @@ func Migrate(ctx *context.APIContext) {} } var opts = migrations.MigrateOptions{ opts := migrations.MigrateOptions{ CloneAddr: remoteAddr, RepoName: form.RepoName, Description: form.Description,
-
-
-
@@ -213,7 +213,7 @@ func EditMilestone(ctx *context.APIContext) {milestone.DeadlineUnix = timeutil.TimeStamp(form.Deadline.Unix()) } var oldIsClosed = milestone.IsClosed oldIsClosed := milestone.IsClosed if form.State != nil { milestone.IsClosed = *form.State == string(api.StateClosed) }
-
-
-
@@ -95,7 +95,6 @@ func ListPullRequests(ctx *context.APIContext) {Labels: ctx.FormStrings("labels"), MilestoneID: ctx.FormInt64("milestone"), }) if err != nil { ctx.Error(http.StatusInternalServerError, "PullRequests", err) return
-
-
-
@@ -178,7 +178,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {} defer file.Close() var filename = header.Filename filename := header.Filename if query := ctx.FormString("name"); query != "" { filename = query }
-
-
-
@@ -160,7 +160,7 @@ func Search(ctx *context.APIContext) {opts.Collaborate = util.OptionalBoolFalse } var mode = ctx.FormString("mode") mode := ctx.FormString("mode") switch mode { case "source": opts.Fork = util.OptionalBoolFalse
-
@@ -186,9 +186,9 @@ func Search(ctx *context.APIContext) {opts.IsPrivate = util.OptionalBoolOf(ctx.FormBool("is_private")) } var sortMode = ctx.FormString("sort") sortMode := ctx.FormString("sort") if len(sortMode) > 0 { var sortOrder = ctx.FormString("order") sortOrder := ctx.FormString("order") if len(sortOrder) == 0 { sortOrder = "asc" }
-
-
-
@@ -55,7 +55,7 @@ func TestRepoEdit(t *testing.T) {Archived: &archived, } var apiCtx = &context.APIContext{Context: ctx, Org: nil} apiCtx := &context.APIContext{Context: ctx, Org: nil} web.SetForm(apiCtx, &opts) Edit(apiCtx)
-
@@ -77,7 +77,7 @@ func TestRepoEditNameChange(t *testing.T) {Name: &name, } var apiCtx = &context.APIContext{Context: ctx, Org: nil} apiCtx := &context.APIContext{Context: ctx, Org: nil} web.SetForm(apiCtx, &opts) Edit(apiCtx) assert.EqualValues(t, http.StatusOK, ctx.Resp.Status())
-
-
-
@@ -176,7 +176,7 @@ func GetCommitStatusesByRef(ctx *context.APIContext) {return } getCommitStatuses(ctx, filter) //By default filter is maybe the raw SHA getCommitStatuses(ctx, filter) // By default filter is maybe the raw SHA } func getCommitStatuses(ctx *context.APIContext, sha string) {
-
-
-
@@ -167,7 +167,7 @@ func getWikiPage(ctx *context.APIContext, title string) *api.WikiPage {return nil } //lookup filename in wiki - get filecontent, real filename // lookup filename in wiki - get filecontent, real filename content, pageFilename := wikiContentsByName(ctx, commit, title, false) if ctx.Written() { return nil
-
@@ -412,7 +412,7 @@ func ListPageRevisions(ctx *context.APIContext) {pageName = "Home" } //lookup filename in wiki - get filecontent, gitTree entry , real filename // lookup filename in wiki - get filecontent, gitTree entry , real filename _, pageFilename := wikiContentsByName(ctx, commit, pageName, false) if ctx.Written() { return
-
@@ -501,7 +501,6 @@ func wikiContentsByEntry(ctx *context.APIContext, entry *git.TreeEntry) string {func wikiContentsByName(ctx *context.APIContext, commit *git.Commit, wikiName string, isSidebarOrFooter bool) (string, string) { pageFilename := wiki_service.NameToFilename(wikiName) entry, err := findEntryForFile(commit, pageFilename) if err != nil { if git.IsErrNotExist(err) { if !isSidebarOrFooter {
-
-
-
@@ -39,7 +39,7 @@ func listGPGKeys(ctx *context.APIContext, uid int64, listOptions db.ListOptions)ctx.JSON(http.StatusOK, &apiKeys) } //ListGPGKeys get the GPG key list of a user // ListGPGKeys get the GPG key list of a user func ListGPGKeys(ctx *context.APIContext) { // swagger:operation GET /users/{username}/gpg_keys user userListGPGKeys // ---
-
@@ -71,7 +71,7 @@ func ListGPGKeys(ctx *context.APIContext) {listGPGKeys(ctx, user.ID, utils.GetListOptions(ctx)) } //ListMyGPGKeys get the GPG key list of the authenticated user // ListMyGPGKeys get the GPG key list of the authenticated user func ListMyGPGKeys(ctx *context.APIContext) { // swagger:operation GET /user/gpg_keys user userCurrentListGPGKeys // ---
-
@@ -94,7 +94,7 @@ func ListMyGPGKeys(ctx *context.APIContext) {listGPGKeys(ctx, ctx.User.ID, utils.GetListOptions(ctx)) } //GetGPGKey get the GPG key based on a id // GetGPGKey get the GPG key based on a id func GetGPGKey(ctx *context.APIContext) { // swagger:operation GET /user/gpg_keys/{id} user userCurrentGetGPGKey // ---
-
@@ -212,7 +212,7 @@ type swaggerUserCurrentPostGPGKey struct {Form api.CreateGPGKeyOption } //CreateGPGKey create a GPG key belonging to the authenticated user // CreateGPGKey create a GPG key belonging to the authenticated user func CreateGPGKey(ctx *context.APIContext) { // swagger:operation POST /user/gpg_keys user userCurrentPostGPGKey // ---
-
@@ -233,7 +233,7 @@ func CreateGPGKey(ctx *context.APIContext) {CreateUserGPGKey(ctx, *form, ctx.User.ID) } //DeleteGPGKey remove a GPG key belonging to the authenticated user // DeleteGPGKey remove a GPG key belonging to the authenticated user func DeleteGPGKey(ctx *context.APIContext) { // swagger:operation DELETE /user/gpg_keys/{id} user userCurrentDeleteGPGKey // ---
-
-
-
@@ -170,7 +170,6 @@ func Watch(ctx *context.APIContext) {URL: subscriptionURL(ctx.Repo.Repository), RepositoryURL: ctx.Repo.Repository.APIURL(), }) } // Unwatch the repo specified in ctx, as the authenticated user
-
-
-
@@ -50,12 +50,12 @@ func GetGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, strin} func searchRefCommitByType(ctx *context.APIContext, refType, filter string) (string, string, error) { refs, lastMethodName, err := GetGitRefs(ctx, refType+"/"+filter) //Search by type refs, lastMethodName, err := GetGitRefs(ctx, refType+"/"+filter) // Search by type if err != nil { return "", lastMethodName, err } if len(refs) > 0 { return refs[0].Object.String(), "", nil //Return found SHA return refs[0].Object.String(), "", nil // Return found SHA } return "", "", nil }
-
-
-
@@ -21,7 +21,7 @@ import (// Middlewares returns common middlewares func Middlewares() []func(http.Handler) http.Handler { var handlers = []func(http.Handler) http.Handler{ handlers := []func(http.Handler) http.Handler{ func(next http.Handler) http.Handler { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { // First of all escape the URL RawPath to ensure that all routing is done using a correctly escaped URL
-
-
-
@@ -54,7 +54,7 @@ func getDbTypeNames() []map[string]string {// Init prepare for rendering installation page func Init(next http.Handler) http.Handler { var rnd = templates.HTMLRenderer() rnd := templates.HTMLRenderer() return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { if setting.InstallLock {
-
@@ -62,9 +62,9 @@ func Init(next http.Handler) http.Handler {_ = rnd.HTML(resp, 200, string(tplPostInstall), nil) return } var locale = middleware.Locale(resp, req) var startTime = time.Now() var ctx = context.Context{ locale := middleware.Locale(resp, req) startTime := time.Now() ctx := context.Context{ Resp: context.NewResponse(resp), Flash: &middleware.Flash{}, Locale: locale,
-
-
-
@@ -28,7 +28,7 @@ func (d *dataStore) GetData() map[string]interface{} {} func installRecovery() func(next http.Handler) http.Handler { var rnd = templates.HTMLRenderer() rnd := templates.HTMLRenderer() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { defer func() {
-
@@ -53,7 +53,7 @@ func installRecovery() func(next http.Handler) http.Handler {log.Error("%s", combinedErr) lc := middleware.Locale(w, req) var store = dataStore{ store := dataStore{ "Language": lc.Language(), "CurrentURL": setting.AppSubURL + req.URL.RequestURI(), "i18n": lc,
-
-
-
@@ -35,12 +35,12 @@ func CheckInternalToken(next http.Handler) http.Handler {// bind binding an obj to a handler func bind(obj interface{}) http.HandlerFunc { var tp = reflect.TypeOf(obj) tp := reflect.TypeOf(obj) for tp.Kind() == reflect.Ptr { tp = tp.Elem() } return web.Wrap(func(ctx *context.PrivateContext) { var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly binding.Bind(ctx.Req, theObj) web.SetForm(ctx, theObj) })
-
@@ -49,7 +49,7 @@ func bind(obj interface{}) http.HandlerFunc {// Routes registers all internal APIs routes to web application. // These APIs will be invoked by internal commands for example `gitea serv` and etc. func Routes() *web.Route { var r = web.NewRoute() r := web.NewRoute() r.Use(context.PrivateContexter()) r.Use(CheckInternalToken)
-
-
-
@@ -18,7 +18,6 @@ import (func Restart(ctx *context.PrivateContext) { graceful.GetManager().DoGracefulRestart() ctx.PlainText(http.StatusOK, "success") } // Shutdown causes the server to perform a graceful shutdown
-
-
-
@@ -23,7 +23,7 @@ func RestoreRepo(ctx *myCtx.PrivateContext) {}) return } var params = struct { params := struct { RepoDir string OwnerName string RepoName string
-
-
-
@@ -209,7 +209,7 @@ func shadowPassword(provider, cfgItem string) string {case "redis": return shadowPasswordKV(cfgItem, ",") case "mysql": //root:@tcp(localhost:3306)/macaron?charset=utf8 // root:@tcp(localhost:3306)/macaron?charset=utf8 atIdx := strings.Index(cfgItem, "@") if atIdx > 0 { colonIdx := strings.Index(cfgItem[:atIdx], ":")
-
-
-
@@ -11,7 +11,7 @@ import () func TestShadowPassword(t *testing.T) { var kases = []struct { kases := []struct { Provider string CfgItem string Result string
-
-
-
@@ -101,9 +101,7 @@ func Emails(ctx *context.Context) {ctx.HTML(http.StatusOK, tplEmails) } var ( nullByte = []byte{0x00} ) var nullByte = []byte{0x00} func isKeywordValid(keyword string) bool { return !bytes.Contains([]byte(keyword), nullByte)
-
@@ -111,7 +109,6 @@ func isKeywordValid(keyword string) bool {// ActivateEmail serves a POST request for activating/deactivating a user's email func ActivateEmail(ctx *context.Context) { truefalse := map[string]bool{"1": true, "0": false} uid := ctx.FormInt64("uid")
-
-
-
@@ -19,7 +19,6 @@ import () func TestNewUserPost_MustChangePassword(t *testing.T) { unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new")
-
-
-
@@ -297,7 +297,7 @@ func handleSignIn(ctx *context.Context, u *user_model.User, remember bool) {ctx.Redirect(redirect) } func handleSignInFull(ctx *context.Context, u *user_model.User, remember bool, obeyRedirect bool) string { func handleSignInFull(ctx *context.Context, u *user_model.User, remember, obeyRedirect bool) string { if remember { days := 86400 * setting.LogInRememberDays ctx.SetCookie(setting.CookieUserName, u.Name, days)
-
@@ -417,7 +417,7 @@ func SignUp(ctx *context.Context) {ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey ctx.Data["PageIsSignUp"] = true //Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true // Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration ctx.HTML(http.StatusOK, tplSignUp)
-
@@ -438,7 +438,7 @@ func SignUpPost(ctx *context.Context) {ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey ctx.Data["PageIsSignUp"] = true //Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true // Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true if setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration { ctx.Error(http.StatusForbidden) return
-
-
-
@@ -27,9 +27,7 @@ import ("github.com/markbates/goth" ) var ( tplLinkAccount base.TplName = "user/auth/link_account" ) var tplLinkAccount base.TplName = "user/auth/link_account" // LinkAccount shows the page where the user can decide to login or create a new account func LinkAccount(ctx *context.Context) {
-
-
-
@@ -1158,5 +1158,4 @@ func oAuth2UserLoginCallback(authSource *auth.Source, request *http.Request, res// no user found to login return nil, gothUser, nil }
-
-
-
@@ -67,7 +67,6 @@ func SignInOpenID(ctx *context.Context) {// Check if the given OpenID URI is allowed by blacklist/whitelist func allowedOpenIDURI(uri string) (err error) { // In case a Whitelist is present, URI must be in it // in order to be accepted if len(setting.Service.OpenIDWhitelist) != 0 {
-
@@ -144,13 +143,12 @@ func SignInOpenIDPost(ctx *context.Context) {// signInOpenIDVerify handles response from OpenID provider func signInOpenIDVerify(ctx *context.Context) { log.Trace("Incoming call to: %s", ctx.Req.URL.String()) fullURL := setting.AppURL + ctx.Req.URL.String()[1:] log.Trace("Full URL: %s", fullURL) var id, err = openid.Verify(fullURL) id, err := openid.Verify(fullURL) if err != nil { ctx.RenderWithErr(err.Error(), tplSignInOpenID, &forms.SignInOpenIDForm{ Openid: id,
-
-
-
@@ -33,7 +33,7 @@ func WebAuthn(ctx *context.Context) {return } //Ensure user is in a 2FA session. // Ensure user is in a 2FA session. if ctx.Session.Get("twofaUid") == nil { ctx.ServerError("UserSignIn", errors.New("not in WebAuthn session")) return
-
-
-
@@ -92,7 +92,7 @@ func storageHandler(storageSetting setting.Storage, prefix string, objStore storreturn } //If we have matched and access to release or issue // If we have matched and access to release or issue fr, err := objStore.Open(rPath) if err != nil { if os.IsNotExist(err) || errors.Is(err, os.ErrNotExist) {
-
@@ -125,7 +125,7 @@ func (d *dataStore) GetData() map[string]interface{} {// Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so. // This error will be created with the gitea 500 page. func Recovery() func(next http.Handler) http.Handler { var rnd = templates.HTMLRenderer() rnd := templates.HTMLRenderer() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { defer func() {
-
@@ -136,14 +136,14 @@ func Recovery() func(next http.Handler) http.Handler {sessionStore := session.GetSession(req) var lc = middleware.Locale(w, req) var store = dataStore{ lc := middleware.Locale(w, req) store := dataStore{ "Language": lc.Language(), "CurrentURL": setting.AppSubURL + req.URL.RequestURI(), "i18n": lc, } var user = context.GetContextUser(req) user := context.GetContextUser(req) if user == nil { // Get user from session if logged in - do not attempt to sign-in user = auth.SessionUser(sessionStore)
-
-
-
@@ -76,7 +76,7 @@ func Code(ctx *context.Context) {return } var rightRepoMap = make(map[int64]*repo_model.Repository, len(repoMaps)) rightRepoMap := make(map[int64]*repo_model.Repository, len(repoMaps)) repoIDs = make([]int64, 0, len(repoMaps)) for id, repo := range repoMaps { if models.CheckRepoUnitUser(repo, ctx.User, unit.TypeCode) {
-
@@ -100,7 +100,7 @@ func Code(ctx *context.Context) {return } var loadRepoIDs = make([]int64, 0, len(searchResults)) loadRepoIDs := make([]int64, 0, len(searchResults)) for _, result := range searchResults { var find bool for _, id := range loadRepoIDs {
-
-
-
@@ -25,9 +25,7 @@ const (// UserSearchDefaultSortType is the default sort type for user search const UserSearchDefaultSortType = "alphabetically" var ( nullByte = []byte{0x00} ) var nullByte = []byte{0x00} func isKeywordValid(keyword string) bool { return !bytes.Contains([]byte(keyword), nullByte)
-
-
-
@@ -110,7 +110,7 @@ func Home(ctx *context.Context) {return } var opts = &models.FindOrgMembersOpts{ opts := &models.FindOrgMembersOpts{ OrgID: org.ID, PublicOnly: true, ListOptions: db.ListOptions{Page: 1, PageSize: 25},
-
-
-
@@ -31,7 +31,7 @@ func Members(ctx *context.Context) {page = 1 } var opts = &models.FindOrgMembersOpts{ opts := &models.FindOrgMembersOpts{ OrgID: org.ID, PublicOnly: true, }
-
-
-
@@ -117,7 +117,8 @@ func SettingsPost(ctx *context.Context) {// update forks visibility if visibilityChanged { repos, _, err := models.GetUserRepositories(&models.SearchRepoOptions{ Actor: org.AsUser(), Private: true, ListOptions: db.ListOptions{Page: 1, PageSize: org.NumRepos}}) Actor: org.AsUser(), Private: true, ListOptions: db.ListOptions{Page: 1, PageSize: org.NumRepos}, }) if err != nil { ctx.ServerError("GetRepositories", err) return
-
-
-
@@ -100,12 +100,12 @@ func GetAttachment(ctx *context.Context) {return } if repository == nil { //If not linked if !(ctx.IsSigned && attach.UploaderID == ctx.User.ID) { //We block if not the uploader if repository == nil { // If not linked if !(ctx.IsSigned && attach.UploaderID == ctx.User.ID) { // We block if not the uploader ctx.Error(http.StatusNotFound) return } } else { //If we have the repository we check access } else { // If we have the repository we check access perm, err := models.GetUserRepoPermission(repository, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err.Error())
-
@@ -123,7 +123,7 @@ func GetAttachment(ctx *context.Context) {} if setting.Attachment.ServeDirect { //If we have a signed url (S3, object storage), redirect to this directly. // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.Attachments.URL(attach.RelativePath(), attach.Name) if u != nil && err == nil {
-
@@ -136,7 +136,7 @@ func GetAttachment(ctx *context.Context) {return } //If we have matched and access to release or issue // If we have matched and access to release or issue fr, err := storage.Attachments.Open(attach.RelativePath()) if err != nil { ctx.ServerError("Open", err)
-
-
-
@@ -233,12 +233,12 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames mlanguage = "" } } var lines = make([]string, 0) lines := make([]string, 0) rows := make([]*blameRow, 0) escapeStatus := charset.EscapeStatus{} var i = 0 var commitCnt = 0 i := 0 commitCnt := 0 for _, part := range blameParts { for index, line := range part.Lines { i++
-
-
-
@@ -203,7 +203,7 @@ func loadBranches(ctx *context.Context, skip, limit int) (*Branch, []*Branch, incontinue } var branch = loadOneBranch(ctx, rawBranches[i], defaultBranch, protectedBranches, repoIDToRepo, repoIDToGitRepo) branch := loadOneBranch(ctx, rawBranches[i], defaultBranch, protectedBranches, repoIDToRepo, repoIDToGitRepo) if branch == nil { return nil, nil, 0 }
-
-
-
@@ -111,7 +111,7 @@ func setCsvCompareContext(ctx *context.Context) {Error string } ctx.Data["CreateCsvDiff"] = func(diffFile *gitdiff.DiffFile, baseCommit *git.Commit, headCommit *git.Commit) CsvDiffResult { ctx.Data["CreateCsvDiff"] = func(diffFile *gitdiff.DiffFile, baseCommit, headCommit *git.Commit) CsvDiffResult { if diffFile == nil || baseCommit == nil || headCommit == nil { return CsvDiffResult{nil, ""} }
-
@@ -541,8 +541,8 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo {func PrepareCompareDiff( ctx *context.Context, ci *CompareInfo, whitespaceBehavior string) bool { whitespaceBehavior string, ) bool { var ( repo = ctx.Repo.Repository err error
-
@@ -839,7 +839,8 @@ func ExcerptBlob(ctx *context.Context) {RightIdx: idxRight, LeftHunkSize: leftHunkSize, RightHunkSize: rightHunkSize, }} }, } if direction == "up" { section.Lines = append([]*gitdiff.DiffLine{lineSection}, section.Lines...) } else if direction == "down" {
-
-
-
@@ -52,7 +52,7 @@ func ServeBlobOrLFS(ctx *context.Context, blob *git.Blob) error {} if setting.LFS.ServeDirect { //If we have a signed url (S3, object storage), redirect to this directly. // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.LFS.URL(pointer.RelativePath(), blob.Name()) if u != nil && err == nil { ctx.Redirect(u.String())
-
-
-
@@ -17,7 +17,7 @@ import (func TestCleanUploadName(t *testing.T) { unittest.PrepareTestEnv(t) var kases = map[string]string{ kases := map[string]string{ ".git/refs/master": "", "/root/abc": "root/abc", "./../../abc": "abc",
-
-
-
@@ -104,7 +104,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) {} isWiki := false var unitType = unit.TypeCode unitType := unit.TypeCode var wikiRepoName string if strings.HasSuffix(reponame, ".wiki") { isWiki = true
-
@@ -457,7 +457,6 @@ func serviceRPC(ctx gocontext.Context, h serviceHandler, service string) {if err := h.r.Body.Close(); err != nil { log.Error("serviceRPC: Close: %v", err) } }() if !hasAccess(ctx, service, h, true) {
-
@@ -468,7 +467,7 @@ func serviceRPC(ctx gocontext.Context, h serviceHandler, service string) {h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service)) var err error var reqBody = h.r.Body reqBody := h.r.Body // Handle GZIP. if h.r.Header.Get("Content-Encoding") == "gzip" {
-
-
-
@@ -57,17 +57,15 @@ const (issueTemplateTitleKey = "IssueTemplateTitle" ) var ( // IssueTemplateCandidates issue templates IssueTemplateCandidates = []string{ "ISSUE_TEMPLATE.md", "issue_template.md", ".gitea/ISSUE_TEMPLATE.md", ".gitea/issue_template.md", ".github/ISSUE_TEMPLATE.md", ".github/issue_template.md", } ) // IssueTemplateCandidates issue templates var IssueTemplateCandidates = []string{ "ISSUE_TEMPLATE.md", "issue_template.md", ".gitea/ISSUE_TEMPLATE.md", ".gitea/issue_template.md", ".github/ISSUE_TEMPLATE.md", ".github/issue_template.md", } // MustAllowUserComment checks to make sure if an issue is locked. // If locked and user has permissions to write to the repository,
-
@@ -245,7 +243,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti} } var issueList = models.IssueList(issues) issueList := models.IssueList(issues) approvalCounts, err := issueList.GetApprovalCounts() if err != nil { ctx.ServerError("ApprovalCounts", err)
-
@@ -311,8 +309,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption utiassigneeID = 0 // Reset ID to prevent unexpected selection of assignee. } ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, ctx.Repo.RepoLink) ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, ctx.Repo.RepoLink) ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 { counts, ok := approvalCounts[issueID]
-
@@ -442,7 +439,6 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.R} func retrieveProjects(ctx *context.Context, repo *repo_model.Repository) { var err error ctx.Data["OpenProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{
-
@@ -2508,7 +2504,7 @@ func filterXRefComments(ctx *context.Context, issue *models.Issue) error {// GetIssueAttachments returns attachments for the issue func GetIssueAttachments(ctx *context.Context) { issue := GetActionIssue(ctx) var attachments = make([]*api.Attachment, len(issue.Attachments)) attachments := make([]*api.Attachment, len(issue.Attachments)) for i := 0; i < len(issue.Attachments); i++ { attachments[i] = convert.ToReleaseAttachment(issue.Attachments[i]) }
-
@@ -2522,7 +2518,7 @@ func GetCommentAttachments(ctx *context.Context) {ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err) return } var attachments = make([]*api.Attachment, 0) attachments := make([]*api.Attachment, 0) if comment.Type == models.CommentTypeComment { if err := comment.LoadAttachments(); err != nil { ctx.ServerError("LoadAttachments", err)
-
@@ -2667,7 +2663,7 @@ func handleTeamMentions(ctx *context.Context) {var isAdmin bool var err error var teams []*models.Team var org = models.OrgFromUser(ctx.Repo.Owner) org := models.OrgFromUser(ctx.Repo.Owner) // Admin has super access. if ctx.User.IsAdmin { isAdmin = true
-
-
-
@@ -83,8 +83,8 @@ func GetContentHistoryList(ctx *context.Context) {// canSoftDeleteContentHistory checks whether current user can soft-delete a history revision // Admins or owners can always delete history revisions. Normal users can only delete own history revisions. func canSoftDeleteContentHistory(ctx *context.Context, issue *models.Issue, comment *models.Comment, history *issuesModel.ContentHistory) bool { history *issuesModel.ContentHistory, ) bool { canSoftDelete := false if ctx.Repo.IsOwner() { canSoftDelete = true
-
@@ -103,7 +103,7 @@ func canSoftDeleteContentHistory(ctx *context.Context, issue *models.Issue, commreturn canSoftDelete } //GetContentHistoryDetail get detail // GetContentHistoryDetail get detail func GetContentHistoryDetail(ctx *context.Context) { issue := GetActionIssue(ctx) if issue == nil {
-
@@ -169,7 +169,7 @@ func GetContentHistoryDetail(ctx *context.Context) {}) } //SoftDeleteContentHistory soft delete // SoftDeleteContentHistory soft delete func SoftDeleteContentHistory(ctx *context.Context) { issue := GetActionIssue(ctx) if issue == nil {
-
-
-
@@ -48,7 +48,6 @@ func LockIssue(ctx *context.Context) {// UnlockIssue unlocks a previously locked issue. func UnlockIssue(ctx *context.Context) { issue := GetActionIssue(ctx) if ctx.Written() { return
-
-
-
@@ -13,7 +13,7 @@ import () func TestCombineLabelComments(t *testing.T) { var kases = []struct { kases := []struct { name string beforeCombined []*models.Comment afterCombined []*models.Comment
-
@@ -366,7 +366,7 @@ func TestCombineLabelComments(t *testing.T) {for _, kase := range kases { t.Run(kase.name, func(t *testing.T) { var issue = models.Issue{ issue := models.Issue{ Comments: kase.beforeCombined, } combineLabelComments(&issue)
-
-
-
@@ -305,7 +305,7 @@ func LFSFileGet(ctx *context.Context) {var output bytes.Buffer lines := strings.Split(escapedContent.String(), "\n") //Remove blank line at the end of file // Remove blank line at the end of file if len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] }
-
@@ -536,7 +536,7 @@ func LFSAutoAssociate(ctx *context.Context) {return } metas[i].Oid = oid[:idx] //metas[i].RepositoryID = ctx.Repo.Repository.ID // metas[i].RepositoryID = ctx.Repo.Repository.ID } if err := models.LFSAutoAssociate(metas, ctx.User, ctx.Repo.Repository.ID); err != nil { ctx.ServerError("LFSAutoAssociate", err)
-
-
-
@@ -203,7 +203,7 @@ func MigratePost(ctx *context.Context) {} } var opts = migrations.MigrateOptions{ opts := migrations.MigrateOptions{ OriginalURL: form.CloneAddr, GitServiceType: form.Service, CloneAddr: remoteAddr,
-
-
-
@@ -531,7 +531,6 @@ func EditProjectBoard(ctx *context.Context) {// SetDefaultProjectBoard set default board for uncategorized issues/pulls func SetDefaultProjectBoard(ctx *context.Context) { project, board := checkProjectBoardChangePermissions(ctx) if ctx.Written() { return
-
-
-
@@ -48,16 +48,14 @@ const (pullRequestTemplateKey = "PullRequestTemplate" ) var ( pullRequestTemplateCandidates = []string{ "PULL_REQUEST_TEMPLATE.md", "pull_request_template.md", ".gitea/PULL_REQUEST_TEMPLATE.md", ".gitea/pull_request_template.md", ".github/PULL_REQUEST_TEMPLATE.md", ".github/pull_request_template.md", } ) var pullRequestTemplateCandidates = []string{ "PULL_REQUEST_TEMPLATE.md", "pull_request_template.md", ".gitea/PULL_REQUEST_TEMPLATE.md", ".gitea/pull_request_template.md", ".github/PULL_REQUEST_TEMPLATE.md", ".github/pull_request_template.md", } func getRepository(ctx *context.Context, repoID int64) *repo_model.Repository { repo, err := repo_model.GetRepositoryByID(repoID)
-
@@ -125,7 +123,7 @@ func getForkRepository(ctx *context.Context) *repo_model.Repository {} } var traverseParentRepo = forkRepo traverseParentRepo := forkRepo for { if ctx.User.ID == traverseParentRepo.OwnerID { canForkToUser = false
-
@@ -195,7 +193,7 @@ func ForkPost(ctx *context.Context) {} var err error var traverseParentRepo = forkRepo traverseParentRepo := forkRepo for { if ctxUser.ID == traverseParentRepo.OwnerID { ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form)
-
@@ -1085,7 +1083,6 @@ func MergePullRequest(ctx *context.Context) {} func stopTimerIfAvailable(user *user_model.User, issue *models.Issue) error { if models.StopwatchExists(user.ID, issue.ID) { if err := models.CreateOrStopIssueStopwatch(user, issue); err != nil { return err
-
-
-
@@ -481,7 +481,7 @@ func EditReleasePost(ctx *context.Context) {const delPrefix = "attachment-del-" const editPrefix = "attachment-edit-" var addAttachmentUUIDs, delAttachmentUUIDs []string var editAttachments = make(map[string]string) // uuid -> new name editAttachments := make(map[string]string) // uuid -> new name if setting.Attachment.Enabled { addAttachmentUUIDs = form.Files for k, v := range ctx.Req.Form {
-
-
-
@@ -410,7 +410,7 @@ func Download(ctx *context.Context) {} var times int var t = time.NewTicker(time.Second * 1) t := time.NewTicker(time.Second * 1) defer t.Stop() for {
-
@@ -447,7 +447,7 @@ func download(ctx *context.Context, archiveName string, archiver *repo_model.Rep} if setting.RepoArchive.ServeDirect { //If we have a signed url (S3, object storage), redirect to this directly. // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.RepoArchives.URL(rPath, downloadName) if u != nil && err == nil { ctx.Redirect(u.String())
-
@@ -455,7 +455,7 @@ func download(ctx *context.Context, archiveName string, archiver *repo_model.Rep} } //If we have matched and access to release or issue // If we have matched and access to release or issue fr, err := storage.RepoArchives.Open(rPath) if err != nil { ctx.ServerError("Open", err)
-
-
-
@@ -100,7 +100,6 @@ func TestAddReadWriteOnlyDeployKey(t *testing.T) {} func TestCollaborationPost(t *testing.T) { unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2)
-
@@ -136,7 +135,6 @@ func TestCollaborationPost(t *testing.T) {} func TestCollaborationPost_InactiveUser(t *testing.T) { unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2)
-
@@ -160,7 +158,6 @@ func TestCollaborationPost_InactiveUser(t *testing.T) {} func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) { unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2)
-
@@ -202,7 +199,6 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) {} func TestCollaborationPost_NonExistentUser(t *testing.T) { unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2)
-
@@ -302,7 +298,6 @@ func TestAddTeamPost_NotAllowed(t *testing.T) {assert.False(t, team.HasRepository(re.ID)) assert.EqualValues(t, http.StatusFound, ctx.Resp.Status()) assert.NotEmpty(t, ctx.Flash.ErrorMsg) } func TestAddTeamPost_AddTeamTwice(t *testing.T) {
-
-
-
@@ -22,8 +22,8 @@ func TopicsPost(ctx *context.Context) {return } var topics = make([]string, 0) var topicsStr = ctx.FormTrim("topics") topics := make([]string, 0) topicsStr := ctx.FormTrim("topics") if len(topicsStr) > 0 { topics = strings.Split(topicsStr, ",") }
-
-
-
@@ -77,7 +77,7 @@ func getReadmeFileFromPath(commit *git.Commit, treePath string) (*namedBlob, err} var readmeFiles [4]*namedBlob var exts = []string{".md", ".txt", ""} // sorted by priority exts := []string{".md", ".txt", ""} // sorted by priority for _, entry := range entries { if entry.IsDir() { continue
-
@@ -150,7 +150,7 @@ func renderDirectory(ctx *context.Context, treeLink string) {// strictly match an extension var readmeFiles [4]*namedBlob var docsEntries [3]*git.TreeEntry var exts = []string{".md", ".txt", ""} // sorted by priority exts := []string{".md", ".txt", ""} // sorted by priority for _, entry := range entries { if entry.IsDir() { lowerName := strings.ToLower(entry.Name())
-
@@ -368,7 +368,6 @@ func renderDirectory(ctx *context.Context, treeLink string) {ctx.Data["CanAddFile"] = !ctx.Repo.Repository.IsArchived ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled && !ctx.Repo.Repository.IsArchived } } func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
-
@@ -399,7 +398,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink stisDisplayingSource := ctx.FormString("display") == "source" isDisplayingRendered := !isDisplayingSource //Check for LFS meta file // Check for LFS meta file if isTextFile && setting.LFS.StartServer { pointer, _ := lfs.ReadPointerFromBuffer(buf) if pointer.IsValid() {
-
-
-
@@ -191,7 +191,7 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {ctx.Data["title"] = pageName ctx.Data["RequireHighlightJS"] = true //lookup filename in wiki - get filecontent, gitTree entry , real filename // lookup filename in wiki - get filecontent, gitTree entry , real filename data, entry, pageFilename, noEntry := wikiContentsByName(ctx, commit, pageName) if noEntry { ctx.Redirect(ctx.Repo.RepoLink + "/wiki/?action=_pages")
-
@@ -219,7 +219,7 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) {return nil, nil } var rctx = &markup.RenderContext{ rctx := &markup.RenderContext{ Ctx: ctx, URLPrefix: ctx.Repo.RepoLink, Metas: ctx.Repo.Repository.ComposeDocumentMetas(),
-
@@ -291,7 +291,7 @@ func renderRevisionPage(ctx *context.Context) (*git.Repository, *git.TreeEntry)ctx.Data["Username"] = ctx.Repo.Owner.Name ctx.Data["Reponame"] = ctx.Repo.Repository.Name //lookup filename in wiki - get filecontent, gitTree entry , real filename // lookup filename in wiki - get filecontent, gitTree entry , real filename data, entry, pageFilename, noEntry := wikiContentsByName(ctx, commit, pageName) if noEntry { ctx.Redirect(ctx.Repo.RepoLink + "/wiki/?action=_pages")
-
@@ -365,7 +365,7 @@ func renderEditPage(ctx *context.Context) {ctx.Data["title"] = pageName ctx.Data["RequireHighlightJS"] = true //lookup filename in wiki - get filecontent, gitTree entry , real filename // lookup filename in wiki - get filecontent, gitTree entry , real filename data, entry, _, noEntry := wikiContentsByName(ctx, commit, pageName) if noEntry { ctx.Redirect(ctx.Repo.RepoLink + "/wiki/?action=_pages")
-
-
-
@@ -20,8 +20,10 @@ import ("github.com/stretchr/testify/assert" ) const content = "Wiki contents for unit tests" const message = "Wiki commit message for unit tests" const ( content = "Wiki contents for unit tests" message = "Wiki commit message for unit tests" ) func wikiEntry(t *testing.T, repo *repo_model.Repository, wikiName string) *git.TreeEntry { wikiRepo, err := git.OpenRepository(repo.WikiPath())
-
-
-
@@ -197,7 +197,7 @@ func Milestones(ctx *context.Context) {if issueReposQueryPattern.MatchString(reposQuery) { // remove "[" and "]" from string reposQuery = reposQuery[1 : len(reposQuery)-1] //for each ID (delimiter ",") add to int to repoIDs // for each ID (delimiter ",") add to int to repoIDs for _, rID := range strings.Split(reposQuery, ",") { // Ensure nonempty string entries
-
@@ -350,7 +350,6 @@ func Issues(ctx *context.Context) {var issueReposQueryPattern = regexp.MustCompile(`^\[\d+(,\d+)*,?\]$`) func buildIssueOverview(ctx *context.Context, unitType unit.Type) { // ---------------------------------------------------- // Determine user; can be either user or organization. // Return with NotFound or ServerError if unsuccessful.
-
@@ -586,8 +585,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) {ctx.Data["IsShowClosed"] = isShowClosed ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, ctx.FormString("RepoLink")) ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, ctx.FormString("RepoLink")) ctx.Data["Issues"] = issues
-
@@ -661,7 +659,7 @@ func getRepoIDs(reposQuery string) []int64 {var repoIDs []int64 // remove "[" and "]" from string reposQuery = reposQuery[1 : len(reposQuery)-1] //for each ID (delimiter ",") add to int to repoIDs // for each ID (delimiter ",") add to int to repoIDs for _, rID := range strings.Split(reposQuery, ",") { // Ensure nonempty string entries if rID != "" && rID != "0" {
-
@@ -693,8 +691,8 @@ func issueIDsFromSearch(ctxUser *user_model.User, keyword string, opts *models.I} func loadRepoByIDs(ctxUser *user_model.User, issueCountByRepo map[int64]int64, unitType unit.Type) (map[int64]*repo_model.Repository, error) { var totalRes = make(map[int64]*repo_model.Repository, len(issueCountByRepo)) var repoIDs = make([]int64, 0, 500) totalRes := make(map[int64]*repo_model.Repository, len(issueCountByRepo)) repoIDs := make([]int64, 0, 500) for id := range issueCountByRepo { if id <= 0 { continue
-
@@ -745,7 +743,7 @@ func ShowGPGKeys(ctx *context.Context, uid int64) {if err != nil { if asymkey_model.IsErrGPGKeyImportNotExist(err) { failedEntitiesID = append(failedEntitiesID, k.KeyID) continue //Skip previous import without backup of imported armored key continue // Skip previous import without backup of imported armored key } ctx.ServerError("ShowGPGKeys", err) return
-
@@ -755,12 +753,12 @@ func ShowGPGKeys(ctx *context.Context, uid int64) {var buf bytes.Buffer headers := make(map[string]string) if len(failedEntitiesID) > 0 { //If some key need re-import to be exported if len(failedEntitiesID) > 0 { // If some key need re-import to be exported headers["Note"] = fmt.Sprintf("The keys with the following IDs couldn't be exported and need to be reuploaded %s", strings.Join(failedEntitiesID, ", ")) } writer, _ := armor.Encode(&buf, "PGP PUBLIC KEY BLOCK", headers) for _, e := range entities { err = e.Serialize(writer) //TODO find why key are exported with a different cipherTypeByte as original (should not be blocking but strange) err = e.Serialize(writer) // TODO find why key are exported with a different cipherTypeByte as original (should not be blocking but strange) if err != nil { ctx.ServerError("ShowGPGKeys", err) return
-
-
-
@@ -258,7 +258,8 @@ func Profile(ctx *context.Context) {total = ctxUser.NumFollowing case "activity": ctx.Data["Feeds"] = feed.RetrieveFeeds(ctx, models.GetFeedsOptions{RequestedUser: ctxUser, ctx.Data["Feeds"] = feed.RetrieveFeeds(ctx, models.GetFeedsOptions{ RequestedUser: ctxUser, Actor: ctx.User, IncludePrivate: showPrivate, OnlyPerformedBy: true,
-
-
-
@@ -20,9 +20,9 @@ import (func TestChangePassword(t *testing.T) { oldPassword := "password" setting.MinPasswordLength = 6 var pcALL = []string{"lower", "upper", "digit", "spec"} var pcLUN = []string{"lower", "upper", "digit"} var pcLU = []string{"lower", "upper"} pcALL := []string{"lower", "upper", "digit", "spec"} pcLUN := []string{"lower", "upper", "digit"} pcLU := []string{"lower", "upper"} for _, req := range []struct { OldPassword string
-
-
-
@@ -211,7 +211,6 @@ func KeysPost(ctx *context.Context) {ctx.Flash.Warning("Function not implemented") ctx.Redirect(setting.AppSubURL + "/user/settings/keys") } } // DeleteKey response for delete user's SSH/GPG key
-
-
-
@@ -415,5 +415,4 @@ func UpdateUserLang(ctx *context.Context) {log.Trace("User settings updated: %s", ctx.User.Name) ctx.Flash.Success(i18n.Tr(ctx.User.Language, "settings.update_language_success")) ctx.Redirect(setting.AppSubURL + "/user/settings/appearance") }
-
-
-
@@ -56,9 +56,9 @@ const (func CorsHandler() func(next http.Handler) http.Handler { if setting.CORSConfig.Enabled { return cors.Handler(cors.Options{ //Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option AllowedOrigins: setting.CORSConfig.AllowDomain, //setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option AllowedMethods: setting.CORSConfig.Methods, AllowCredentials: setting.CORSConfig.AllowCredentials, MaxAge: int(setting.CORSConfig.MaxAge.Seconds()),
-
@@ -459,7 +459,6 @@ func RegisterRoutes(m *web.Route) {m.Post("/msteams/new", bindIgnErr(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost) m.Post("/feishu/new", bindIgnErr(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost) m.Post("/wechatwork/new", bindIgnErr(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost) }) m.Group("/auths", func() {
-
@@ -691,7 +690,6 @@ func RegisterRoutes(m *web.Route) {m.Post("/{lid}/unlock", repo.LFSUnlock) }) }) }, func(ctx *context.Context) { ctx.Data["PageIsSettings"] = true ctx.Data["LFSStartServer"] = setting.LFS.StartServer
-
@@ -818,7 +816,6 @@ func RegisterRoutes(m *web.Route) {m.Post("/delete", repo.DeleteBranchPost) m.Post("/restore", repo.RestoreBranchPost) }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty) }, reqSignIn, context.RepoAssignment, context.UnitTypes()) // Releases
-
@@ -857,7 +854,6 @@ func RegisterRoutes(m *web.Route) {} ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount }) }, ignSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoReleaseReader) // to maintain compatibility with old attachments
-
@@ -1085,5 +1081,4 @@ func RegisterRoutes(m *web.Route) {ctx := context.GetContext(req) ctx.NotFound("", nil) }) }
-
-
-
@@ -95,8 +95,10 @@ func isAttachmentDownload(req *http.Request) bool {return strings.HasPrefix(req.URL.Path, "/attachments/") && req.Method == "GET" } var gitRawReleasePathRe = regexp.MustCompile(`^/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+/(?:(?:git-(?:(?:upload)|(?:receive))-pack$)|(?:info/refs$)|(?:HEAD$)|(?:objects/)|(?:raw/)|(?:releases/download/))`) var lfsPathRe = regexp.MustCompile(`^/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+/info/lfs/`) var ( gitRawReleasePathRe = regexp.MustCompile(`^/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+/(?:(?:git-(?:(?:upload)|(?:receive))-pack$)|(?:info/refs$)|(?:HEAD$)|(?:objects/)|(?:raw/)|(?:releases/download/))`) lfsPathRe = regexp.MustCompile(`^/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+/info/lfs/`) ) func isGitRawReleaseOrLFSPath(req *http.Request) bool { if gitRawReleasePathRe.MatchString(req.URL.Path) {
-
-
-
@@ -13,7 +13,6 @@ import () func Test_isGitRawOrLFSPath(t *testing.T) { tests := []struct { path string
-
-
-
@@ -30,8 +30,7 @@ const BasicMethodName = "basic"// Basic implements the Auth interface and authenticates requests (API requests // only) by looking for Basic authentication data or "x-oauth-basic" token in the "Authorization" // header. type Basic struct { } type Basic struct{} // Name represents the name of auth method func (b *Basic) Name() string {
-
-
-
@@ -53,8 +53,7 @@ func CheckOAuthAccessToken(accessToken string) int64 {// OAuth2 implements the Auth interface and authenticates requests // (API requests only) by looking for an OAuth token in query parameters or the // "Authorization" header. type OAuth2 struct { } type OAuth2 struct{} // Name represents the name of auth method func (o *OAuth2) Name() string {
-
-
-
@@ -32,8 +32,7 @@ const ReverseProxyMethodName = "reverse_proxy"// On successful authentication the proxy is expected to populate the username in the // "setting.ReverseProxyAuthUser" header. Optionally it can also populate the email of the // user in the "setting.ReverseProxyAuthEmail" header. type ReverseProxy struct { } type ReverseProxy struct{} // getUserName extracts the username from the "setting.ReverseProxyAuthUser" header func (r *ReverseProxy) getUserName(req *http.Request) string {
-
-
-
@@ -19,8 +19,7 @@ var (// Session checks if there is a user uid stored in the session and returns the user // object for that uid. type Session struct { } type Session struct{} // Name represents the name of auth method func (s *Session) Name() string {
-
-
-
@@ -164,7 +164,6 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {if err == nil && len(source.AttributeAvatar) > 0 { _ = user_service.UploadAvatar(usr, su.Avatar) } } } }
-
-
-
@@ -410,7 +410,7 @@ func loadOrCreateAsymmetricKey() (interface{}, error) {return err } f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err }
-
-
-
@@ -139,10 +139,8 @@ func ClearProviders() {goth.ClearProviders() } var ( // ErrAuthSourceNotActived login source is not actived error ErrAuthSourceNotActived = errors.New("auth source is not actived") ) // ErrAuthSourceNotActived login source is not actived error var ErrAuthSourceNotActived = errors.New("auth source is not actived") // used to create different types of goth providers func createProvider(providerName string, source *Source) (goth.Provider, error) {
-
-
-
@@ -13,8 +13,7 @@ import () // OpenIDProvider is a GothProvider for OpenID type OpenIDProvider struct { } type OpenIDProvider struct{} // Name provides the technical name for this provider func (o *OpenIDProvider) Name() string {
-
-
-
@@ -107,5 +107,4 @@ func init() {return microsoftonline.New(clientID, secret, callbackURL, scopes...) }, )) }
-
-
-
@@ -18,7 +18,7 @@ func (source *Source) Callout(request *http.Request, response http.ResponseWrite// don't use the default gothic begin handler to prevent issues when some error occurs // normally the gothic library will write some custom stuff to the response instead of our own nice error page //gothic.BeginAuthHandler(response, request) // gothic.BeginAuthHandler(response, request) gothRWMutex.RLock() defer gothRWMutex.RUnlock()
-
-
-
@@ -51,10 +51,8 @@ const (// Authenticators contains available SMTP authentication type names. var Authenticators = []string{PlainAuthentication, LoginAuthentication, CRAMMD5Authentication} var ( // ErrUnsupportedLoginType login source is unknown error ErrUnsupportedLoginType = errors.New("Login source is unknown") ) // ErrUnsupportedLoginType login source is unknown error var ErrUnsupportedLoginType = errors.New("Login source is unknown") // Authenticate performs an SMTP authentication. func Authenticate(a smtp.Auth, source *Source) error {
-
-
-
@@ -40,7 +40,7 @@ func CreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issu// UpdateComment updates information of comment. func UpdateComment(c *models.Comment, doer *user_model.User, oldContent string) error { var needsContentHistory = c.Content != oldContent && needsContentHistory := c.Content != oldContent && (c.Type == models.CommentTypeComment || c.Type == models.CommentTypeReview || c.Type == models.CommentTypeCode) if needsContentHistory { hasContentHistory, err := issues.HasIssueContentHistory(db.DefaultContext, c.IssueID, c.ID)
-
-
-
@@ -43,7 +43,6 @@ func NewContext() {started = false lock.Unlock() }) } // TaskTableRow represents a task row in the tasks table
-
-
-
@@ -19,10 +19,12 @@ import ("code.gitea.io/gitea/modules/setting" ) var lock = sync.Mutex{} var started = false var tasks = []*Task{} var tasksMap = map[string]*Task{} var ( lock = sync.Mutex{} started = false tasks = []*Task{} tasksMap = map[string]*Task{} ) // Task represents a Cron task type Task struct {
-
-
-
@@ -13,7 +13,6 @@ import () func TestSubmitReviewForm_IsEmpty(t *testing.T) { cases := []struct { form SubmitReviewForm expected bool
-
@@ -43,7 +42,6 @@ func TestSubmitReviewForm_IsEmpty(t *testing.T) {} func TestIssueLock_HasValidReason(t *testing.T) { // Init settings _ = setting.Repository
-
-
-
@@ -12,9 +12,11 @@ import ("code.gitea.io/gitea/modules/util" ) const unmappedColumn = -1 const maxRowsToInspect int = 10 const minRatioToMatch float32 = 0.8 const ( unmappedColumn = -1 maxRowsToInspect int = 10 minRatioToMatch float32 = 0.8 ) // TableDiffCellType represents the type of a TableDiffCell. type TableDiffCellType uint8
-
@@ -172,7 +174,7 @@ func createCsvDiff(diffFile *DiffFile, baseReader, headReader *csv.Reader) ([]*T// createDiffTableRow takes the row # of the `a` line and `b` line of a diff (starting from 1), 0 if the line doesn't exist (undefined) // in the base or head respectively. // Returns a TableDiffRow which has the row index createDiffTableRow := func(aLineNum int, bLineNum int) (*TableDiffRow, error) { createDiffTableRow := func(aLineNum, bLineNum int) (*TableDiffRow, error) { // diffTableCells is a row of the diff table. It will have a cells for added, deleted, changed, and unchanged content, thus either // the same size as the head table or bigger diffTableCells := make([]*TableDiffCell, numDiffTableCols)
-
-
-
@@ -16,7 +16,7 @@ import () func TestCSVDiff(t *testing.T) { var cases = []struct { cases := []struct { diff string base string head string
-
@@ -35,7 +35,8 @@ func TestCSVDiff(t *testing.T) {a,a`, cells: [][]TableDiffCellType{ {TableDiffCellAdd, TableDiffCellAdd}, {TableDiffCellAdd, TableDiffCellAdd}}, {TableDiffCellAdd, TableDiffCellAdd}, }, }, // case 1 - adding 1 row at end {
-
@@ -53,7 +54,8 @@ a,a`,a,a b,b`, cells: [][]TableDiffCellType{ {TableDiffCellUnchanged, TableDiffCellUnchanged}, {TableDiffCellUnchanged, TableDiffCellUnchanged}, {TableDiffCellUnchanged, TableDiffCellUnchanged}, {TableDiffCellUnchanged, TableDiffCellUnchanged}, {TableDiffCellAdd, TableDiffCellAdd}, }, },
-
@@ -72,7 +74,8 @@ b,b`,head: `col1,col2 b,b`, cells: [][]TableDiffCellType{ {TableDiffCellUnchanged, TableDiffCellUnchanged}, {TableDiffCellDel, TableDiffCellDel}, {TableDiffCellUnchanged, TableDiffCellUnchanged}, {TableDiffCellDel, TableDiffCellDel}, {TableDiffCellUnchanged, TableDiffCellUnchanged}, }, },
-
-
-
@@ -190,9 +190,11 @@ var (codeTagSuffix = []byte(`</span>`) ) var unfinishedtagRegex = regexp.MustCompile(`<[^>]*$`) var trailingSpanRegex = regexp.MustCompile(`<span\s*[[:alpha:]="]*?[>]?$`) var entityRegex = regexp.MustCompile(`&[#]*?[0-9[:alpha:]]*$`) var ( unfinishedtagRegex = regexp.MustCompile(`<[^>]*$`) trailingSpanRegex = regexp.MustCompile(`<span\s*[[:alpha:]="]*?[>]?$`) entityRegex = regexp.MustCompile(`&[#]*?[0-9[:alpha:]]*$`) ) // shouldWriteInline represents combinations where we manually write inline changes func shouldWriteInline(diff diffmatchpatch.Diff, lineType DiffLineType) bool {
-
@@ -206,7 +208,6 @@ func shouldWriteInline(diff diffmatchpatch.Diff, lineType DiffLineType) bool {} func fixupBrokenSpans(diffs []diffmatchpatch.Diff) []diffmatchpatch.Diff { // Create a new array to store our fixed up blocks fixedup := make([]diffmatchpatch.Diff, 0, len(diffs))
-
@@ -658,10 +659,10 @@ func (diffFile *DiffFile) GetTailSection(gitRepo *git.Repository, leftCommitID,LastRightIdx: lastLine.RightIdx, LeftIdx: leftLineCount, RightIdx: rightLineCount, }} }, } tailSection := &DiffSection{FileName: diffFile.Name, Lines: []*DiffLine{tailDiffLine}} return tailSection } func getCommitFileLineCount(commit *git.Commit, filePath string) int {
-
@@ -942,8 +943,8 @@ parsingLoop:// TODO: There are numerous issues with this: // - we might want to consider detecting encoding while parsing but... // - we're likely to fail to get the correct encoding here anyway as we won't have enough information var diffLineTypeBuffers = make(map[DiffLineType]*bytes.Buffer, 3) var diffLineTypeDecoders = make(map[DiffLineType]*encoding.Decoder, 3) diffLineTypeBuffers := make(map[DiffLineType]*bytes.Buffer, 3) diffLineTypeDecoders := make(map[DiffLineType]*encoding.Decoder, 3) diffLineTypeBuffers[DiffLinePlain] = new(bytes.Buffer) diffLineTypeBuffers[DiffLineAdd] = new(bytes.Buffer) diffLineTypeBuffers[DiffLineDel] = new(bytes.Buffer)
-
@@ -1539,7 +1540,8 @@ func GetWhitespaceFlag(whiteSpaceBehavior string) string {"ignore-all": "-w", "ignore-change": "-b", "ignore-eol": "--ignore-space-at-eol", "": ""} "": "", } return whitespaceFlags[whiteSpaceBehavior] }
-
-
-
@@ -504,7 +504,7 @@ index 6961180..9ba1a00 100644// Test max lines diffBuilder := &strings.Builder{} var diff = `diff --git a/newfile2 b/newfile2 diff := `diff --git a/newfile2 b/newfile2 new file mode 100644 index 0000000..6bb8f39 --- /dev/null
-
@@ -594,7 +594,7 @@ index 0000000..6bb8f39} println(result) var diff2 = `diff --git "a/A \\ B" "b/A \\ B" diff2 := `diff --git "a/A \\ B" "b/A \\ B" --- "a/A \\ B" +++ "b/A \\ B" @@ -1,3 +1,6 @@
-
@@ -611,7 +611,7 @@ index 0000000..6bb8f39} println(result) var diff2a = `diff --git "a/A \\ B" b/A/B diff2a := `diff --git "a/A \\ B" b/A/B --- "a/A \\ B" +++ b/A/B @@ -1,3 +1,6 @@
-
@@ -628,7 +628,7 @@ index 0000000..6bb8f39} println(result) var diff3 = `diff --git a/README.md b/README.md diff3 := `diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@
-
@@ -665,6 +665,7 @@ func setupDefaultDiff() *Diff {}, } } func TestDiff_LoadComments(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase())
-
-
-
@@ -162,8 +162,8 @@ func AddAssigneeIfNotAssigned(issue *models.Issue, doer *user_model.User, assign// GetRefEndNamesAndURLs retrieves the ref end names (e.g. refs/heads/branch-name -> branch-name) // and their respective URLs. func GetRefEndNamesAndURLs(issues []*models.Issue, repoLink string) (map[int64]string, map[int64]string) { var issueRefEndNames = make(map[int64]string, len(issues)) var issueRefURLs = make(map[int64]string, len(issues)) issueRefEndNames := make(map[int64]string, len(issues)) issueRefURLs := make(map[int64]string, len(issues)) for _, issue := range issues { if issue.Ref != "" { issueRefEndNames[issue.ID] = git.RefEndName(issue.Ref)
-
-
-
@@ -15,7 +15,7 @@ import () func TestIssue_AddLabels(t *testing.T) { var tests = []struct { tests := []struct { issueID int64 labelIDs []int64 doerID int64
-
@@ -41,7 +41,7 @@ func TestIssue_AddLabels(t *testing.T) {} func TestIssue_AddLabel(t *testing.T) { var tests = []struct { tests := []struct { issueID int64 labelID int64 doerID int64
-
-
-
@@ -80,7 +80,7 @@ func GetListLockHandler(ctx *context.Context) {limit = 0 } id := ctx.FormString("id") if id != "" { //Case where we request a specific id if id != "" { // Case where we request a specific id v, err := strconv.ParseInt(id, 10, 64) if err != nil { ctx.JSON(http.StatusBadRequest, api.LFSLockError{
-
@@ -97,7 +97,7 @@ func GetListLockHandler(ctx *context.Context) {} path := ctx.FormString("path") if path != "" { //Case where we request a specific id if path != "" { // Case where we request a specific id lock, err := models.GetLFSLock(repository, path) if err != nil && !models.IsErrLFSLockNotExist(err) { log.Error("Unable to get lock for repository %-v with path %s: Error: %v", repository, path, err)
-
@@ -106,7 +106,7 @@ func GetListLockHandler(ctx *context.Context) {return } //If no query params path or id // If no query params path or id lockList, err := models.GetLFSLockByRepoID(repository.ID, cursor, limit) if err != nil { log.Error("Unable to list locks for repository ID[%d]: Error: %v", repository.ID, err)
-
-
-
@@ -440,7 +440,7 @@ func buildObjectResponse(rc *requestContext, pointer lfs_module.Pointer, downloaif download { rep.Actions["download"] = &lfs_module.Link{Href: rc.DownloadLink(pointer), Header: header} if setting.LFS.ServeDirect { //If we have a signed url (S3, object storage), redirect to this directly. // If we have a signed url (S3, object storage), redirect to this directly. u, err := storage.LFS.URL(pointer.RelativePath(), pointer.Oid) if u != nil && err == nil { rep.Actions["download"] = &lfs_module.Link{Href: u.String(), Header: header}
-
-
-
@@ -40,7 +40,6 @@ const (// 1. Repository watchers (except for WIP pull requests) and users who are participated in comments. // 2. Users who are not in 1. but get mentioned in current issue/comment. func mailIssueCommentToParticipants(ctx *mailCommentContext, mentions []*user_model.User) error { // Required by the mail composer; make sure to load these before calling the async function if err := ctx.Issue.LoadRepo(); err != nil { return fmt.Errorf("LoadRepo(): %v", err)
-
-
-
@@ -44,7 +44,7 @@ const bodyTpl = `func prepareMailerTest(t *testing.T) (doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment) { assert.NoError(t, unittest.PrepareTestDatabase()) var mailService = setting.Mailer{ mailService := setting.Mailer{ From: "test@gitea.com", }
-
@@ -67,8 +67,10 @@ func TestComposeIssueCommentMessage(t *testing.T) {InitMailRender(stpl, btpl) recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}, {Name: "Test2", Email: "test2@gitea.com"}} msgs, err := composeIssueCommentMessages(&mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, Content: "test body", Comment: comment}, "en-US", recipients, false, "issue comment") msgs, err := composeIssueCommentMessages(&mailCommentContext{ Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, Content: "test body", Comment: comment, }, "en-US", recipients, false, "issue comment") assert.NoError(t, err) assert.Len(t, msgs, 2) gomailMsg := msgs[0].ToMessage()
-
@@ -94,8 +96,10 @@ func TestComposeIssueMessage(t *testing.T) {InitMailRender(stpl, btpl) recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}, {Name: "Test2", Email: "test2@gitea.com"}} msgs, err := composeIssueCommentMessages(&mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, Content: "test body"}, "en-US", recipients, false, "issue create") msgs, err := composeIssueCommentMessages(&mailCommentContext{ Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, Content: "test body", }, "en-US", recipients, false, "issue create") assert.NoError(t, err) assert.Len(t, msgs, 2)
-
@@ -138,22 +142,30 @@ func TestTemplateSelection(t *testing.T) {assert.Contains(t, wholemsg, expBody) } msg := testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, Content: "test body"}, recipients, false, "TestTemplateSelection") msg := testComposeIssueCommentMessage(t, &mailCommentContext{ Issue: issue, Doer: doer, ActionType: models.ActionCreateIssue, Content: "test body", }, recipients, false, "TestTemplateSelection") expect(t, msg, "issue/new/subject", "issue/new/body") msg = testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, Content: "test body", Comment: comment}, recipients, false, "TestTemplateSelection") msg = testComposeIssueCommentMessage(t, &mailCommentContext{ Issue: issue, Doer: doer, ActionType: models.ActionCommentIssue, Content: "test body", Comment: comment, }, recipients, false, "TestTemplateSelection") expect(t, msg, "issue/default/subject", "issue/default/body") pull := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2, Repo: repo, Poster: doer}).(*models.Issue) comment = unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: 4, Issue: pull}).(*models.Comment) msg = testComposeIssueCommentMessage(t, &mailCommentContext{Issue: pull, Doer: doer, ActionType: models.ActionCommentPull, Content: "test body", Comment: comment}, recipients, false, "TestTemplateSelection") msg = testComposeIssueCommentMessage(t, &mailCommentContext{ Issue: pull, Doer: doer, ActionType: models.ActionCommentPull, Content: "test body", Comment: comment, }, recipients, false, "TestTemplateSelection") expect(t, msg, "pull/comment/subject", "pull/comment/body") msg = testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: models.ActionCloseIssue, Content: "test body", Comment: comment}, recipients, false, "TestTemplateSelection") msg = testComposeIssueCommentMessage(t, &mailCommentContext{ Issue: issue, Doer: doer, ActionType: models.ActionCloseIssue, Content: "test body", Comment: comment, }, recipients, false, "TestTemplateSelection") expect(t, msg, "Re: [user2/repo1] issue1 (#1)", "issue/close/body") }
-
@@ -162,15 +174,17 @@ func TestTemplateServices(t *testing.T) {assert.NoError(t, issue.LoadRepo()) expect := func(t *testing.T, issue *models.Issue, comment *models.Comment, doer *user_model.User, actionType models.ActionType, fromMention bool, tplSubject, tplBody, expSubject, expBody string) { actionType models.ActionType, fromMention bool, tplSubject, tplBody, expSubject, expBody string, ) { stpl := texttmpl.Must(texttmpl.New("issue/default").Parse(tplSubject)) btpl := template.Must(template.New("issue/default").Parse(tplBody)) InitMailRender(stpl, btpl) recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}} msg := testComposeIssueCommentMessage(t, &mailCommentContext{Issue: issue, Doer: doer, ActionType: actionType, Content: "test body", Comment: comment}, recipients, fromMention, "TestTemplateServices") msg := testComposeIssueCommentMessage(t, &mailCommentContext{ Issue: issue, Doer: doer, ActionType: actionType, Content: "test body", Comment: comment, }, recipients, fromMention, "TestTemplateServices") subject := msg.ToMessage().GetHeader("Subject") msgbuf := new(bytes.Buffer)
-
-
-
@@ -141,8 +141,7 @@ func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {} // Sender SMTP mail sender type smtpSender struct { } type smtpSender struct{} // Send send email func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
-
@@ -254,8 +253,7 @@ func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error {} // Sender sendmail mail sender type sendmailSender struct { } type sendmailSender struct{} // Send send email func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {
-
@@ -280,7 +278,6 @@ func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {cmd := exec.CommandContext(ctx, setting.MailService.SendmailPath, args...) pipe, err := cmd.StdinPipe() if err != nil { return err }
-
@@ -314,8 +311,7 @@ func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {} // Sender sendmail mail sender type dummySender struct { } type dummySender struct{} // Send send email func (s *dummySender) Send(from string, to []string, msg io.WriterTo) error {
-
-
-
@@ -30,8 +30,7 @@ func init() {} // CodebaseDownloaderFactory defines a downloader factory type CodebaseDownloaderFactory struct { } type CodebaseDownloaderFactory struct{} // New returns a downloader related to this factory according MigrateOptions func (f *CodebaseDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
-
@@ -88,7 +87,7 @@ func (d *CodebaseDownloader) SetContext(ctx context.Context) {func NewCodebaseDownloader(ctx context.Context, projectURL *url.URL, project, repoName, username, password string) *CodebaseDownloader { baseURL, _ := url.Parse("https://api3.codebasehq.com") var downloader = &CodebaseDownloader{ downloader := &CodebaseDownloader{ ctx: ctx, baseURL: baseURL, projectURL: projectURL,
-
@@ -206,7 +205,7 @@ func (d *CodebaseDownloader) GetMilestones() ([]*base.Milestone, error) {return nil, err } var milestones = make([]*base.Milestone, 0, len(rawMilestones.TicketingMilestone)) milestones := make([]*base.Milestone, 0, len(rawMilestones.TicketingMilestone)) for _, milestone := range rawMilestones.TicketingMilestone { var deadline *time.Time if len(milestone.Deadline.Value) > 0 {
-
@@ -256,7 +255,7 @@ func (d *CodebaseDownloader) GetLabels() ([]*base.Label, error) {return nil, err } var labels = make([]*base.Label, 0, len(rawTypes.TicketingType)) labels := make([]*base.Label, 0, len(rawTypes.TicketingType)) for _, label := range rawTypes.TicketingType { labels = append(labels, &base.Label{ Name: label.Name,
-
@@ -400,7 +399,8 @@ func (d *CodebaseDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool,Created: issue.CreatedAt.Value, Updated: issue.UpdatedAt.Value, Labels: []*base.Label{ {Name: issue.Type.Name}}, {Name: issue.Type.Name}, }, Context: codebaseIssueContext{ foreignID: issue.TicketID.Value, localID: issue.TicketID.Value,
-
-
-
@@ -27,9 +27,7 @@ import ("gopkg.in/yaml.v2" ) var ( _ base.Uploader = &RepositoryDumper{} ) var _ base.Uploader = &RepositoryDumper{} // RepositoryDumper implements an Uploader to the local directory type RepositoryDumper struct {
-
@@ -403,7 +401,7 @@ func (g *RepositoryDumper) createItems(dir string, itemFiles map[int64]*os.File,// CreateComments creates comments of issues func (g *RepositoryDumper) CreateComments(comments ...*base.Comment) error { var commentsMap = make(map[int64][]interface{}, len(comments)) commentsMap := make(map[int64][]interface{}, len(comments)) for _, comment := range comments { commentsMap[comment.IssueIndex] = append(commentsMap[comment.IssueIndex], comment) }
-
@@ -532,7 +530,7 @@ func (g *RepositoryDumper) CreatePullRequests(prs ...*base.PullRequest) error {// CreateReviews create pull request reviews func (g *RepositoryDumper) CreateReviews(reviews ...*base.Review) error { var reviewsMap = make(map[int64][]interface{}, len(reviews)) reviewsMap := make(map[int64][]interface{}, len(reviews)) for _, review := range reviews { reviewsMap[review.IssueIndex] = append(reviewsMap[review.IssueIndex], review) }
-
@@ -611,7 +609,7 @@ func RestoreRepository(ctx context.Context, baseDir, ownerName, repoName string,if err != nil { return err } var uploader = NewGiteaLocalUploader(ctx, doer, ownerName, repoName) uploader := NewGiteaLocalUploader(ctx, doer, ownerName, repoName) downloader, err := NewRepositoryRestorer(ctx, baseDir, ownerName, repoName) if err != nil { return err
-
@@ -622,7 +620,7 @@ func RestoreRepository(ctx context.Context, baseDir, ownerName, repoName string,} tp, _ := strconv.Atoi(opts["service_type"]) var migrateOpts = base.MigrateOptions{ migrateOpts := base.MigrateOptions{ GitServiceType: structs.GitServiceType(tp), } updateOptionsUnits(&migrateOpts, units)
-
-
-
@@ -11,10 +11,8 @@ import ("github.com/google/go-github/v39/github" ) var ( // ErrRepoNotCreated returns the error that repository not created ErrRepoNotCreated = errors.New("repository is not created yet") ) // ErrRepoNotCreated returns the error that repository not created var ErrRepoNotCreated = errors.New("repository is not created yet") // IsRateLimitError returns true if the err is github.RateLimitError func IsRateLimitError(err error) bool {
-
-
-
@@ -10,9 +10,7 @@ import (base "code.gitea.io/gitea/modules/migration" ) var ( _ base.Downloader = &PlainGitDownloader{} ) var _ base.Downloader = &PlainGitDownloader{} // PlainGitDownloader implements a Downloader interface to clone git from a http/https URL type PlainGitDownloader struct {
-
-
-
@@ -23,8 +23,7 @@ func init() {} // GitBucketDownloaderFactory defines a GitBucket downloader factory type GitBucketDownloaderFactory struct { } type GitBucketDownloaderFactory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GitBucketDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
-
-
-
@@ -32,8 +32,7 @@ func init() {} // GiteaDownloaderFactory defines a gitea downloader factory type GiteaDownloaderFactory struct { } type GiteaDownloaderFactory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GiteaDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
-
@@ -159,7 +158,7 @@ func (g *GiteaDownloader) GetTopics() ([]string, error) {// GetMilestones returns milestones func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { var milestones = make([]*base.Milestone, 0, g.maxPerPage) milestones := make([]*base.Milestone, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully
-
@@ -224,7 +223,7 @@ func (g *GiteaDownloader) convertGiteaLabel(label *gitea_sdk.Label) *base.Label// GetLabels returns labels func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { var labels = make([]*base.Label, 0, g.maxPerPage) labels := make([]*base.Label, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully
-
@@ -304,7 +303,7 @@ func (g *GiteaDownloader) convertGiteaRelease(rel *gitea_sdk.Release) *base.Rele// GetReleases returns releases func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { var releases = make([]*base.Release, 0, g.maxPerPage) releases := make([]*base.Release, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully
-
@@ -379,7 +378,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, errif perPage > g.maxPerPage { perPage = g.maxPerPage } var allIssues = make([]*base.Issue, 0, perPage) allIssues := make([]*base.Issue, 0, perPage) issues, _, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gitea_sdk.ListIssueOption{ ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: perPage},
-
@@ -391,7 +390,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err} for _, issue := range issues { var labels = make([]*base.Label, 0, len(issue.Labels)) labels := make([]*base.Label, 0, len(issue.Labels)) for i := range issue.Labels { labels = append(labels, g.convertGiteaLabel(issue.Labels[i])) }
-
@@ -444,7 +443,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err// GetComments returns comments according issueNumber func (g *GiteaDownloader) GetComments(opts base.GetCommentOptions) ([]*base.Comment, bool, error) { var allComments = make([]*base.Comment, 0, g.maxPerPage) allComments := make([]*base.Comment, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully
-
@@ -496,7 +495,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequesif perPage > g.maxPerPage { perPage = g.maxPerPage } var allPRs = make([]*base.PullRequest, 0, perPage) allPRs := make([]*base.PullRequest, 0, perPage) prs, _, err := g.client.ListRepoPullRequests(g.repoOwner, g.repoName, gitea_sdk.ListPullRequestsOptions{ ListOptions: gitea_sdk.ListOptions{
-
@@ -514,7 +513,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequesmilestone = pr.Milestone.Title } var labels = make([]*base.Label, 0, len(pr.Labels)) labels := make([]*base.Label, 0, len(pr.Labels)) for i := range pr.Labels { labels = append(labels, g.convertGiteaLabel(pr.Labels[i])) }
-
@@ -620,7 +619,7 @@ func (g *GiteaDownloader) GetReviews(context base.IssueContext) ([]*base.Review,return nil, nil } var allReviews = make([]*base.Review, 0, g.maxPerPage) allReviews := make([]*base.Review, 0, g.maxPerPage) for i := 1; ; i++ { // make sure gitea can shutdown gracefully
-
-
-
@@ -33,9 +33,7 @@ import (gouuid "github.com/google/uuid" ) var ( _ base.Uploader = &GiteaLocalUploader{} ) var _ base.Uploader = &GiteaLocalUploader{} // GiteaLocalUploader implements an Uploader to gitea sites type GiteaLocalUploader struct {
-
@@ -159,7 +157,7 @@ func (g *GiteaLocalUploader) CreateTopics(topics ...string) error {// CreateMilestones creates milestones func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) error { var mss = make([]*models.Milestone, 0, len(milestones)) mss := make([]*models.Milestone, 0, len(milestones)) for _, milestone := range milestones { var deadline timeutil.TimeStamp if milestone.Deadline != nil {
-
@@ -182,7 +180,7 @@ func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) errmilestone.Updated = &milestone.Created } var ms = models.Milestone{ ms := models.Milestone{ RepoID: g.repo.ID, Name: milestone.Title, Content: milestone.Description,
-
@@ -210,7 +208,7 @@ func (g *GiteaLocalUploader) CreateMilestones(milestones ...*base.Milestone) err// CreateLabels creates labels func (g *GiteaLocalUploader) CreateLabels(labels ...*base.Label) error { var lbs = make([]*models.Label, 0, len(labels)) lbs := make([]*models.Label, 0, len(labels)) for _, label := range labels { lbs = append(lbs, &models.Label{ RepoID: g.repo.ID,
-
@@ -232,7 +230,7 @@ func (g *GiteaLocalUploader) CreateLabels(labels ...*base.Label) error {// CreateReleases creates releases func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error { var rels = make([]*models.Release, 0, len(releases)) rels := make([]*models.Release, 0, len(releases)) for _, release := range releases { if release.Created.IsZero() { if !release.Published.IsZero() {
-
@@ -242,7 +240,7 @@ func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error {} } var rel = models.Release{ rel := models.Release{ RepoID: g.repo.ID, TagName: release.TagName, LowerTagName: strings.ToLower(release.TagName),
-
@@ -297,7 +295,7 @@ func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error {asset.Created = release.Created } } var attach = repo_model.Attachment{ attach := repo_model.Attachment{ UUID: gouuid.New().String(), Name: asset.Name, DownloadCount: int64(*asset.DownloadCount),
-
@@ -348,7 +346,7 @@ func (g *GiteaLocalUploader) SyncTags() error {// CreateIssues creates issues func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error { var iss = make([]*models.Issue, 0, len(issues)) iss := make([]*models.Issue, 0, len(issues)) for _, issue := range issues { var labels []*models.Label for _, label := range issue.Labels {
-
@@ -381,7 +379,7 @@ func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error {} } var is = models.Issue{ is := models.Issue{ RepoID: g.repo.ID, Repo: g.repo, Index: issue.Number,
-
@@ -433,7 +431,7 @@ func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error {g.userMap[reaction.UserID] = userid } } var res = models.Reaction{ res := models.Reaction{ Type: reaction.Content, CreatedUnix: timeutil.TimeStampNow(), }
-
@@ -464,7 +462,7 @@ func (g *GiteaLocalUploader) CreateIssues(issues ...*base.Issue) error {// CreateComments creates comments of issues func (g *GiteaLocalUploader) CreateComments(comments ...*base.Comment) error { var cms = make([]*models.Comment, 0, len(comments)) cms := make([]*models.Comment, 0, len(comments)) for _, comment := range comments { var issue *models.Issue issueInter, ok := g.issues.Load(comment.IssueIndex)
-
@@ -528,7 +526,7 @@ func (g *GiteaLocalUploader) CreateComments(comments ...*base.Comment) error {g.userMap[reaction.UserID] = userid } } var res = models.Reaction{ res := models.Reaction{ Type: reaction.Content, CreatedUnix: timeutil.TimeStampNow(), }
-
@@ -553,7 +551,7 @@ func (g *GiteaLocalUploader) CreateComments(comments ...*base.Comment) error {// CreatePullRequests creates pull requests func (g *GiteaLocalUploader) CreatePullRequests(prs ...*base.PullRequest) error { var gprs = make([]*models.PullRequest, 0, len(prs)) gprs := make([]*models.PullRequest, 0, len(prs)) for _, pr := range prs { gpr, err := g.newPullRequest(pr) if err != nil {
-
@@ -652,7 +650,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullRreturn nil, err } var head = "unknown repository" head := "unknown repository" if pr.IsForkPullRequest() && pr.State != "closed" { if pr.Head.OwnerName != "" { remote := pr.Head.OwnerName
-
@@ -723,7 +721,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullRpr.Updated = pr.Created } var issue = models.Issue{ issue := models.Issue{ RepoID: g.repo.ID, Repo: g.repo, Title: pr.Title,
-
@@ -773,7 +771,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullRg.userMap[reaction.UserID] = userid } } var res = models.Reaction{ res := models.Reaction{ Type: reaction.Content, CreatedUnix: timeutil.TimeStampNow(), }
-
@@ -787,7 +785,7 @@ func (g *GiteaLocalUploader) newPullRequest(pr *base.PullRequest) (*models.PullRissue.Reactions = append(issue.Reactions, &res) } var pullRequest = models.PullRequest{ pullRequest := models.PullRequest{ HeadRepoID: g.repo.ID, HeadBranch: head, BaseRepoID: g.repo.ID,
-
@@ -830,7 +828,7 @@ func convertReviewState(state string) models.ReviewType {// CreateReviews create pull request reviews func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error { var cms = make([]*models.Review, 0, len(reviews)) cms := make([]*models.Review, 0, len(reviews)) for _, review := range reviews { var issue *models.Issue issueInter, ok := g.issues.Load(review.IssueIndex)
-
@@ -862,7 +860,7 @@ func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error {review.CreatedAt = time.Unix(int64(issue.CreatedUnix), 0) } var cm = models.Review{ cm := models.Review{ Type: convertReviewState(review.State), IssueID: issue.ID, Content: review.Content,
-
@@ -926,7 +924,7 @@ func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error {comment.UpdatedAt = comment.CreatedAt } var c = models.Comment{ c := models.Comment{ Type: models.CommentTypeCode, PosterID: comment.PosterID, IssueID: issue.ID,
-
-
-
@@ -37,8 +37,7 @@ func init() {} // GithubDownloaderV3Factory defines a github downloader v3 factory type GithubDownloaderV3Factory struct { } type GithubDownloaderV3Factory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GithubDownloaderV3Factory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
-
@@ -80,7 +79,7 @@ type GithubDownloaderV3 struct {// NewGithubDownloaderV3 creates a github Downloader via github v3 API func NewGithubDownloaderV3(ctx context.Context, baseURL, userName, password, token, repoOwner, repoName string) *GithubDownloaderV3 { var downloader = GithubDownloaderV3{ downloader := GithubDownloaderV3{ userName: userName, password: password, ctx: ctx,
-
@@ -96,7 +95,7 @@ func NewGithubDownloaderV3(ctx context.Context, baseURL, userName, password, tokts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) var client = &http.Client{ client := &http.Client{ Transport: &oauth2.Transport{ Base: NewMigrationHTTPTransport(), Source: oauth2.ReuseTokenSource(nil, ts),
-
@@ -106,12 +105,12 @@ func NewGithubDownloaderV3(ctx context.Context, baseURL, userName, password, tokdownloader.addClient(client, baseURL) } } else { var transport = NewMigrationHTTPTransport() transport := NewMigrationHTTPTransport() transport.Proxy = func(req *http.Request) (*url.URL, error) { req.SetBasicAuth(userName, password) return proxy.Proxy()(req) } var client = &http.Client{ client := &http.Client{ Transport: transport, } downloader.addClient(client, baseURL)
-
@@ -218,8 +217,8 @@ func (g *GithubDownloaderV3) GetTopics() ([]string, error) {// GetMilestones returns milestones func (g *GithubDownloaderV3) GetMilestones() ([]*base.Milestone, error) { var perPage = g.maxPerPage var milestones = make([]*base.Milestone, 0, perPage) perPage := g.maxPerPage milestones := make([]*base.Milestone, 0, perPage) for i := 1; ; i++ { g.waitAndPickClient() ms, resp, err := g.getClient().Issues.ListMilestones(g.ctx, g.repoOwner, g.repoName,
-
@@ -228,14 +227,15 @@ func (g *GithubDownloaderV3) GetMilestones() ([]*base.Milestone, error) {ListOptions: github.ListOptions{ Page: i, PerPage: perPage, }}) }, }) if err != nil { return nil, err } g.setRate(&resp.Rate) for _, m := range ms { var state = "open" state := "open" if m.State != nil { state = *m.State }
-
@@ -266,8 +266,8 @@ func convertGithubLabel(label *github.Label) *base.Label {// GetLabels returns labels func (g *GithubDownloaderV3) GetLabels() ([]*base.Label, error) { var perPage = g.maxPerPage var labels = make([]*base.Label, 0, perPage) perPage := g.maxPerPage labels := make([]*base.Label, 0, perPage) for i := 1; ; i++ { g.waitAndPickClient() ls, resp, err := g.getClient().Issues.ListLabels(g.ctx, g.repoOwner, g.repoName,
-
@@ -311,7 +311,7 @@ func (g *GithubDownloaderV3) convertGithubRelease(rel *github.RepositoryRelease)httpClient := NewMigrationHTTPClient() for _, asset := range rel.Assets { var assetID = *asset.ID // Don't optimize this, for closure we need a local variable assetID := *asset.ID // Don't optimize this, for closure we need a local variable r.Assets = append(r.Assets, &base.ReleaseAsset{ ID: asset.GetID(), Name: asset.GetName(),
-
@@ -357,8 +357,8 @@ func (g *GithubDownloaderV3) convertGithubRelease(rel *github.RepositoryRelease)// GetReleases returns releases func (g *GithubDownloaderV3) GetReleases() ([]*base.Release, error) { var perPage = g.maxPerPage var releases = make([]*base.Release, 0, perPage) perPage := g.maxPerPage releases := make([]*base.Release, 0, perPage) for i := 1; ; i++ { g.waitAndPickClient() ls, resp, err := g.getClient().Repositories.ListReleases(g.ctx, g.repoOwner, g.repoName,
-
@@ -396,7 +396,7 @@ func (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool,}, } var allIssues = make([]*base.Issue, 0, perPage) allIssues := make([]*base.Issue, 0, perPage) g.waitAndPickClient() issues, resp, err := g.getClient().Issues.ListByRepo(g.ctx, g.repoOwner, g.repoName, opt) if err != nil {
-
@@ -409,7 +409,7 @@ func (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool,continue } var labels = make([]*base.Label, 0, len(issue.Labels)) labels := make([]*base.Label, 0, len(issue.Labels)) for _, l := range issue.Labels { labels = append(labels, convertGithubLabel(l)) }
-
@@ -573,7 +573,7 @@ func (g *GithubDownloaderV3) GetAllComments(page, perPage int) ([]*base.Comment,if err != nil { return nil, false, fmt.Errorf("error while listing repos: %v", err) } var isEnd = resp.NextPage == 0 isEnd := resp.NextPage == 0 log.Trace("Request get comments %d/%d, but in fact get %d, next page is %d", perPage, page, len(comments), resp.NextPage) g.setRate(&resp.Rate)
-
@@ -634,7 +634,7 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReqPage: page, }, } var allPRs = make([]*base.PullRequest, 0, perPage) allPRs := make([]*base.PullRequest, 0, perPage) g.waitAndPickClient() prs, resp, err := g.getClient().PullRequests.List(g.ctx, g.repoOwner, g.repoName, opt) if err != nil {
-
@@ -643,7 +643,7 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReqlog.Trace("Request get pull requests %d/%d, but in fact get %d", perPage, page, len(prs)) g.setRate(&resp.Rate) for _, pr := range prs { var labels = make([]*base.Label, 0, len(pr.Labels)) labels := make([]*base.Label, 0, len(pr.Labels)) for _, l := range pr.Labels { labels = append(labels, convertGithubLabel(l)) }
-
@@ -729,7 +729,7 @@ func convertGithubReview(r *github.PullRequestReview) *base.Review {} func (g *GithubDownloaderV3) convertGithubReviewComments(cs []*github.PullRequestComment) ([]*base.ReviewComment, error) { var rcs = make([]*base.ReviewComment, 0, len(cs)) rcs := make([]*base.ReviewComment, 0, len(cs)) for _, c := range cs { // get reactions var reactions []*base.Reaction
-
@@ -776,7 +776,7 @@ func (g *GithubDownloaderV3) convertGithubReviewComments(cs []*github.PullReques// GetReviews returns pull requests review func (g *GithubDownloaderV3) GetReviews(context base.IssueContext) ([]*base.Review, error) { var allReviews = make([]*base.Review, 0, g.maxPerPage) allReviews := make([]*base.Review, 0, g.maxPerPage) opt := &github.ListOptions{ PerPage: g.maxPerPage, }
-
-
-
@@ -32,8 +32,7 @@ func init() {} // GitlabDownloaderFactory defines a gitlab downloader factory type GitlabDownloaderFactory struct { } type GitlabDownloaderFactory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GitlabDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
-
@@ -184,16 +183,17 @@ func (g *GitlabDownloader) GetTopics() ([]string, error) {// GetMilestones returns milestones func (g *GitlabDownloader) GetMilestones() ([]*base.Milestone, error) { var perPage = g.maxPerPage var state = "all" var milestones = make([]*base.Milestone, 0, perPage) perPage := g.maxPerPage state := "all" milestones := make([]*base.Milestone, 0, perPage) for i := 1; ; i++ { ms, _, err := g.client.Milestones.ListMilestones(g.repoID, &gitlab.ListMilestonesOptions{ State: &state, ListOptions: gitlab.ListOptions{ Page: i, PerPage: perPage, }}, nil, gitlab.WithContext(g.ctx)) }, }, nil, gitlab.WithContext(g.ctx)) if err != nil { return nil, err }
-
@@ -203,7 +203,7 @@ func (g *GitlabDownloader) GetMilestones() ([]*base.Milestone, error) {if m.Description != "" { desc = m.Description } var state = "open" state := "open" var closedAt *time.Time if m.State != "" { state = m.State
-
@@ -255,8 +255,8 @@ func (g *GitlabDownloader) normalizeColor(val string) string {// GetLabels returns labels func (g *GitlabDownloader) GetLabels() ([]*base.Label, error) { var perPage = g.maxPerPage var labels = make([]*base.Label, 0, perPage) perPage := g.maxPerPage labels := make([]*base.Label, 0, perPage) for i := 1; ; i++ { ls, _, err := g.client.Labels.ListLabels(g.repoID, &gitlab.ListLabelsOptions{ListOptions: gitlab.ListOptions{ Page: i,
-
@@ -327,8 +327,8 @@ func (g *GitlabDownloader) convertGitlabRelease(rel *gitlab.Release) *base.Relea// GetReleases returns releases func (g *GitlabDownloader) GetReleases() ([]*base.Release, error) { var perPage = g.maxPerPage var releases = make([]*base.Release, 0, perPage) perPage := g.maxPerPage releases := make([]*base.Release, 0, perPage) for i := 1; ; i++ { ls, _, err := g.client.Releases.ListReleases(g.repoID, &gitlab.ListReleasesOptions{ Page: i,
-
@@ -381,7 +381,7 @@ func (g *GitlabDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, er}, } var allIssues = make([]*base.Issue, 0, perPage) allIssues := make([]*base.Issue, 0, perPage) issues, _, err := g.client.Issues.ListProjectIssues(g.repoID, opt, nil, gitlab.WithContext(g.ctx)) if err != nil {
-
@@ -389,7 +389,7 @@ func (g *GitlabDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, er} for _, issue := range issues { var labels = make([]*base.Label, 0, len(issue.Labels)) labels := make([]*base.Label, 0, len(issue.Labels)) for _, l := range issue.Labels { labels = append(labels, &base.Label{ Name: l,
-
@@ -402,7 +402,7 @@ func (g *GitlabDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, er} var reactions []*base.Reaction var awardPage = 1 awardPage := 1 for { awards, _, err := g.client.AwardEmoji.ListIssueAwardEmoji(g.repoID, issue.IID, &gitlab.ListAwardEmojiOptions{Page: awardPage, PerPage: perPage}, gitlab.WithContext(g.ctx)) if err != nil {
-
@@ -456,9 +456,9 @@ func (g *GitlabDownloader) GetComments(opts base.GetCommentOptions) ([]*base.Comreturn nil, false, fmt.Errorf("unexpected context: %+v", opts.Context) } var allComments = make([]*base.Comment, 0, g.maxPerPage) allComments := make([]*base.Comment, 0, g.maxPerPage) var page = 1 page := 1 for { var comments []*gitlab.Discussion
-
@@ -503,7 +503,6 @@ func (g *GitlabDownloader) GetComments(opts base.GetCommentOptions) ([]*base.ComCreated: *c.CreatedAt, }) } } if resp.NextPage == 0 { break
-
@@ -526,7 +525,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque}, } var allPRs = make([]*base.PullRequest, 0, perPage) allPRs := make([]*base.PullRequest, 0, perPage) prs, _, err := g.client.MergeRequests.ListProjectMergeRequests(g.repoID, opt, nil, gitlab.WithContext(g.ctx)) if err != nil {
-
@@ -534,7 +533,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque} for _, pr := range prs { var labels = make([]*base.Label, 0, len(pr.Labels)) labels := make([]*base.Label, 0, len(pr.Labels)) for _, l := range pr.Labels { labels = append(labels, &base.Label{ Name: l,
-
@@ -547,12 +546,12 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequepr.State = "closed" } var mergeTime = pr.MergedAt mergeTime := pr.MergedAt if merged && pr.MergedAt == nil { mergeTime = pr.UpdatedAt } var closeTime = pr.ClosedAt closeTime := pr.ClosedAt if merged && pr.ClosedAt == nil { closeTime = pr.UpdatedAt }
-
@@ -568,7 +567,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque} var reactions []*base.Reaction var awardPage = 1 awardPage := 1 for { awards, _, err := g.client.AwardEmoji.ListMergeRequestAwardEmoji(g.repoID, pr.IID, &gitlab.ListAwardEmojiOptions{Page: awardPage, PerPage: perPage}, gitlab.WithContext(g.ctx)) if err != nil {
-
@@ -641,7 +640,7 @@ func (g *GitlabDownloader) GetReviews(context base.IssueContext) ([]*base.Reviewreturn nil, err } var reviews = make([]*base.Review, 0, len(approvals.ApprovedBy)) reviews := make([]*base.Review, 0, len(approvals.ApprovedBy)) for _, user := range approvals.ApprovedBy { reviews = append(reviews, &base.Review{ IssueIndex: context.LocalID(),
-
-
-
@@ -30,8 +30,7 @@ func init() {} // GogsDownloaderFactory defines a gogs downloader factory type GogsDownloaderFactory struct { } type GogsDownloaderFactory struct{} // New returns a Downloader related to this factory according MigrateOptions func (f *GogsDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
-
@@ -81,7 +80,7 @@ func (g *GogsDownloader) SetContext(ctx context.Context) {// NewGogsDownloader creates a gogs Downloader via gogs API func NewGogsDownloader(ctx context.Context, baseURL, userName, password, token, repoOwner, repoName string) *GogsDownloader { var downloader = GogsDownloader{ downloader := GogsDownloader{ ctx: ctx, baseURL: baseURL, userName: userName,
-
@@ -95,7 +94,7 @@ func NewGogsDownloader(ctx context.Context, baseURL, userName, password, token,client = gogs.NewClient(baseURL, token) downloader.userName = token } else { var transport = NewMigrationHTTPTransport() transport := NewMigrationHTTPTransport() transport.Proxy = func(req *http.Request) (*url.URL, error) { req.SetBasicAuth(userName, password) return proxy.Proxy()(req)
-
@@ -139,8 +138,8 @@ func (g *GogsDownloader) GetRepoInfo() (*base.Repository, error) {// GetMilestones returns milestones func (g *GogsDownloader) GetMilestones() ([]*base.Milestone, error) { var perPage = 100 var milestones = make([]*base.Milestone, 0, perPage) perPage := 100 milestones := make([]*base.Milestone, 0, perPage) ms, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName) if err != nil {
-
@@ -162,8 +161,8 @@ func (g *GogsDownloader) GetMilestones() ([]*base.Milestone, error) {// GetLabels returns labels func (g *GogsDownloader) GetLabels() ([]*base.Label, error) { var perPage = 100 var labels = make([]*base.Label, 0, perPage) perPage := 100 labels := make([]*base.Label, 0, perPage) ls, err := g.client.ListRepoLabels(g.repoOwner, g.repoName) if err != nil { return nil, err
-
@@ -203,7 +202,7 @@ func (g *GogsDownloader) GetIssues(page, _ int) ([]*base.Issue, bool, error) {} func (g *GogsDownloader) getIssues(page int, state string) ([]*base.Issue, bool, error) { var allIssues = make([]*base.Issue, 0, 10) allIssues := make([]*base.Issue, 0, 10) issues, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gogs.ListIssueOption{ Page: page,
-
@@ -225,7 +224,7 @@ func (g *GogsDownloader) getIssues(page int, state string) ([]*base.Issue, bool,// GetComments returns comments according issueNumber func (g *GogsDownloader) GetComments(opts base.GetCommentOptions) ([]*base.Comment, bool, error) { var allComments = make([]*base.Comment, 0, 100) allComments := make([]*base.Comment, 0, 100) comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, opts.Context.ForeignID()) if err != nil {
-
@@ -276,7 +275,7 @@ func convertGogsIssue(issue *gogs.Issue) *base.Issue {if issue.Milestone != nil { milestone = issue.Milestone.Title } var labels = make([]*base.Label, 0, len(issue.Labels)) labels := make([]*base.Label, 0, len(issue.Labels)) for _, l := range issue.Labels { labels = append(labels, convertGogsLabel(l)) }
-
-
-
@@ -123,7 +123,7 @@ func MigrateRepository(ctx context.Context, doer *user_model.User, ownerName strreturn nil, err } var uploader = NewGiteaLocalUploader(ctx, doer, ownerName, opts.RepoName) uploader := NewGiteaLocalUploader(ctx, doer, ownerName, opts.RepoName) uploader.gitServiceType = opts.GitServiceType if err := migrateRepository(downloader, uploader, opts, messenger); err != nil {
-
@@ -305,7 +305,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, optsif opts.Issues { log.Trace("migrating issues and comments") messenger("repo.migrate.migrating_issues") var issueBatchSize = uploader.MaxBatchInsertSize("issue") issueBatchSize := uploader.MaxBatchInsertSize("issue") for i := 1; ; i++ { issues, isEnd, err := downloader.GetIssues(i, issueBatchSize)
-
@@ -322,7 +322,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts} if opts.Comments && !supportAllComments { var allComments = make([]*base.Comment, 0, commentBatchSize) allComments := make([]*base.Comment, 0, commentBatchSize) for _, issue := range issues { log.Trace("migrating issue %d's comments", issue.Number) comments, _, err := downloader.GetComments(base.GetCommentOptions{
-
@@ -362,7 +362,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, optsif opts.PullRequests { log.Trace("migrating pull requests and comments") messenger("repo.migrate.migrating_pulls") var prBatchSize = uploader.MaxBatchInsertSize("pullrequest") prBatchSize := uploader.MaxBatchInsertSize("pullrequest") for i := 1; ; i++ { prs, isEnd, err := downloader.GetPullRequests(i, prBatchSize) if err != nil {
-
@@ -380,7 +380,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, optsif opts.Comments { if !supportAllComments { // plain comments var allComments = make([]*base.Comment, 0, commentBatchSize) allComments := make([]*base.Comment, 0, commentBatchSize) for _, pr := range prs { log.Trace("migrating pull request %d's comments", pr.Number) comments, _, err := downloader.GetComments(base.GetCommentOptions{
-
@@ -410,7 +410,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts} // migrate reviews var allReviews = make([]*base.Review, 0, reviewBatchSize) allReviews := make([]*base.Review, 0, reviewBatchSize) for _, pr := range prs { reviews, err := downloader.GetReviews(pr.Context) if err != nil {
-
-
-
@@ -29,8 +29,7 @@ func init() {} // OneDevDownloaderFactory defines a downloader factory type OneDevDownloaderFactory struct { } type OneDevDownloaderFactory struct{} // New returns a downloader related to this factory according MigrateOptions func (f *OneDevDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
-
@@ -90,7 +89,7 @@ func (d *OneDevDownloader) SetContext(ctx context.Context) {// NewOneDevDownloader creates a new downloader func NewOneDevDownloader(ctx context.Context, baseURL *url.URL, username, password, repoName string) *OneDevDownloader { var downloader = &OneDevDownloader{ downloader := &OneDevDownloader{ ctx: ctx, baseURL: baseURL, repoName: repoName,
-
@@ -195,7 +194,7 @@ func (d *OneDevDownloader) GetMilestones() ([]*base.Milestone, error) {endpoint := fmt.Sprintf("/api/projects/%d/milestones", d.repoID) var milestones = make([]*base.Milestone, 0, 100) milestones := make([]*base.Milestone, 0, 100) offset := 0 for { err := d.callAPI(
-
@@ -583,7 +582,7 @@ func (d *OneDevDownloader) GetReviews(context base.IssueContext) ([]*base.Reviewreturn nil, err } var reviews = make([]*base.Review, 0, len(rawReviews)) reviews := make([]*base.Review, 0, len(rawReviews)) for _, review := range rawReviews { state := base.ReviewStatePending content := ""
-
-
-
@@ -59,7 +59,7 @@ func (r *RepositoryRestorer) getRepoOptions() (map[string]string, error) {return nil, err } var opts = make(map[string]string) opts := make(map[string]string) err = yaml.Unmarshal(bs, &opts) if err != nil { return nil, err
-
@@ -91,7 +91,7 @@ func (r *RepositoryRestorer) GetRepoInfo() (*base.Repository, error) {func (r *RepositoryRestorer) GetTopics() ([]string, error) { p := filepath.Join(r.baseDir, "topic.yml") var topics = struct { topics := struct { Topics []string `yaml:"topics"` }{}
-
@@ -109,7 +109,7 @@ func (r *RepositoryRestorer) GetTopics() ([]string, error) {// GetMilestones returns milestones func (r *RepositoryRestorer) GetMilestones() ([]*base.Milestone, error) { var milestones = make([]*base.Milestone, 0, 10) milestones := make([]*base.Milestone, 0, 10) p := filepath.Join(r.baseDir, "milestone.yml") _, err := os.Stat(p) if err != nil {
-
@@ -133,7 +133,7 @@ func (r *RepositoryRestorer) GetMilestones() ([]*base.Milestone, error) {// GetReleases returns releases func (r *RepositoryRestorer) GetReleases() ([]*base.Release, error) { var releases = make([]*base.Release, 0, 10) releases := make([]*base.Release, 0, 10) p := filepath.Join(r.baseDir, "release.yml") _, err := os.Stat(p) if err != nil {
-
@@ -164,7 +164,7 @@ func (r *RepositoryRestorer) GetReleases() ([]*base.Release, error) {// GetLabels returns labels func (r *RepositoryRestorer) GetLabels() ([]*base.Label, error) { var labels = make([]*base.Label, 0, 10) labels := make([]*base.Label, 0, 10) p := filepath.Join(r.baseDir, "label.yml") _, err := os.Stat(p) if err != nil {
-
@@ -188,7 +188,7 @@ func (r *RepositoryRestorer) GetLabels() ([]*base.Label, error) {// GetIssues returns issues according start and limit func (r *RepositoryRestorer) GetIssues(page, perPage int) ([]*base.Issue, bool, error) { var issues = make([]*base.Issue, 0, 10) issues := make([]*base.Issue, 0, 10) p := filepath.Join(r.baseDir, "issue.yml") _, err := os.Stat(p) if err != nil {
-
@@ -215,7 +215,7 @@ func (r *RepositoryRestorer) GetIssues(page, perPage int) ([]*base.Issue, bool,// GetComments returns comments according issueNumber func (r *RepositoryRestorer) GetComments(opts base.GetCommentOptions) ([]*base.Comment, bool, error) { var comments = make([]*base.Comment, 0, 10) comments := make([]*base.Comment, 0, 10) p := filepath.Join(r.commentDir(), fmt.Sprintf("%d.yml", opts.Context.ForeignID())) _, err := os.Stat(p) if err != nil {
-
@@ -239,7 +239,7 @@ func (r *RepositoryRestorer) GetComments(opts base.GetCommentOptions) ([]*base.C// GetPullRequests returns pull requests according page and perPage func (r *RepositoryRestorer) GetPullRequests(page, perPage int) ([]*base.PullRequest, bool, error) { var pulls = make([]*base.PullRequest, 0, 10) pulls := make([]*base.PullRequest, 0, 10) p := filepath.Join(r.baseDir, "pull_request.yml") _, err := os.Stat(p) if err != nil {
-
@@ -267,7 +267,7 @@ func (r *RepositoryRestorer) GetPullRequests(page, perPage int) ([]*base.PullReq// GetReviews returns pull requests review func (r *RepositoryRestorer) GetReviews(context base.IssueContext) ([]*base.Review, error) { var reviews = make([]*base.Review, 0, 10) reviews := make([]*base.Review, 0, 10) p := filepath.Join(r.reviewDir(), fmt.Sprintf("%d.yml", context.ForeignID())) _, err := os.Stat(p) if err != nil {
-
-
-
@@ -150,8 +150,8 @@ func pruneBrokenReferences(ctx context.Context,timeout time.Duration, stdoutBuilder, stderrBuilder *strings.Builder, sanitizer *strings.Replacer, isWiki bool) error { isWiki bool, ) error { wiki := "" if isWiki { wiki = "Wiki "
-
-
-
@@ -26,7 +26,7 @@ func MergeRequiredContextsCommitStatus(commitStatuses []*models.CommitStatus, rereturn structs.CommitStatusSuccess } var returnedStatus = structs.CommitStatusSuccess returnedStatus := structs.CommitStatusSuccess for _, ctx := range requiredContexts { var targetStatus structs.CommitStatusState for _, commitStatus := range commitStatuses {
-
-
-
@@ -165,13 +165,13 @@ func rawMerge(ctx context.Context, pr *models.PullRequest, doer *user_model.User} infoPath := filepath.Join(tmpBasePath, ".git", "info") if err := os.MkdirAll(infoPath, 0700); err != nil { if err := os.MkdirAll(infoPath, 0o700); err != nil { log.Error("Unable to create .git/info in %s: %v", tmpBasePath, err) return "", fmt.Errorf("Unable to create .git/info in tmpBasePath: %v", err) } sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout") if err := os.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil { if err := os.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0o600); err != nil { log.Error("Unable to write .git/info/sparse-checkout file in %s: %v", tmpBasePath, err) return "", fmt.Errorf("Unable to write .git/info/sparse-checkout file in tmpBasePath: %v", err) }
-
-
-
@@ -24,7 +24,6 @@ import (// CreateCodeComment creates a comment on the code line func CreateCodeComment(ctx context.Context, doer *user_model.User, gitRepo *git.Repository, issue *models.Issue, line int64, content, treePath string, isReview bool, replyReviewID int64, latestCommitID string) (*models.Comment, error) { var ( existsReview bool err error
-
-
-
@@ -70,7 +70,7 @@ func createTemporaryRepo(ctx context.Context, pr *models.PullRequest) (string, e// Add head repo remote. addCacheRepo := func(staging, cache string) error { p := filepath.Join(staging, ".git", "objects", "info", "alternates") f, err := os.OpenFile(p, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) f, err := os.OpenFile(p, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err != nil { log.Error("Could not create .git/objects/info/alternates file in %s: %v", staging, err) return err
-
-
-
@@ -26,7 +26,7 @@ func Update(ctx context.Context, pull *models.PullRequest, doer *user_model.Userpr = pull style = repo_model.MergeStyleRebaseUpdate } else { //use merge functions but switch repo's and branch's // use merge functions but switch repo's and branch's pr = &models.PullRequest{ HeadRepoID: pull.BaseRepoID, BaseRepoID: pull.HeadRepoID,
-
-
-
@@ -210,7 +210,7 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *models.Rreturn fmt.Errorf("AddReleaseAttachments: %v", err) } var deletedUUIDsMap = make(map[string]bool) deletedUUIDsMap := make(map[string]bool) if len(delAttachmentUUIDs) > 0 { // Check attachments attachments, err := repo_model.GetAttachmentsByUUIDs(ctx, delAttachmentUUIDs)
-
@@ -230,7 +230,7 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *models.R} if len(editAttachments) > 0 { var updateAttachmentsList = make([]string, 0, len(editAttachments)) updateAttachmentsList := make([]string, 0, len(editAttachments)) for k := range editAttachments { updateAttachmentsList = append(updateAttachmentsList, k) }
-
-
-
@@ -112,7 +112,7 @@ func TestRelease_Create(t *testing.T) {}, strings.NewReader("testtest")) assert.NoError(t, err) var release = models.Release{ release := models.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID,
-
-
-
@@ -252,7 +252,8 @@ func checkUnadoptedRepositories(userName string, repoNamesToCheck []string, unadListOptions: db.ListOptions{ Page: 1, PageSize: len(repoNamesToCheck), }, LowerNames: repoNamesToCheck}) }, LowerNames: repoNamesToCheck, }) if err != nil { return err }
-
-
-
@@ -69,7 +69,7 @@ func TestListUnadoptedRepositories_ListOptions(t *testing.T) {username := "user2" unadoptedList := []string{path.Join(username, "unadopted1"), path.Join(username, "unadopted2")} for _, unadopted := range unadoptedList { _ = os.Mkdir(path.Join(setting.RepoRootPath, unadopted+".git"), 0755) _ = os.Mkdir(path.Join(setting.RepoRootPath, unadopted+".git"), 0o755) } opts := db.ListOptions{Page: 1, PageSize: 1}
-
-
-
@@ -172,7 +172,7 @@ func doArchive(r *ArchiveRequest) (*repo_model.RepoArchiver, error) {w.Close() rd.Close() }() var done = make(chan error) done := make(chan error) repo, err := repo_model.GetRepositoryByID(archiver.RepoID) if err != nil { return nil, fmt.Errorf("archiver.LoadRepo failed: %v", err)
-
-
-
@@ -128,6 +128,6 @@ func TestArchive_Basic(t *testing.T) {} func TestErrUnknownArchiveFormat(t *testing.T) { var err = ErrUnknownArchiveFormat{RequestFormat: "master"} err := ErrUnknownArchiveFormat{RequestFormat: "master"} assert.True(t, errors.Is(err, ErrUnknownArchiveFormat{})) }
-
-
-
@@ -312,7 +312,7 @@ func pushUpdateAddTags(ctx context.Context, repo *repo_model.Repository, gitReposig = commit.Committer } var author *user_model.User var createdAt = time.Unix(1, 0) createdAt := time.Unix(1, 0) if sig != nil { var ok bool
-
-
-
@@ -92,7 +92,7 @@ func CreateMigrateTask(doer, u *user_model.User, opts base.MigrateOptions) (*modreturn nil, err } var task = &models.Task{ task := &models.Task{ DoerID: doer.ID, OwnerID: u.ID, Type: structs.TaskTypeMigrateRepo,
-
-
-
@@ -64,7 +64,7 @@ func Deliver(t *webhook_model.HookTask) error {req.Header.Set("Content-Type", "application/json") case webhook_model.ContentTypeForm: var forms = url.Values{ forms := url.Values{ "payload": []string{t.PayloadContent}, }
-
@@ -255,7 +255,6 @@ func DeliverHooks(ctx context.Context) {} } } } var (
-
-
-
@@ -19,7 +19,7 @@ func TestWebhookProxy(t *testing.T) {setting.Webhook.ProxyURLFixed, _ = url.Parse(setting.Webhook.ProxyURL) setting.Webhook.ProxyHosts = []string{"*.discordapp.com", "discordapp.com"} var kases = map[string]string{ kases := map[string]string{ "https://discordapp.com/api/webhooks/xxxxxxxxx/xxxxxxxxxxxxxxxxxxx": "http://localhost:8080", "http://s.discordapp.com/assets/xxxxxx": "http://localhost:8080", "http://github.com/a/b": "",
-
-
-
@@ -23,9 +23,7 @@ type (DingtalkPayload dingtalk.Payload ) var ( _ PayloadConvertor = &DingtalkPayload{} ) var _ PayloadConvertor = &DingtalkPayload{} // JSONPayload Marshals the DingtalkPayload to json func (d *DingtalkPayload) JSONPayload() ([]byte, error) {
-
@@ -135,7 +133,6 @@ func (d *DingtalkPayload) Review(p *api.PullRequestPayload, event webhook_model.title = fmt.Sprintf("[%s] Pull request review %s : #%d %s", p.Repository.FullName, action, p.Index, p.PullRequest.Title) text = p.Review.Content } return createDingtalkPayload(title, title+"\r\n\r\n"+text, "view pull request", p.PullRequest.HTMLURL), nil
-
-
-
@@ -106,9 +106,7 @@ func (d *DiscordPayload) JSONPayload() ([]byte, error) {return data, nil } var ( _ PayloadConvertor = &DiscordPayload{} ) var _ PayloadConvertor = &DiscordPayload{} // Create implements PayloadConvertor Create method func (d *DiscordPayload) Create(p *api.CreatePayload) (api.Payloader, error) {
-
-
-
@@ -44,9 +44,7 @@ func (f *FeishuPayload) JSONPayload() ([]byte, error) {return data, nil } var ( _ PayloadConvertor = &FeishuPayload{} ) var _ PayloadConvertor = &FeishuPayload{} // Create implements PayloadConvertor Create method func (f *FeishuPayload) Create(p *api.CreatePayload) (api.Payloader, error) {
-
@@ -80,7 +78,7 @@ func (f *FeishuPayload) Push(p *api.PushPayload) (api.Payloader, error) {commitDesc string ) var text = fmt.Sprintf("[%s:%s] %s\r\n", p.Repo.FullName, branchName, commitDesc) text := fmt.Sprintf("[%s:%s] %s\r\n", p.Repo.FullName, branchName, commitDesc) // for each commit, generate attachment text for i, commit := range p.Commits { var authorName string
-
-
-
@@ -53,9 +53,7 @@ type MatrixPayloadUnsafe struct {AccessToken string `json:"access_token"` } var ( _ PayloadConvertor = &MatrixPayloadUnsafe{} ) var _ PayloadConvertor = &MatrixPayloadUnsafe{} // safePayload "converts" a unsafe payload to a safe payload func (m *MatrixPayloadUnsafe) safePayload() *MatrixPayloadSafe {
-
-
-
@@ -65,9 +65,7 @@ func (m *MSTeamsPayload) JSONPayload() ([]byte, error) {return data, nil } var ( _ PayloadConvertor = &MSTeamsPayload{} ) var _ PayloadConvertor = &MSTeamsPayload{} // Create implements PayloadConvertor Create method func (m *MSTeamsPayload) Create(p *api.CreatePayload) (api.Payloader, error) {
-
-
-
@@ -96,9 +96,7 @@ func SlackLinkToRef(repoURL, ref string) string {return SlackLinkFormatter(url, refName) } var ( _ PayloadConvertor = &SlackPayload{} ) var _ PayloadConvertor = &SlackPayload{} // Create implements PayloadConvertor Create method func (s *SlackPayload) Create(p *api.CreatePayload) (api.Payloader, error) {
-
-
-
@@ -40,9 +40,7 @@ func GetTelegramHook(w *webhook_model.Webhook) *TelegramMeta {return s } var ( _ PayloadConvertor = &TelegramPayload{} ) var _ PayloadConvertor = &TelegramPayload{} // JSONPayload Marshals the TelegramPayload to json func (t *TelegramPayload) JSONPayload() ([]byte, error) {
-
-
-
@@ -25,42 +25,40 @@ type webhook struct {payloadCreator func(p api.Payloader, event webhook_model.HookEventType, meta string) (api.Payloader, error) } var ( webhooks = map[webhook_model.HookType]*webhook{ webhook_model.SLACK: { name: webhook_model.SLACK, payloadCreator: GetSlackPayload, }, webhook_model.DISCORD: { name: webhook_model.DISCORD, payloadCreator: GetDiscordPayload, }, webhook_model.DINGTALK: { name: webhook_model.DINGTALK, payloadCreator: GetDingtalkPayload, }, webhook_model.TELEGRAM: { name: webhook_model.TELEGRAM, payloadCreator: GetTelegramPayload, }, webhook_model.MSTEAMS: { name: webhook_model.MSTEAMS, payloadCreator: GetMSTeamsPayload, }, webhook_model.FEISHU: { name: webhook_model.FEISHU, payloadCreator: GetFeishuPayload, }, webhook_model.MATRIX: { name: webhook_model.MATRIX, payloadCreator: GetMatrixPayload, }, webhook_model.WECHATWORK: { name: webhook_model.WECHATWORK, payloadCreator: GetWechatworkPayload, }, } ) var webhooks = map[webhook_model.HookType]*webhook{ webhook_model.SLACK: { name: webhook_model.SLACK, payloadCreator: GetSlackPayload, }, webhook_model.DISCORD: { name: webhook_model.DISCORD, payloadCreator: GetDiscordPayload, }, webhook_model.DINGTALK: { name: webhook_model.DINGTALK, payloadCreator: GetDingtalkPayload, }, webhook_model.TELEGRAM: { name: webhook_model.TELEGRAM, payloadCreator: GetTelegramPayload, }, webhook_model.MSTEAMS: { name: webhook_model.MSTEAMS, payloadCreator: GetMSTeamsPayload, }, webhook_model.FEISHU: { name: webhook_model.FEISHU, payloadCreator: GetFeishuPayload, }, webhook_model.MATRIX: { name: webhook_model.MATRIX, payloadCreator: GetMatrixPayload, }, webhook_model.WECHATWORK: { name: webhook_model.WECHATWORK, payloadCreator: GetWechatworkPayload, }, } // RegisterWebhook registers a webhook func RegisterWebhook(name string, webhook *webhook) {
-
-
-
@@ -52,9 +52,7 @@ func newWechatworkMarkdownPayload(title string) *WechatworkPayload {} } var ( _ PayloadConvertor = &WechatworkPayload{} ) var _ PayloadConvertor = &WechatworkPayload{} // Create implements PayloadConvertor Create method func (f *WechatworkPayload) Create(p *api.CreatePayload) (api.Payloader, error) {
-
@@ -72,12 +70,10 @@ func (f *WechatworkPayload) Delete(p *api.DeletePayload) (api.Payloader, error)title := fmt.Sprintf("[%s] %s %s deleted", p.Repo.FullName, p.RefType, refName) return newWechatworkMarkdownPayload(title), nil } // Fork implements PayloadConvertor Fork method func (f *WechatworkPayload) Fork(p *api.ForkPayload) (api.Payloader, error) { title := fmt.Sprintf("%s is forked to %s", p.Forkee.FullName, p.Repo.FullName) return newWechatworkMarkdownPayload(title), nil
-
@@ -110,7 +106,6 @@ func (f *WechatworkPayload) Push(p *api.PushPayload) (api.Payloader, error) {} } return newWechatworkMarkdownPayload(title + "\r\n\r\n" + text), nil } // Issue implements PayloadConvertor Issue method
-
@@ -120,7 +115,6 @@ func (f *WechatworkPayload) Issue(p *api.IssuePayload) (api.Payloader, error) {content += fmt.Sprintf(" ><font color=\"info\">%s</font>\n >%s \n ><font color=\"warning\"> %s</font> \n [%s](%s)", text, attachmentText, issueTitle, p.Issue.HTMLURL, p.Issue.HTMLURL) return newWechatworkMarkdownPayload(content), nil } // IssueComment implements PayloadConvertor IssueComment method
-
@@ -130,7 +124,6 @@ func (f *WechatworkPayload) IssueComment(p *api.IssueCommentPayload) (api.Payloacontent += fmt.Sprintf(" ><font color=\"info\">%s</font>\n >%s \n ><font color=\"warning\">%s</font> \n [%s](%s)", text, p.Comment.Body, issueTitle, p.Comment.HTMLURL, p.Comment.HTMLURL) return newWechatworkMarkdownPayload(content), nil } // PullRequest implements PayloadConvertor PullRequest method
-
@@ -140,7 +133,6 @@ func (f *WechatworkPayload) PullRequest(p *api.PullRequestPayload) (api.Payloadetext, issueTitle, attachmentText) return newWechatworkMarkdownPayload(pr), nil } // Review implements PayloadConvertor Review method
-
@@ -157,7 +149,6 @@ func (f *WechatworkPayload) Review(p *api.PullRequestPayload, event webhook_mode} return newWechatworkMarkdownPayload("# " + title + "\r\n\r\n >" + text), nil } // Repository implements PayloadConvertor Repository method
-
-
-
@@ -24,16 +24,14 @@ import (// (for example, the input is lexically correct and was parsed successfully). // -1 if the input must not be added to corpus even if gives new coverage and 0 otherwise. var ( renderContext = markup.RenderContext{ Ctx: context.Background(), URLPrefix: "https://example.com/go-gitea/gitea", Metas: map[string]string{ "user": "go-gitea", "repo": "gitea", }, } ) var renderContext = markup.RenderContext{ Ctx: context.Background(), URLPrefix: "https://example.com/go-gitea/gitea", Metas: map[string]string{ "user": "go-gitea", "repo": "gitea", }, } func FuzzMarkdownRenderRaw(data []byte) int { setting.AppURL = "http://localhost:3000/"
-