diff --git a/cmd/web.go b/cmd/web.go index d9cd59c1a..e16e40b90 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -156,9 +156,9 @@ func newMacaron() *macaron.Macaron { return m } -func runWeb(ctx *cli.Context) error { - if ctx.IsSet("config") { - setting.CustomConf = ctx.String("config") +func runWeb(c *cli.Context) error { + if c.IsSet("config") { + setting.CustomConf = c.String("config") } routers.GlobalInit() checkVersion() @@ -177,8 +177,8 @@ func runWeb(ctx *cli.Context) error { // Routers. m.Get("/", ignSignIn, routers.Home) m.Group("/explore", func() { - m.Get("", func(ctx *context.Context) { - ctx.Redirect(setting.AppSubURL + "/explore/repos") + m.Get("", func(c *context.Context) { + c.Redirect(setting.AppSubURL + "/explore/repos") }) m.Get("/repos", routers.ExploreRepos) m.Get("/users", routers.ExploreUsers) @@ -237,8 +237,8 @@ func runWeb(ctx *cli.Context) error { Post(bindIgnErr(form.NewAccessToken{}), user.SettingsApplicationsPost) m.Post("/applications/delete", user.SettingsDeleteApplication) m.Route("/delete", "GET,POST", user.SettingsDelete) - }, reqSignIn, func(ctx *context.Context) { - ctx.Data["PageIsUserSettings"] = true + }, reqSignIn, func(c *context.Context) { + c.Data["PageIsUserSettings"] = true }) m.Group("/user", func() { @@ -300,28 +300,28 @@ func runWeb(ctx *cli.Context) error { m.Get("/stars", user.Stars) }) - m.Get("/attachments/:uuid", func(ctx *context.Context) { - attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid")) + m.Get("/attachments/:uuid", func(c *context.Context) { + attach, err := models.GetAttachmentByUUID(c.Params(":uuid")) if err != nil { - ctx.NotFoundOrServerError("GetAttachmentByUUID", models.IsErrAttachmentNotExist, err) + c.NotFoundOrServerError("GetAttachmentByUUID", models.IsErrAttachmentNotExist, err) return } else if !com.IsFile(attach.LocalPath()) { - ctx.NotFound() + c.NotFound() return } fr, err := os.Open(attach.LocalPath()) if err != nil { - ctx.Handle(500, "Open", err) + c.Handle(500, "Open", err) return } defer fr.Close() - ctx.Header().Set("Cache-Control", "public,max-age=86400") + c.Header().Set("Cache-Control", "public,max-age=86400") fmt.Println("attach.Name:", attach.Name) - ctx.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name)) - if err = repo.ServeData(ctx, attach.Name, fr); err != nil { - ctx.Handle(500, "ServeData", err) + c.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name)) + if err = repo.ServeData(c, attach.Name, fr); err != nil { + c.Handle(500, "ServeData", err) return } }) @@ -345,9 +345,9 @@ func runWeb(ctx *cli.Context) error { m.Group("", func() { m.Get("/create", org.Create) m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost) - }, func(ctx *context.Context) { - if !ctx.User.CanCreateOrganization() { - ctx.NotFound() + }, func(c *context.Context) { + if !c.User.CanCreateOrganization() { + c.NotFound() } }) @@ -425,9 +425,9 @@ func runWeb(ctx *cli.Context) error { m.Post("/default_branch", repo.UpdateDefaultBranch) m.Combo("/*").Get(repo.SettingsProtectedBranch). Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost) - }, func(ctx *context.Context) { - if ctx.Repo.Repository.IsMirror { - ctx.NotFound() + }, func(c *context.Context) { + if c.Repo.Repository.IsMirror { + c.NotFound() return } }) @@ -462,8 +462,8 @@ func runWeb(ctx *cli.Context) error { m.Post("/delete", repo.DeleteDeployKey) }) - }, func(ctx *context.Context) { - ctx.Data["PageIsSettings"] = true + }, func(c *context.Context) { + c.Data["PageIsSettings"] = true }) }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef()) @@ -530,11 +530,11 @@ func runWeb(ctx *cli.Context) error { m.Post("/delete", repo.DeleteRelease) m.Get("/edit/*", repo.EditRelease) m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost) - }, repo.MustBeNotBare, reqRepoWriter, func(ctx *context.Context) { - ctx.Data["PageIsViewFiles"] = true + }, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) { + c.Data["PageIsViewFiles"] = true }) - // FIXME: Should use ctx.Repo.PullRequest to unify template, currently we have inconsistent URL + // FIXME: Should use c.Repo.PullRequest to unify template, currently we have inconsistent URL // for PR in same repository. After select branch on the page, the URL contains redundant head user name. // e.g. /org1/test-repo/compare/master...org1:develop // which should be /org1/test-repo/compare/master...develop @@ -555,19 +555,19 @@ func runWeb(ctx *cli.Context) error { Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost) m.Post("/upload-file", repo.UploadFileToServer) m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer) - }, func(ctx *context.Context) { + }, func(c *context.Context) { if !setting.Repository.Upload.Enabled { - ctx.NotFound() + c.NotFound() return } }) - }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) { - if !ctx.Repo.CanEnableEditor() { - ctx.NotFound() + }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) { + if !c.Repo.CanEnableEditor() { + c.NotFound() return } - ctx.Data["PageIsViewFiles"] = true + c.Data["PageIsViewFiles"] = true }) }, reqSignIn, context.RepoAssignment()) @@ -582,8 +582,8 @@ func runWeb(ctx *cli.Context) error { m.Get("", repo.Branches) m.Get("/all", repo.AllBranches) m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost) - }, repo.MustBeNotBare, func(ctx *context.Context) { - ctx.Data["PageIsViewFiles"] = true + }, repo.MustBeNotBare, func(c *context.Context) { + c.Data["PageIsViewFiles"] = true }) m.Group("/wiki", func() { @@ -642,11 +642,11 @@ func runWeb(ctx *cli.Context) error { }, ignSignIn) // robots.txt - m.Get("/robots.txt", func(ctx *context.Context) { + m.Get("/robots.txt", func(c *context.Context) { if setting.HasRobotsTxt { - ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt")) + c.ServeFileContent(path.Join(setting.CustomPath, "robots.txt")) } else { - ctx.Error(404) + c.NotFound() } }) @@ -654,9 +654,9 @@ func runWeb(ctx *cli.Context) error { m.NotFound(routers.NotFound) // Flag for port number in case first time run conflict. - if ctx.IsSet("port") { - setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, ctx.String("port"), 1) - setting.HTTPPort = ctx.String("port") + if c.IsSet("port") { + setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, c.String("port"), 1) + setting.HTTPPort = c.String("port") } var listenAddr string diff --git a/pkg/context/api.go b/pkg/context/api.go index 623bc1aac..f4b95b4c7 100644 --- a/pkg/context/api.go +++ b/pkg/context/api.go @@ -25,7 +25,7 @@ const DOC_URL = "https://github.com/gogits/go-gogs-client/wiki" // Error responses error message to client with given message. // If status is 500, also it prints error to log. -func (ctx *APIContext) Error(status int, title string, obj interface{}) { +func (c *APIContext) Error(status int, title string, obj interface{}) { var message string if err, ok := obj.(error); ok { message = err.Error() @@ -37,39 +37,39 @@ func (ctx *APIContext) Error(status int, title string, obj interface{}) { log.Error(3, "%s: %s", title, message) } - ctx.JSON(status, map[string]string{ + c.JSON(status, map[string]string{ "message": message, "url": DOC_URL, }) } // SetLinkHeader sets pagination link header by given totol number and page size. -func (ctx *APIContext) SetLinkHeader(total, pageSize int) { - page := paginater.New(total, pageSize, ctx.QueryInt("page"), 0) +func (c *APIContext) SetLinkHeader(total, pageSize int) { + page := paginater.New(total, pageSize, c.QueryInt("page"), 0) links := make([]string, 0, 4) if page.HasNext() { - links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, ctx.Req.URL.Path[1:], page.Next())) + links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, c.Req.URL.Path[1:], page.Next())) } if !page.IsLast() { - links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, ctx.Req.URL.Path[1:], page.TotalPages())) + links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, c.Req.URL.Path[1:], page.TotalPages())) } if !page.IsFirst() { - links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, ctx.Req.URL.Path[1:])) + links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, c.Req.URL.Path[1:])) } if page.HasPrevious() { - links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, ctx.Req.URL.Path[1:], page.Previous())) + links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, c.Req.URL.Path[1:], page.Previous())) } if len(links) > 0 { - ctx.Header().Set("Link", strings.Join(links, ",")) + c.Header().Set("Link", strings.Join(links, ",")) } } func APIContexter() macaron.Handler { - return func(c *Context) { - ctx := &APIContext{ - Context: c, + return func(ctx *Context) { + c := &APIContext{ + Context: ctx, } - c.Map(ctx) + ctx.Map(c) } } diff --git a/pkg/context/auth.go b/pkg/context/auth.go index 9ad5cdd0f..3ffc9c8f2 100644 --- a/pkg/context/auth.go +++ b/pkg/context/auth.go @@ -22,73 +22,73 @@ type ToggleOptions struct { } func Toggle(options *ToggleOptions) macaron.Handler { - return func(ctx *Context) { + return func(c *Context) { // Cannot view any page before installation. if !setting.InstallLock { - ctx.Redirect(setting.AppSubURL + "/install") + c.Redirect(setting.AppSubURL + "/install") return } // Check prohibit login users. - if ctx.IsLogged && ctx.User.ProhibitLogin { - ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") - ctx.HTML(200, "user/auth/prohibit_login") + if c.IsLogged && c.User.ProhibitLogin { + c.Data["Title"] = c.Tr("auth.prohibit_login") + c.HTML(200, "user/auth/prohibit_login") return } // Check non-logged users landing page. - if !ctx.IsLogged && ctx.Req.RequestURI == "/" && setting.LandingPageURL != setting.LANDING_PAGE_HOME { - ctx.Redirect(setting.AppSubURL + string(setting.LandingPageURL)) + if !c.IsLogged && c.Req.RequestURI == "/" && setting.LandingPageURL != setting.LANDING_PAGE_HOME { + c.Redirect(setting.AppSubURL + string(setting.LandingPageURL)) return } // Redirect to dashboard if user tries to visit any non-login page. - if options.SignOutRequired && ctx.IsLogged && ctx.Req.RequestURI != "/" { - ctx.Redirect(setting.AppSubURL + "/") + if options.SignOutRequired && c.IsLogged && c.Req.RequestURI != "/" { + c.Redirect(setting.AppSubURL + "/") return } - if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" && !auth.IsAPIPath(ctx.Req.URL.Path) { - csrf.Validate(ctx.Context, ctx.csrf) - if ctx.Written() { + if !options.SignOutRequired && !options.DisableCSRF && c.Req.Method == "POST" && !auth.IsAPIPath(c.Req.URL.Path) { + csrf.Validate(c.Context, c.csrf) + if c.Written() { return } } if options.SignInRequired { - if !ctx.IsLogged { + if !c.IsLogged { // Restrict API calls with error message. - if auth.IsAPIPath(ctx.Req.URL.Path) { - ctx.JSON(403, map[string]string{ + if auth.IsAPIPath(c.Req.URL.Path) { + c.JSON(403, map[string]string{ "message": "Only signed in user is allowed to call APIs.", }) return } - ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+ctx.Req.RequestURI), 0, setting.AppSubURL) - ctx.Redirect(setting.AppSubURL + "/user/login") + c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+c.Req.RequestURI), 0, setting.AppSubURL) + c.Redirect(setting.AppSubURL + "/user/login") return - } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { - ctx.Data["Title"] = ctx.Tr("auth.active_your_account") - ctx.HTML(200, "user/auth/activate") + } else if !c.User.IsActive && setting.Service.RegisterEmailConfirm { + c.Data["Title"] = c.Tr("auth.active_your_account") + c.HTML(200, "user/auth/activate") return } } // Redirect to log in page if auto-signin info is provided and has not signed in. - if !options.SignOutRequired && !ctx.IsLogged && !auth.IsAPIPath(ctx.Req.URL.Path) && - len(ctx.GetCookie(setting.CookieUserName)) > 0 { - ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+ctx.Req.RequestURI), 0, setting.AppSubURL) - ctx.Redirect(setting.AppSubURL + "/user/login") + if !options.SignOutRequired && !c.IsLogged && !auth.IsAPIPath(c.Req.URL.Path) && + len(c.GetCookie(setting.CookieUserName)) > 0 { + c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+c.Req.RequestURI), 0, setting.AppSubURL) + c.Redirect(setting.AppSubURL + "/user/login") return } if options.AdminRequired { - if !ctx.User.IsAdmin { - ctx.Error(403) + if !c.User.IsAdmin { + c.Error(403) return } - ctx.Data["PageIsAdmin"] = true + c.Data["PageIsAdmin"] = true } } } diff --git a/pkg/context/context.go b/pkg/context/context.go index d52c668e5..e8843cea4 100644 --- a/pkg/context/context.go +++ b/pkg/context/context.go @@ -85,39 +85,39 @@ func (c *Context) UserID() int64 { } // HasError returns true if error occurs in form validation. -func (ctx *Context) HasApiError() bool { - hasErr, ok := ctx.Data["HasError"] +func (c *Context) HasApiError() bool { + hasErr, ok := c.Data["HasError"] if !ok { return false } return hasErr.(bool) } -func (ctx *Context) GetErrMsg() string { - return ctx.Data["ErrorMsg"].(string) +func (c *Context) GetErrMsg() string { + return c.Data["ErrorMsg"].(string) } // HasError returns true if error occurs in form validation. -func (ctx *Context) HasError() bool { - hasErr, ok := ctx.Data["HasError"] +func (c *Context) HasError() bool { + hasErr, ok := c.Data["HasError"] if !ok { return false } - ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string) - ctx.Data["Flash"] = ctx.Flash + c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string) + c.Data["Flash"] = c.Flash return hasErr.(bool) } // HasValue returns true if value of given name exists. -func (ctx *Context) HasValue(name string) bool { - _, ok := ctx.Data[name] +func (c *Context) HasValue(name string) bool { + _, ok := c.Data[name] return ok } // HTML responses template with given status. -func (ctx *Context) HTML(status int, name string) { +func (c *Context) HTML(status int, name string) { log.Trace("Template: %s", name) - ctx.Context.HTML(status, name) + c.Context.HTML(status, name) } // Success responses template with status http.StatusOK. @@ -137,33 +137,33 @@ func (c *Context) SubURLRedirect(location string, status ...int) { } // RenderWithErr used for page has form validation but need to prompt error to users. -func (ctx *Context) RenderWithErr(msg, tpl string, f interface{}) { +func (c *Context) RenderWithErr(msg, tpl string, f interface{}) { if f != nil { - form.Assign(f, ctx.Data) + form.Assign(f, c.Data) } - ctx.Flash.ErrorMsg = msg - ctx.Data["Flash"] = ctx.Flash - ctx.HTML(http.StatusOK, tpl) + c.Flash.ErrorMsg = msg + c.Data["Flash"] = c.Flash + c.HTML(http.StatusOK, tpl) } // Handle handles and logs error by given status. -func (ctx *Context) Handle(status int, title string, err error) { +func (c *Context) Handle(status int, title string, err error) { switch status { case http.StatusNotFound: - ctx.Data["Title"] = "Page Not Found" + c.Data["Title"] = "Page Not Found" case http.StatusInternalServerError: - ctx.Data["Title"] = "Internal Server Error" + c.Data["Title"] = "Internal Server Error" log.Error(2, "%s: %v", title, err) - if !setting.ProdMode || (ctx.IsLogged && ctx.User.IsAdmin) { - ctx.Data["ErrorMsg"] = err + if !setting.ProdMode || (c.IsLogged && c.User.IsAdmin) { + c.Data["ErrorMsg"] = err } } - ctx.HTML(status, fmt.Sprintf("status/%d", status)) + c.HTML(status, fmt.Sprintf("status/%d", status)) } // NotFound renders the 404 page. -func (ctx *Context) NotFound() { - ctx.Handle(http.StatusNotFound, "", nil) +func (c *Context) NotFound() { + c.Handle(http.StatusNotFound, "", nil) } // ServerError renders the 500 page. @@ -182,11 +182,11 @@ func (c *Context) NotFoundOrServerError(title string, errck func(error) bool, er c.ServerError(title, err) } -func (ctx *Context) HandleText(status int, title string) { - ctx.PlainText(status, []byte(title)) +func (c *Context) HandleText(status int, title string) { + c.PlainText(status, []byte(title)) } -func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) { +func (c *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) { modtime := time.Now() for _, p := range params { switch v := p.(type) { @@ -194,14 +194,14 @@ func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interfa modtime = v } } - ctx.Resp.Header().Set("Content-Description", "File Transfer") - ctx.Resp.Header().Set("Content-Type", "application/octet-stream") - ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name) - ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary") - ctx.Resp.Header().Set("Expires", "0") - ctx.Resp.Header().Set("Cache-Control", "must-revalidate") - ctx.Resp.Header().Set("Pragma", "public") - http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r) + c.Resp.Header().Set("Content-Description", "File Transfer") + c.Resp.Header().Set("Content-Type", "application/octet-stream") + c.Resp.Header().Set("Content-Disposition", "attachment; filename="+name) + c.Resp.Header().Set("Content-Transfer-Encoding", "binary") + c.Resp.Header().Set("Expires", "0") + c.Resp.Header().Set("Cache-Control", "must-revalidate") + c.Resp.Header().Set("Pragma", "public") + http.ServeContent(c.Resp, c.Req.Request, name, modtime, r) } // Contexter initializes a classic context for a request. @@ -228,8 +228,8 @@ func Contexter() macaron.Handler { // This is particular a workaround for "go get" command which does not respect // .netrc file. if c.Query("go-get") == "1" { - ownerName := ctx.Params(":username") - repoName := ctx.Params(":reponame") + ownerName := c.Params(":username") + repoName := c.Params(":reponame") branchName := "master" owner, err := models.GetUserByName(ownerName) @@ -244,7 +244,7 @@ func Contexter() macaron.Handler { } prefix := setting.AppURL + path.Join(ownerName, repoName, "src", branchName) - ctx.PlainText(http.StatusOK, []byte(com.Expand(` + c.PlainText(http.StatusOK, []byte(com.Expand(`
diff --git a/pkg/context/org.go b/pkg/context/org.go index be0b0572b..45c23bd6e 100644 --- a/pkg/context/org.go +++ b/pkg/context/org.go @@ -25,7 +25,7 @@ type Organization struct { Team *models.Team } -func HandleOrgAssignment(ctx *Context, args ...bool) { +func HandleOrgAssignment(c *Context, args ...bool) { var ( requireMember bool requireOwner bool @@ -45,106 +45,106 @@ func HandleOrgAssignment(ctx *Context, args ...bool) { requireTeamAdmin = args[3] } - orgName := ctx.Params(":org") + orgName := c.Params(":org") var err error - ctx.Org.Organization, err = models.GetUserByName(orgName) + c.Org.Organization, err = models.GetUserByName(orgName) if err != nil { - ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) + c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) return } - org := ctx.Org.Organization - ctx.Data["Org"] = org + org := c.Org.Organization + c.Data["Org"] = org // Force redirection when username is actually a user. if !org.IsOrganization() { - ctx.Redirect("/" + org.Name) + c.Redirect("/" + org.Name) return } // Admin has super access. - if ctx.IsLogged && ctx.User.IsAdmin { - ctx.Org.IsOwner = true - ctx.Org.IsMember = true - ctx.Org.IsTeamMember = true - ctx.Org.IsTeamAdmin = true - } else if ctx.IsLogged { - ctx.Org.IsOwner = org.IsOwnedBy(ctx.User.ID) - if ctx.Org.IsOwner { - ctx.Org.IsMember = true - ctx.Org.IsTeamMember = true - ctx.Org.IsTeamAdmin = true + if c.IsLogged && c.User.IsAdmin { + c.Org.IsOwner = true + c.Org.IsMember = true + c.Org.IsTeamMember = true + c.Org.IsTeamAdmin = true + } else if c.IsLogged { + c.Org.IsOwner = org.IsOwnedBy(c.User.ID) + if c.Org.IsOwner { + c.Org.IsMember = true + c.Org.IsTeamMember = true + c.Org.IsTeamAdmin = true } else { - if org.IsOrgMember(ctx.User.ID) { - ctx.Org.IsMember = true + if org.IsOrgMember(c.User.ID) { + c.Org.IsMember = true } } } else { // Fake data. - ctx.Data["SignedUser"] = &models.User{} + c.Data["SignedUser"] = &models.User{} } - if (requireMember && !ctx.Org.IsMember) || - (requireOwner && !ctx.Org.IsOwner) { - ctx.Handle(404, "OrgAssignment", err) + if (requireMember && !c.Org.IsMember) || + (requireOwner && !c.Org.IsOwner) { + c.Handle(404, "OrgAssignment", err) return } - ctx.Data["IsOrganizationOwner"] = ctx.Org.IsOwner - ctx.Data["IsOrganizationMember"] = ctx.Org.IsMember + c.Data["IsOrganizationOwner"] = c.Org.IsOwner + c.Data["IsOrganizationMember"] = c.Org.IsMember - ctx.Org.OrgLink = setting.AppSubURL + "/org/" + org.Name - ctx.Data["OrgLink"] = ctx.Org.OrgLink + c.Org.OrgLink = setting.AppSubURL + "/org/" + org.Name + c.Data["OrgLink"] = c.Org.OrgLink // Team. - if ctx.Org.IsMember { - if ctx.Org.IsOwner { + if c.Org.IsMember { + if c.Org.IsOwner { if err := org.GetTeams(); err != nil { - ctx.Handle(500, "GetTeams", err) + c.Handle(500, "GetTeams", err) return } } else { - org.Teams, err = org.GetUserTeams(ctx.User.ID) + org.Teams, err = org.GetUserTeams(c.User.ID) if err != nil { - ctx.Handle(500, "GetUserTeams", err) + c.Handle(500, "GetUserTeams", err) return } } } - teamName := ctx.Params(":team") + teamName := c.Params(":team") if len(teamName) > 0 { teamExists := false for _, team := range org.Teams { if team.LowerName == strings.ToLower(teamName) { teamExists = true - ctx.Org.Team = team - ctx.Org.IsTeamMember = true - ctx.Data["Team"] = ctx.Org.Team + c.Org.Team = team + c.Org.IsTeamMember = true + c.Data["Team"] = c.Org.Team break } } if !teamExists { - ctx.Handle(404, "OrgAssignment", err) + c.Handle(404, "OrgAssignment", err) return } - ctx.Data["IsTeamMember"] = ctx.Org.IsTeamMember - if requireTeamMember && !ctx.Org.IsTeamMember { - ctx.Handle(404, "OrgAssignment", err) + c.Data["IsTeamMember"] = c.Org.IsTeamMember + if requireTeamMember && !c.Org.IsTeamMember { + c.Handle(404, "OrgAssignment", err) return } - ctx.Org.IsTeamAdmin = ctx.Org.Team.IsOwnerTeam() || ctx.Org.Team.Authorize >= models.ACCESS_MODE_ADMIN - ctx.Data["IsTeamAdmin"] = ctx.Org.IsTeamAdmin - if requireTeamAdmin && !ctx.Org.IsTeamAdmin { - ctx.Handle(404, "OrgAssignment", err) + c.Org.IsTeamAdmin = c.Org.Team.IsOwnerTeam() || c.Org.Team.Authorize >= models.ACCESS_MODE_ADMIN + c.Data["IsTeamAdmin"] = c.Org.IsTeamAdmin + if requireTeamAdmin && !c.Org.IsTeamAdmin { + c.Handle(404, "OrgAssignment", err) return } } } func OrgAssignment(args ...bool) macaron.Handler { - return func(ctx *Context) { - HandleOrgAssignment(ctx, args...) + return func(c *Context) { + HandleOrgAssignment(c, args...) } } diff --git a/pkg/context/repo.go b/pkg/context/repo.go index 7920b27bd..761b8af01 100644 --- a/pkg/context/repo.go +++ b/pkg/context/repo.go @@ -108,7 +108,7 @@ func (r *Repository) PullRequestURL(baseBranch, headBranch string) string { // [0]: issues, [1]: wiki func RepoAssignment(pages ...bool) macaron.Handler { - return func(ctx *Context) { + return func(c *Context) { var ( owner *models.User err error @@ -123,53 +123,53 @@ func RepoAssignment(pages ...bool) macaron.Handler { isWikiPage = pages[1] } - ownerName := ctx.Params(":username") - repoName := strings.TrimSuffix(ctx.Params(":reponame"), ".git") - refName := ctx.Params(":branchname") + ownerName := c.Params(":username") + repoName := strings.TrimSuffix(c.Params(":reponame"), ".git") + refName := c.Params(":branchname") if len(refName) == 0 { - refName = ctx.Params(":path") + refName = c.Params(":path") } // Check if the user is the same as the repository owner - if ctx.IsLogged && ctx.User.LowerName == strings.ToLower(ownerName) { - owner = ctx.User + if c.IsLogged && c.User.LowerName == strings.ToLower(ownerName) { + owner = c.User } else { owner, err = models.GetUserByName(ownerName) if err != nil { - ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) + c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) return } } - ctx.Repo.Owner = owner - ctx.Data["Username"] = ctx.Repo.Owner.Name + c.Repo.Owner = owner + c.Data["Username"] = c.Repo.Owner.Name repo, err := models.GetRepositoryByName(owner.ID, repoName) if err != nil { - ctx.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err) + c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err) return } - ctx.Repo.Repository = repo - ctx.Data["RepoName"] = ctx.Repo.Repository.Name - ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare - ctx.Repo.RepoLink = repo.Link() - ctx.Data["RepoLink"] = ctx.Repo.RepoLink - ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name + c.Repo.Repository = repo + c.Data["RepoName"] = c.Repo.Repository.Name + c.Data["IsBareRepo"] = c.Repo.Repository.IsBare + c.Repo.RepoLink = repo.Link() + c.Data["RepoLink"] = c.Repo.RepoLink + c.Data["RepoRelPath"] = c.Repo.Owner.Name + "/" + c.Repo.Repository.Name // Admin has super access. - if ctx.IsLogged && ctx.User.IsAdmin { - ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER + if c.IsLogged && c.User.IsAdmin { + c.Repo.AccessMode = models.ACCESS_MODE_OWNER } else { - mode, err := models.AccessLevel(ctx.UserID(), repo) + mode, err := models.AccessLevel(c.UserID(), repo) if err != nil { - ctx.ServerError("AccessLevel", err) + c.ServerError("AccessLevel", err) return } - ctx.Repo.AccessMode = mode + c.Repo.AccessMode = mode } // Check access - if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { + if c.Repo.AccessMode == models.ACCESS_MODE_NONE { // Redirect to any accessible page if not yet on it if repo.IsPartialPublic() && (!(isIssuesPage || isWikiPage) || @@ -177,11 +177,11 @@ func RepoAssignment(pages ...bool) macaron.Handler { (isWikiPage && !repo.CanGuestViewWiki())) { switch { case repo.CanGuestViewIssues(): - ctx.Redirect(repo.Link() + "/issues") + c.Redirect(repo.Link() + "/issues") case repo.CanGuestViewWiki(): - ctx.Redirect(repo.Link() + "/wiki") + c.Redirect(repo.Link() + "/wiki") default: - ctx.NotFound() + c.NotFound() } return } @@ -190,92 +190,92 @@ func RepoAssignment(pages ...bool) macaron.Handler { if !repo.IsPartialPublic() || (isIssuesPage && !repo.CanGuestViewIssues()) || (isWikiPage && !repo.CanGuestViewWiki()) { - ctx.NotFound() + c.NotFound() return } - ctx.Repo.Repository.EnableIssues = repo.CanGuestViewIssues() - ctx.Repo.Repository.EnableWiki = repo.CanGuestViewWiki() + c.Repo.Repository.EnableIssues = repo.CanGuestViewIssues() + c.Repo.Repository.EnableWiki = repo.CanGuestViewWiki() } if repo.IsMirror { - ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID) + c.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID) if err != nil { - ctx.Handle(500, "GetMirror", err) + c.ServerError("GetMirror", err) return } - ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune - ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval - ctx.Data["Mirror"] = ctx.Repo.Mirror + c.Data["MirrorEnablePrune"] = c.Repo.Mirror.EnablePrune + c.Data["MirrorInterval"] = c.Repo.Mirror.Interval + c.Data["Mirror"] = c.Repo.Mirror } gitRepo, err := git.OpenRepository(models.RepoPath(ownerName, repoName)) if err != nil { - ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(ownerName, repoName), err) + c.ServerError(fmt.Sprintf("RepoAssignment Invalid repo '%s'", c.Repo.Repository.RepoPath()), err) return } - ctx.Repo.GitRepo = gitRepo + c.Repo.GitRepo = gitRepo - tags, err := ctx.Repo.GitRepo.GetTags() + tags, err := c.Repo.GitRepo.GetTags() if err != nil { - ctx.Handle(500, fmt.Sprintf("GetTags '%s'", ctx.Repo.Repository.RepoPath()), err) + c.ServerError(fmt.Sprintf("GetTags '%s'", c.Repo.Repository.RepoPath()), err) return } - ctx.Data["Tags"] = tags - ctx.Repo.Repository.NumTags = len(tags) - - ctx.Data["Title"] = owner.Name + "/" + repo.Name - ctx.Data["Repository"] = repo - ctx.Data["Owner"] = ctx.Repo.Repository.Owner - ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner() - ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin() - ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter() - - ctx.Data["DisableSSH"] = setting.SSH.Disabled - ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit - ctx.Data["CloneLink"] = repo.CloneLink() - ctx.Data["WikiCloneLink"] = repo.WikiCloneLink() - - if ctx.IsLogged { - ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID) - ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID) + c.Data["Tags"] = tags + c.Repo.Repository.NumTags = len(tags) + + c.Data["Title"] = owner.Name + "/" + repo.Name + c.Data["Repository"] = repo + c.Data["Owner"] = c.Repo.Repository.Owner + c.Data["IsRepositoryOwner"] = c.Repo.IsOwner() + c.Data["IsRepositoryAdmin"] = c.Repo.IsAdmin() + c.Data["IsRepositoryWriter"] = c.Repo.IsWriter() + + c.Data["DisableSSH"] = setting.SSH.Disabled + c.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit + c.Data["CloneLink"] = repo.CloneLink() + c.Data["WikiCloneLink"] = repo.WikiCloneLink() + + if c.IsLogged { + c.Data["IsWatchingRepo"] = models.IsWatching(c.User.ID, repo.ID) + c.Data["IsStaringRepo"] = models.IsStaring(c.User.ID, repo.ID) } // repo is bare and display enable - if ctx.Repo.Repository.IsBare { + if c.Repo.Repository.IsBare { return } - ctx.Data["TagName"] = ctx.Repo.TagName - brs, err := ctx.Repo.GitRepo.GetBranches() + c.Data["TagName"] = c.Repo.TagName + brs, err := c.Repo.GitRepo.GetBranches() if err != nil { - ctx.Handle(500, "GetBranches", err) + c.ServerError("GetBranches", err) return } - ctx.Data["Branches"] = brs - ctx.Data["BrancheCount"] = len(brs) + c.Data["Branches"] = brs + c.Data["BrancheCount"] = len(brs) // If not branch selected, try default one. // If default branch doesn't exists, fall back to some other branch. - if len(ctx.Repo.BranchName) == 0 { - if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) { - ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch + if len(c.Repo.BranchName) == 0 { + if len(c.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(c.Repo.Repository.DefaultBranch) { + c.Repo.BranchName = c.Repo.Repository.DefaultBranch } else if len(brs) > 0 { - ctx.Repo.BranchName = brs[0] + c.Repo.BranchName = brs[0] } } - ctx.Data["BranchName"] = ctx.Repo.BranchName - ctx.Data["CommitID"] = ctx.Repo.CommitID + c.Data["BranchName"] = c.Repo.BranchName + c.Data["CommitID"] = c.Repo.CommitID - ctx.Data["IsGuest"] = !ctx.Repo.HasAccess() + c.Data["IsGuest"] = !c.Repo.HasAccess() } } // RepoRef handles repository reference name including those contain `/`. func RepoRef() macaron.Handler { - return func(ctx *Context) { + return func(c *Context) { // Empty repository does not have reference information. - if ctx.Repo.Repository.IsBare { + if c.Repo.Repository.IsBare { return } @@ -285,44 +285,44 @@ func RepoRef() macaron.Handler { ) // For API calls. - if ctx.Repo.GitRepo == nil { - repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) - ctx.Repo.GitRepo, err = git.OpenRepository(repoPath) + if c.Repo.GitRepo == nil { + repoPath := models.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name) + c.Repo.GitRepo, err = git.OpenRepository(repoPath) if err != nil { - ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err) + c.Handle(500, "RepoRef Invalid repo "+repoPath, err) return } } // Get default branch. - if len(ctx.Params("*")) == 0 { - refName = ctx.Repo.Repository.DefaultBranch - if !ctx.Repo.GitRepo.IsBranchExist(refName) { - brs, err := ctx.Repo.GitRepo.GetBranches() + if len(c.Params("*")) == 0 { + refName = c.Repo.Repository.DefaultBranch + if !c.Repo.GitRepo.IsBranchExist(refName) { + brs, err := c.Repo.GitRepo.GetBranches() if err != nil { - ctx.Handle(500, "GetBranches", err) + c.Handle(500, "GetBranches", err) return } refName = brs[0] } - ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName) + c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(refName) if err != nil { - ctx.Handle(500, "GetBranchCommit", err) + c.Handle(500, "GetBranchCommit", err) return } - ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() - ctx.Repo.IsViewBranch = true + c.Repo.CommitID = c.Repo.Commit.ID.String() + c.Repo.IsViewBranch = true } else { hasMatched := false - parts := strings.Split(ctx.Params("*"), "/") + parts := strings.Split(c.Params("*"), "/") for i, part := range parts { refName = strings.TrimPrefix(refName+"/"+part, "/") - if ctx.Repo.GitRepo.IsBranchExist(refName) || - ctx.Repo.GitRepo.IsTagExist(refName) { + if c.Repo.GitRepo.IsBranchExist(refName) || + c.Repo.GitRepo.IsTagExist(refName) { if i < len(parts)-1 { - ctx.Repo.TreePath = strings.Join(parts[i+1:], "/") + c.Repo.TreePath = strings.Join(parts[i+1:], "/") } hasMatched = true break @@ -330,97 +330,97 @@ func RepoRef() macaron.Handler { } if !hasMatched && len(parts[0]) == 40 { refName = parts[0] - ctx.Repo.TreePath = strings.Join(parts[1:], "/") + c.Repo.TreePath = strings.Join(parts[1:], "/") } - if ctx.Repo.GitRepo.IsBranchExist(refName) { - ctx.Repo.IsViewBranch = true + if c.Repo.GitRepo.IsBranchExist(refName) { + c.Repo.IsViewBranch = true - ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName) + c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(refName) if err != nil { - ctx.Handle(500, "GetBranchCommit", err) + c.Handle(500, "GetBranchCommit", err) return } - ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() + c.Repo.CommitID = c.Repo.Commit.ID.String() - } else if ctx.Repo.GitRepo.IsTagExist(refName) { - ctx.Repo.IsViewTag = true - ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName) + } else if c.Repo.GitRepo.IsTagExist(refName) { + c.Repo.IsViewTag = true + c.Repo.Commit, err = c.Repo.GitRepo.GetTagCommit(refName) if err != nil { - ctx.Handle(500, "GetTagCommit", err) + c.Handle(500, "GetTagCommit", err) return } - ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() + c.Repo.CommitID = c.Repo.Commit.ID.String() } else if len(refName) == 40 { - ctx.Repo.IsViewCommit = true - ctx.Repo.CommitID = refName + c.Repo.IsViewCommit = true + c.Repo.CommitID = refName - ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName) + c.Repo.Commit, err = c.Repo.GitRepo.GetCommit(refName) if err != nil { - ctx.NotFound() + c.NotFound() return } } else { - ctx.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName)) + c.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName)) return } } - ctx.Repo.BranchName = refName - ctx.Data["BranchName"] = ctx.Repo.BranchName - ctx.Data["CommitID"] = ctx.Repo.CommitID - ctx.Data["TreePath"] = ctx.Repo.TreePath - ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch - ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag - ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit + c.Repo.BranchName = refName + c.Data["BranchName"] = c.Repo.BranchName + c.Data["CommitID"] = c.Repo.CommitID + c.Data["TreePath"] = c.Repo.TreePath + c.Data["IsViewBranch"] = c.Repo.IsViewBranch + c.Data["IsViewTag"] = c.Repo.IsViewTag + c.Data["IsViewCommit"] = c.Repo.IsViewCommit // People who have push access or have fored repository can propose a new pull request. - if ctx.Repo.IsWriter() || (ctx.IsLogged && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) { + if c.Repo.IsWriter() || (c.IsLogged && c.User.HasForkedRepo(c.Repo.Repository.ID)) { // Pull request is allowed if this is a fork repository // and base repository accepts pull requests. - if ctx.Repo.Repository.BaseRepo != nil { - if ctx.Repo.Repository.BaseRepo.AllowsPulls() { - ctx.Repo.PullRequest.Allowed = true + if c.Repo.Repository.BaseRepo != nil { + if c.Repo.Repository.BaseRepo.AllowsPulls() { + c.Repo.PullRequest.Allowed = true // In-repository pull requests has higher priority than cross-repository if user is viewing // base repository and 1) has write access to it 2) has forked it. - if ctx.Repo.IsWriter() { - ctx.Data["BaseRepo"] = ctx.Repo.Repository.BaseRepo - ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository.BaseRepo - ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName + if c.Repo.IsWriter() { + c.Data["BaseRepo"] = c.Repo.Repository.BaseRepo + c.Repo.PullRequest.BaseRepo = c.Repo.Repository.BaseRepo + c.Repo.PullRequest.HeadInfo = c.Repo.Owner.Name + ":" + c.Repo.BranchName } else { - ctx.Data["BaseRepo"] = ctx.Repo.Repository - ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository - ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName + c.Data["BaseRepo"] = c.Repo.Repository + c.Repo.PullRequest.BaseRepo = c.Repo.Repository + c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName } } } else { // Or, this is repository accepts pull requests between branches. - if ctx.Repo.Repository.AllowsPulls() { - ctx.Data["BaseRepo"] = ctx.Repo.Repository - ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository - ctx.Repo.PullRequest.Allowed = true - ctx.Repo.PullRequest.SameRepo = true - ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName + if c.Repo.Repository.AllowsPulls() { + c.Data["BaseRepo"] = c.Repo.Repository + c.Repo.PullRequest.BaseRepo = c.Repo.Repository + c.Repo.PullRequest.Allowed = true + c.Repo.PullRequest.SameRepo = true + c.Repo.PullRequest.HeadInfo = c.Repo.BranchName } } } - ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest + c.Data["PullRequestCtx"] = c.Repo.PullRequest } } func RequireRepoAdmin() macaron.Handler { - return func(ctx *Context) { - if !ctx.IsLogged || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) { - ctx.NotFound() + return func(c *Context) { + if !c.IsLogged || (!c.Repo.IsAdmin() && !c.User.IsAdmin) { + c.NotFound() return } } } func RequireRepoWriter() macaron.Handler { - return func(ctx *Context) { - if !ctx.IsLogged || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) { - ctx.NotFound() + return func(c *Context) { + if !c.IsLogged || (!c.Repo.IsWriter() && !c.User.IsAdmin) { + c.NotFound() return } } @@ -428,9 +428,9 @@ func RequireRepoWriter() macaron.Handler { // GitHookService checks if repository Git hooks service has been enabled. func GitHookService() macaron.Handler { - return func(ctx *Context) { - if !ctx.User.CanEditGitHook() { - ctx.NotFound() + return func(c *Context) { + if !c.User.CanEditGitHook() { + c.NotFound() return } } diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 69ca48774..0d5eb7a68 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -125,111 +125,111 @@ const ( REINIT_MISSING_REPOSITORY ) -func Dashboard(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.dashboard") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminDashboard"] = true +func Dashboard(c *context.Context) { + c.Data["Title"] = c.Tr("admin.dashboard") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminDashboard"] = true // Run operation. - op, _ := com.StrTo(ctx.Query("op")).Int() + op, _ := com.StrTo(c.Query("op")).Int() if op > 0 { var err error var success string switch AdminOperation(op) { case CLEAN_INACTIVATE_USER: - success = ctx.Tr("admin.dashboard.delete_inactivate_accounts_success") + success = c.Tr("admin.dashboard.delete_inactivate_accounts_success") err = models.DeleteInactivateUsers() case CLEAN_REPO_ARCHIVES: - success = ctx.Tr("admin.dashboard.delete_repo_archives_success") + success = c.Tr("admin.dashboard.delete_repo_archives_success") err = models.DeleteRepositoryArchives() case CLEAN_MISSING_REPOS: - success = ctx.Tr("admin.dashboard.delete_missing_repos_success") + success = c.Tr("admin.dashboard.delete_missing_repos_success") err = models.DeleteMissingRepositories() case GIT_GC_REPOS: - success = ctx.Tr("admin.dashboard.git_gc_repos_success") + success = c.Tr("admin.dashboard.git_gc_repos_success") err = models.GitGcRepos() case SYNC_SSH_AUTHORIZED_KEY: - success = ctx.Tr("admin.dashboard.resync_all_sshkeys_success") + success = c.Tr("admin.dashboard.resync_all_sshkeys_success") err = models.RewriteAllPublicKeys() case SYNC_REPOSITORY_HOOKS: - success = ctx.Tr("admin.dashboard.resync_all_hooks_success") + success = c.Tr("admin.dashboard.resync_all_hooks_success") err = models.SyncRepositoryHooks() case REINIT_MISSING_REPOSITORY: - success = ctx.Tr("admin.dashboard.reinit_missing_repos_success") + success = c.Tr("admin.dashboard.reinit_missing_repos_success") err = models.ReinitMissingRepositories() } if err != nil { - ctx.Flash.Error(err.Error()) + c.Flash.Error(err.Error()) } else { - ctx.Flash.Success(success) + c.Flash.Success(success) } - ctx.Redirect(setting.AppSubURL + "/admin") + c.Redirect(setting.AppSubURL + "/admin") return } - ctx.Data["Stats"] = models.GetStatistic() + c.Data["Stats"] = models.GetStatistic() // FIXME: update periodically updateSystemStatus() - ctx.Data["SysStatus"] = sysStatus - ctx.HTML(200, DASHBOARD) + c.Data["SysStatus"] = sysStatus + c.HTML(200, DASHBOARD) } -func SendTestMail(ctx *context.Context) { - email := ctx.Query("email") +func SendTestMail(c *context.Context) { + email := c.Query("email") // Send a test email to the user's email address and redirect back to Config if err := mailer.SendTestMail(email); err != nil { - ctx.Flash.Error(ctx.Tr("admin.config.test_mail_failed", email, err)) + c.Flash.Error(c.Tr("admin.config.test_mail_failed", email, err)) } else { - ctx.Flash.Info(ctx.Tr("admin.config.test_mail_sent", email)) + c.Flash.Info(c.Tr("admin.config.test_mail_sent", email)) } - ctx.Redirect(setting.AppSubURL + "/admin/config") + c.Redirect(setting.AppSubURL + "/admin/config") } -func Config(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.config") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminConfig"] = true +func Config(c *context.Context) { + c.Data["Title"] = c.Tr("admin.config") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminConfig"] = true - ctx.Data["AppURL"] = setting.AppURL - ctx.Data["Domain"] = setting.Domain - ctx.Data["OfflineMode"] = setting.OfflineMode - ctx.Data["DisableRouterLog"] = setting.DisableRouterLog - ctx.Data["RunUser"] = setting.RunUser - ctx.Data["RunMode"] = strings.Title(macaron.Env) - ctx.Data["StaticRootPath"] = setting.StaticRootPath - ctx.Data["LogRootPath"] = setting.LogRootPath - ctx.Data["ReverseProxyAuthUser"] = setting.ReverseProxyAuthUser + c.Data["AppURL"] = setting.AppURL + c.Data["Domain"] = setting.Domain + c.Data["OfflineMode"] = setting.OfflineMode + c.Data["DisableRouterLog"] = setting.DisableRouterLog + c.Data["RunUser"] = setting.RunUser + c.Data["RunMode"] = strings.Title(macaron.Env) + c.Data["StaticRootPath"] = setting.StaticRootPath + c.Data["LogRootPath"] = setting.LogRootPath + c.Data["ReverseProxyAuthUser"] = setting.ReverseProxyAuthUser - ctx.Data["SSH"] = setting.SSH + c.Data["SSH"] = setting.SSH - ctx.Data["RepoRootPath"] = setting.RepoRootPath - ctx.Data["ScriptType"] = setting.ScriptType - ctx.Data["Repository"] = setting.Repository + c.Data["RepoRootPath"] = setting.RepoRootPath + c.Data["ScriptType"] = setting.ScriptType + c.Data["Repository"] = setting.Repository - ctx.Data["Service"] = setting.Service - ctx.Data["DbCfg"] = models.DbCfg - ctx.Data["Webhook"] = setting.Webhook + c.Data["Service"] = setting.Service + c.Data["DbCfg"] = models.DbCfg + c.Data["Webhook"] = setting.Webhook - ctx.Data["MailerEnabled"] = false + c.Data["MailerEnabled"] = false if setting.MailService != nil { - ctx.Data["MailerEnabled"] = true - ctx.Data["Mailer"] = setting.MailService + c.Data["MailerEnabled"] = true + c.Data["Mailer"] = setting.MailService } - ctx.Data["CacheAdapter"] = setting.CacheAdapter - ctx.Data["CacheInterval"] = setting.CacheInterval - ctx.Data["CacheConn"] = setting.CacheConn + c.Data["CacheAdapter"] = setting.CacheAdapter + c.Data["CacheInterval"] = setting.CacheInterval + c.Data["CacheConn"] = setting.CacheConn - ctx.Data["SessionConfig"] = setting.SessionConfig + c.Data["SessionConfig"] = setting.SessionConfig - ctx.Data["DisableGravatar"] = setting.DisableGravatar - ctx.Data["EnableFederatedAvatar"] = setting.EnableFederatedAvatar + c.Data["DisableGravatar"] = setting.DisableGravatar + c.Data["EnableFederatedAvatar"] = setting.EnableFederatedAvatar - ctx.Data["GitVersion"] = setting.Git.Version - ctx.Data["Git"] = setting.Git + c.Data["GitVersion"] = setting.Git.Version + c.Data["Git"] = setting.Git type logger struct { Mode, Config string @@ -243,16 +243,16 @@ func Config(ctx *context.Context) { result, _ := json.MarshalIndent(setting.LogConfigs[i], "", " ") loggers[i].Config = string(result) } - ctx.Data["Loggers"] = loggers + c.Data["Loggers"] = loggers - ctx.HTML(200, CONFIG) + c.HTML(200, CONFIG) } -func Monitor(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.monitor") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminMonitor"] = true - ctx.Data["Processes"] = process.Processes - ctx.Data["Entries"] = cron.ListTasks() - ctx.HTML(200, MONITOR) +func Monitor(c *context.Context) { + c.Data["Title"] = c.Tr("admin.monitor") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminMonitor"] = true + c.Data["Processes"] = process.Processes + c.Data["Entries"] = cron.ListTasks() + c.HTML(200, MONITOR) } diff --git a/routers/admin/auths.go b/routers/admin/auths.go index bc60fb2d9..56a0aad60 100644 --- a/routers/admin/auths.go +++ b/routers/admin/auths.go @@ -24,20 +24,20 @@ const ( AUTH_EDIT = "admin/auth/edit" ) -func Authentications(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.authentication") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminAuthentications"] = true +func Authentications(c *context.Context) { + c.Data["Title"] = c.Tr("admin.authentication") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminAuthentications"] = true var err error - ctx.Data["Sources"], err = models.LoginSources() + c.Data["Sources"], err = models.LoginSources() if err != nil { - ctx.Handle(500, "LoginSources", err) + c.Handle(500, "LoginSources", err) return } - ctx.Data["Total"] = models.CountLoginSources() - ctx.HTML(200, AUTHS) + c.Data["Total"] = models.CountLoginSources() + c.HTML(200, AUTHS) } type dropdownItem struct { @@ -59,20 +59,20 @@ var ( } ) -func NewAuthSource(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.auths.new") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminAuthentications"] = true - - ctx.Data["type"] = models.LOGIN_LDAP - ctx.Data["CurrentTypeName"] = models.LoginNames[models.LOGIN_LDAP] - ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_UNENCRYPTED] - ctx.Data["smtp_auth"] = "PLAIN" - ctx.Data["is_active"] = true - ctx.Data["AuthSources"] = authSources - ctx.Data["SecurityProtocols"] = securityProtocols - ctx.Data["SMTPAuths"] = models.SMTPAuths - ctx.HTML(200, AUTH_NEW) +func NewAuthSource(c *context.Context) { + c.Data["Title"] = c.Tr("admin.auths.new") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminAuthentications"] = true + + c.Data["type"] = models.LOGIN_LDAP + c.Data["CurrentTypeName"] = models.LoginNames[models.LOGIN_LDAP] + c.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_UNENCRYPTED] + c.Data["smtp_auth"] = "PLAIN" + c.Data["is_active"] = true + c.Data["AuthSources"] = authSources + c.Data["SecurityProtocols"] = securityProtocols + c.Data["SMTPAuths"] = models.SMTPAuths + c.HTML(200, AUTH_NEW) } func parseLDAPConfig(f form.Authentication) *models.LDAPConfig { @@ -115,16 +115,16 @@ func parseSMTPConfig(f form.Authentication) *models.SMTPConfig { } } -func NewAuthSourcePost(ctx *context.Context, f form.Authentication) { - ctx.Data["Title"] = ctx.Tr("admin.auths.new") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminAuthentications"] = true +func NewAuthSourcePost(c *context.Context, f form.Authentication) { + c.Data["Title"] = c.Tr("admin.auths.new") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminAuthentications"] = true - ctx.Data["CurrentTypeName"] = models.LoginNames[models.LoginType(f.Type)] - ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocol(f.SecurityProtocol)] - ctx.Data["AuthSources"] = authSources - ctx.Data["SecurityProtocols"] = securityProtocols - ctx.Data["SMTPAuths"] = models.SMTPAuths + c.Data["CurrentTypeName"] = models.LoginNames[models.LoginType(f.Type)] + c.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocol(f.SecurityProtocol)] + c.Data["AuthSources"] = authSources + c.Data["SecurityProtocols"] = securityProtocols + c.Data["SMTPAuths"] = models.SMTPAuths hasTLS := false var config core.Conversion @@ -140,13 +140,13 @@ func NewAuthSourcePost(ctx *context.Context, f form.Authentication) { ServiceName: f.PAMServiceName, } default: - ctx.Error(400) + c.Error(400) return } - ctx.Data["HasTLS"] = hasTLS + c.Data["HasTLS"] = hasTLS - if ctx.HasError() { - ctx.HTML(200, AUTH_NEW) + if c.HasError() { + c.HTML(200, AUTH_NEW) return } @@ -157,56 +157,56 @@ func NewAuthSourcePost(ctx *context.Context, f form.Authentication) { Cfg: config, }); err != nil { if models.IsErrLoginSourceAlreadyExist(err) { - ctx.Data["Err_Name"] = true - ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(models.ErrLoginSourceAlreadyExist).Name), AUTH_NEW, f) + c.Data["Err_Name"] = true + c.RenderWithErr(c.Tr("admin.auths.login_source_exist", err.(models.ErrLoginSourceAlreadyExist).Name), AUTH_NEW, f) } else { - ctx.Handle(500, "CreateSource", err) + c.Handle(500, "CreateSource", err) } return } - log.Trace("Authentication created by admin(%s): %s", ctx.User.Name, f.Name) + log.Trace("Authentication created by admin(%s): %s", c.User.Name, f.Name) - ctx.Flash.Success(ctx.Tr("admin.auths.new_success", f.Name)) - ctx.Redirect(setting.AppSubURL + "/admin/auths") + c.Flash.Success(c.Tr("admin.auths.new_success", f.Name)) + c.Redirect(setting.AppSubURL + "/admin/auths") } -func EditAuthSource(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.auths.edit") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminAuthentications"] = true +func EditAuthSource(c *context.Context) { + c.Data["Title"] = c.Tr("admin.auths.edit") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminAuthentications"] = true - ctx.Data["SecurityProtocols"] = securityProtocols - ctx.Data["SMTPAuths"] = models.SMTPAuths + c.Data["SecurityProtocols"] = securityProtocols + c.Data["SMTPAuths"] = models.SMTPAuths - source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid")) + source, err := models.GetLoginSourceByID(c.ParamsInt64(":authid")) if err != nil { - ctx.Handle(500, "GetLoginSourceByID", err) + c.Handle(500, "GetLoginSourceByID", err) return } - ctx.Data["Source"] = source - ctx.Data["HasTLS"] = source.HasTLS() + c.Data["Source"] = source + c.Data["HasTLS"] = source.HasTLS() - ctx.HTML(200, AUTH_EDIT) + c.HTML(200, AUTH_EDIT) } -func EditAuthSourcePost(ctx *context.Context, f form.Authentication) { - ctx.Data["Title"] = ctx.Tr("admin.auths.edit") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminAuthentications"] = true +func EditAuthSourcePost(c *context.Context, f form.Authentication) { + c.Data["Title"] = c.Tr("admin.auths.edit") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminAuthentications"] = true - ctx.Data["SMTPAuths"] = models.SMTPAuths + c.Data["SMTPAuths"] = models.SMTPAuths - source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid")) + source, err := models.GetLoginSourceByID(c.ParamsInt64(":authid")) if err != nil { - ctx.Handle(500, "GetLoginSourceByID", err) + c.Handle(500, "GetLoginSourceByID", err) return } - ctx.Data["Source"] = source - ctx.Data["HasTLS"] = source.HasTLS() + c.Data["Source"] = source + c.Data["HasTLS"] = source.HasTLS() - if ctx.HasError() { - ctx.HTML(200, AUTH_EDIT) + if c.HasError() { + c.HTML(200, AUTH_EDIT) return } @@ -221,7 +221,7 @@ func EditAuthSourcePost(ctx *context.Context, f form.Authentication) { ServiceName: f.PAMServiceName, } default: - ctx.Error(400) + c.Error(400) return } @@ -229,37 +229,37 @@ func EditAuthSourcePost(ctx *context.Context, f form.Authentication) { source.IsActived = f.IsActive source.Cfg = config if err := models.UpdateSource(source); err != nil { - ctx.Handle(500, "UpdateSource", err) + c.Handle(500, "UpdateSource", err) return } - log.Trace("Authentication changed by admin(%s): %d", ctx.User.Name, source.ID) + log.Trace("Authentication changed by admin(%s): %d", c.User.Name, source.ID) - ctx.Flash.Success(ctx.Tr("admin.auths.update_success")) - ctx.Redirect(setting.AppSubURL + "/admin/auths/" + com.ToStr(f.ID)) + c.Flash.Success(c.Tr("admin.auths.update_success")) + c.Redirect(setting.AppSubURL + "/admin/auths/" + com.ToStr(f.ID)) } -func DeleteAuthSource(ctx *context.Context) { - source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid")) +func DeleteAuthSource(c *context.Context) { + source, err := models.GetLoginSourceByID(c.ParamsInt64(":authid")) if err != nil { - ctx.Handle(500, "GetLoginSourceByID", err) + c.Handle(500, "GetLoginSourceByID", err) return } if err = models.DeleteSource(source); err != nil { if models.IsErrLoginSourceInUse(err) { - ctx.Flash.Error(ctx.Tr("admin.auths.still_in_used")) + c.Flash.Error(c.Tr("admin.auths.still_in_used")) } else { - ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err)) + c.Flash.Error(fmt.Sprintf("DeleteSource: %v", err)) } - ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubURL + "/admin/auths/" + ctx.Params(":authid"), + c.JSON(200, map[string]interface{}{ + "redirect": setting.AppSubURL + "/admin/auths/" + c.Params(":authid"), }) return } - log.Trace("Authentication deleted by admin(%s): %d", ctx.User.Name, source.ID) + log.Trace("Authentication deleted by admin(%s): %d", c.User.Name, source.ID) - ctx.Flash.Success(ctx.Tr("admin.auths.deletion_success")) - ctx.JSON(200, map[string]interface{}{ + c.Flash.Success(c.Tr("admin.auths.deletion_success")) + c.JSON(200, map[string]interface{}{ "redirect": setting.AppSubURL + "/admin/auths", }) } diff --git a/routers/admin/notice.go b/routers/admin/notice.go index 37f120bcf..c743a1da5 100644 --- a/routers/admin/notice.go +++ b/routers/admin/notice.go @@ -18,31 +18,31 @@ const ( NOTICES = "admin/notice" ) -func Notices(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.notices") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminNotices"] = true +func Notices(c *context.Context) { + c.Data["Title"] = c.Tr("admin.notices") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminNotices"] = true total := models.CountNotices() - page := ctx.QueryInt("page") + page := c.QueryInt("page") if page <= 1 { page = 1 } - ctx.Data["Page"] = paginater.New(int(total), setting.UI.Admin.NoticePagingNum, page, 5) + c.Data["Page"] = paginater.New(int(total), setting.UI.Admin.NoticePagingNum, page, 5) notices, err := models.Notices(page, setting.UI.Admin.NoticePagingNum) if err != nil { - ctx.Handle(500, "Notices", err) + c.Handle(500, "Notices", err) return } - ctx.Data["Notices"] = notices + c.Data["Notices"] = notices - ctx.Data["Total"] = total - ctx.HTML(200, NOTICES) + c.Data["Total"] = total + c.HTML(200, NOTICES) } -func DeleteNotices(ctx *context.Context) { - strs := ctx.QueryStrings("ids[]") +func DeleteNotices(c *context.Context) { + strs := c.QueryStrings("ids[]") ids := make([]int64, 0, len(strs)) for i := range strs { id := com.StrTo(strs[i]).MustInt64() @@ -52,21 +52,21 @@ func DeleteNotices(ctx *context.Context) { } if err := models.DeleteNoticesByIDs(ids); err != nil { - ctx.Flash.Error("DeleteNoticesByIDs: " + err.Error()) - ctx.Status(500) + c.Flash.Error("DeleteNoticesByIDs: " + err.Error()) + c.Status(500) } else { - ctx.Flash.Success(ctx.Tr("admin.notices.delete_success")) - ctx.Status(200) + c.Flash.Success(c.Tr("admin.notices.delete_success")) + c.Status(200) } } -func EmptyNotices(ctx *context.Context) { +func EmptyNotices(c *context.Context) { if err := models.DeleteNotices(0, 0); err != nil { - ctx.Handle(500, "DeleteNotices", err) + c.Handle(500, "DeleteNotices", err) return } - log.Trace("System notices deleted by admin (%s): [start: %d]", ctx.User.Name, 0) - ctx.Flash.Success(ctx.Tr("admin.notices.delete_success")) - ctx.Redirect(setting.AppSubURL + "/admin/notices") + log.Trace("System notices deleted by admin (%s): [start: %d]", c.User.Name, 0) + c.Flash.Success(c.Tr("admin.notices.delete_success")) + c.Redirect(setting.AppSubURL + "/admin/notices") } diff --git a/routers/admin/orgs.go b/routers/admin/orgs.go index 80732e724..4b995acd6 100644 --- a/routers/admin/orgs.go +++ b/routers/admin/orgs.go @@ -15,12 +15,12 @@ const ( ORGS = "admin/org/list" ) -func Organizations(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.organizations") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminOrganizations"] = true +func Organizations(c *context.Context) { + c.Data["Title"] = c.Tr("admin.organizations") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminOrganizations"] = true - routers.RenderUserSearch(ctx, &routers.UserSearchOptions{ + routers.RenderUserSearch(c, &routers.UserSearchOptions{ Type: models.USER_TYPE_ORGANIZATION, Counter: models.CountOrganizations, Ranger: models.Organizations, diff --git a/routers/admin/repos.go b/routers/admin/repos.go index b26917062..b4fa22664 100644 --- a/routers/admin/repos.go +++ b/routers/admin/repos.go @@ -17,12 +17,12 @@ const ( REPOS = "admin/repo/list" ) -func Repos(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.repositories") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminRepositories"] = true +func Repos(c *context.Context) { + c.Data["Title"] = c.Tr("admin.repositories") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminRepositories"] = true - page := ctx.QueryInt("page") + page := c.QueryInt("page") if page <= 0 { page = 1 } @@ -33,11 +33,11 @@ func Repos(ctx *context.Context) { err error ) - keyword := ctx.Query("q") + keyword := c.Query("q") if len(keyword) == 0 { repos, err = models.Repositories(page, setting.UI.Admin.RepoPagingNum) if err != nil { - ctx.Handle(500, "Repositories", err) + c.Handle(500, "Repositories", err) return } count = models.CountRepositories(true) @@ -50,38 +50,38 @@ func Repos(ctx *context.Context) { PageSize: setting.UI.Admin.RepoPagingNum, }) if err != nil { - ctx.Handle(500, "SearchRepositoryByName", err) + c.Handle(500, "SearchRepositoryByName", err) return } } - ctx.Data["Keyword"] = keyword - ctx.Data["Total"] = count - ctx.Data["Page"] = paginater.New(int(count), setting.UI.Admin.RepoPagingNum, page, 5) + c.Data["Keyword"] = keyword + c.Data["Total"] = count + c.Data["Page"] = paginater.New(int(count), setting.UI.Admin.RepoPagingNum, page, 5) if err = models.RepositoryList(repos).LoadAttributes(); err != nil { - ctx.Handle(500, "LoadAttributes", err) + c.Handle(500, "LoadAttributes", err) return } - ctx.Data["Repos"] = repos + c.Data["Repos"] = repos - ctx.HTML(200, REPOS) + c.HTML(200, REPOS) } -func DeleteRepo(ctx *context.Context) { - repo, err := models.GetRepositoryByID(ctx.QueryInt64("id")) +func DeleteRepo(c *context.Context) { + repo, err := models.GetRepositoryByID(c.QueryInt64("id")) if err != nil { - ctx.Handle(500, "GetRepositoryByID", err) + c.Handle(500, "GetRepositoryByID", err) return } if err := models.DeleteRepository(repo.MustOwner().ID, repo.ID); err != nil { - ctx.Handle(500, "DeleteRepository", err) + c.Handle(500, "DeleteRepository", err) return } log.Trace("Repository deleted: %s/%s", repo.MustOwner().Name, repo.Name) - ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success")) - ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubURL + "/admin/repos?page=" + ctx.Query("page"), + c.Flash.Success(c.Tr("repo.settings.deletion_success")) + c.JSON(200, map[string]interface{}{ + "redirect": setting.AppSubURL + "/admin/repos?page=" + c.Query("page"), }) } diff --git a/routers/admin/users.go b/routers/admin/users.go index 4b8949c18..237f2dc65 100644 --- a/routers/admin/users.go +++ b/routers/admin/users.go @@ -24,12 +24,12 @@ const ( USER_EDIT = "admin/user/edit" ) -func Users(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.users") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminUsers"] = true +func Users(c *context.Context) { + c.Data["Title"] = c.Tr("admin.users") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminUsers"] = true - routers.RenderUserSearch(ctx, &routers.UserSearchOptions{ + routers.RenderUserSearch(c, &routers.UserSearchOptions{ Type: models.USER_TYPE_INDIVIDUAL, Counter: models.CountUsers, Ranger: models.Users, @@ -39,40 +39,40 @@ func Users(ctx *context.Context) { }) } -func NewUser(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.users.new_account") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminUsers"] = true +func NewUser(c *context.Context) { + c.Data["Title"] = c.Tr("admin.users.new_account") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminUsers"] = true - ctx.Data["login_type"] = "0-0" + c.Data["login_type"] = "0-0" sources, err := models.LoginSources() if err != nil { - ctx.Handle(500, "LoginSources", err) + c.Handle(500, "LoginSources", err) return } - ctx.Data["Sources"] = sources + c.Data["Sources"] = sources - ctx.Data["CanSendEmail"] = setting.MailService != nil - ctx.HTML(200, USER_NEW) + c.Data["CanSendEmail"] = setting.MailService != nil + c.HTML(200, USER_NEW) } -func NewUserPost(ctx *context.Context, f form.AdminCrateUser) { - ctx.Data["Title"] = ctx.Tr("admin.users.new_account") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminUsers"] = true +func NewUserPost(c *context.Context, f form.AdminCrateUser) { + c.Data["Title"] = c.Tr("admin.users.new_account") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminUsers"] = true sources, err := models.LoginSources() if err != nil { - ctx.Handle(500, "LoginSources", err) + c.Handle(500, "LoginSources", err) return } - ctx.Data["Sources"] = sources + c.Data["Sources"] = sources - ctx.Data["CanSendEmail"] = setting.MailService != nil + c.Data["CanSendEmail"] = setting.MailService != nil - if ctx.HasError() { - ctx.HTML(200, USER_NEW) + if c.HasError() { + c.HTML(200, USER_NEW) return } @@ -96,88 +96,88 @@ func NewUserPost(ctx *context.Context, f form.AdminCrateUser) { if err := models.CreateUser(u); err != nil { switch { case models.IsErrUserAlreadyExist(err): - ctx.Data["Err_UserName"] = true - ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), USER_NEW, &f) + c.Data["Err_UserName"] = true + c.RenderWithErr(c.Tr("form.username_been_taken"), USER_NEW, &f) case models.IsErrEmailAlreadyUsed(err): - ctx.Data["Err_Email"] = true - ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_NEW, &f) + c.Data["Err_Email"] = true + c.RenderWithErr(c.Tr("form.email_been_used"), USER_NEW, &f) case models.IsErrNameReserved(err): - ctx.Data["Err_UserName"] = true - ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), USER_NEW, &f) + c.Data["Err_UserName"] = true + c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), USER_NEW, &f) case models.IsErrNamePatternNotAllowed(err): - ctx.Data["Err_UserName"] = true - ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), USER_NEW, &f) + c.Data["Err_UserName"] = true + c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), USER_NEW, &f) default: - ctx.Handle(500, "CreateUser", err) + c.Handle(500, "CreateUser", err) } return } - log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name) + log.Trace("Account created by admin (%s): %s", c.User.Name, u.Name) // Send email notification. if f.SendNotify && setting.MailService != nil { - mailer.SendRegisterNotifyMail(ctx.Context, models.NewMailerUser(u)) + mailer.SendRegisterNotifyMail(c.Context, models.NewMailerUser(u)) } - ctx.Flash.Success(ctx.Tr("admin.users.new_success", u.Name)) - ctx.Redirect(setting.AppSubURL + "/admin/users/" + com.ToStr(u.ID)) + c.Flash.Success(c.Tr("admin.users.new_success", u.Name)) + c.Redirect(setting.AppSubURL + "/admin/users/" + com.ToStr(u.ID)) } -func prepareUserInfo(ctx *context.Context) *models.User { - u, err := models.GetUserByID(ctx.ParamsInt64(":userid")) +func prepareUserInfo(c *context.Context) *models.User { + u, err := models.GetUserByID(c.ParamsInt64(":userid")) if err != nil { - ctx.Handle(500, "GetUserByID", err) + c.Handle(500, "GetUserByID", err) return nil } - ctx.Data["User"] = u + c.Data["User"] = u if u.LoginSource > 0 { - ctx.Data["LoginSource"], err = models.GetLoginSourceByID(u.LoginSource) + c.Data["LoginSource"], err = models.GetLoginSourceByID(u.LoginSource) if err != nil { - ctx.Handle(500, "GetLoginSourceByID", err) + c.Handle(500, "GetLoginSourceByID", err) return nil } } else { - ctx.Data["LoginSource"] = &models.LoginSource{} + c.Data["LoginSource"] = &models.LoginSource{} } sources, err := models.LoginSources() if err != nil { - ctx.Handle(500, "LoginSources", err) + c.Handle(500, "LoginSources", err) return nil } - ctx.Data["Sources"] = sources + c.Data["Sources"] = sources return u } -func EditUser(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("admin.users.edit_account") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminUsers"] = true - ctx.Data["EnableLocalPathMigration"] = setting.Repository.EnableLocalPathMigration +func EditUser(c *context.Context) { + c.Data["Title"] = c.Tr("admin.users.edit_account") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminUsers"] = true + c.Data["EnableLocalPathMigration"] = setting.Repository.EnableLocalPathMigration - prepareUserInfo(ctx) - if ctx.Written() { + prepareUserInfo(c) + if c.Written() { return } - ctx.HTML(200, USER_EDIT) + c.HTML(200, USER_EDIT) } -func EditUserPost(ctx *context.Context, f form.AdminEditUser) { - ctx.Data["Title"] = ctx.Tr("admin.users.edit_account") - ctx.Data["PageIsAdmin"] = true - ctx.Data["PageIsAdminUsers"] = true - ctx.Data["EnableLocalPathMigration"] = setting.Repository.EnableLocalPathMigration +func EditUserPost(c *context.Context, f form.AdminEditUser) { + c.Data["Title"] = c.Tr("admin.users.edit_account") + c.Data["PageIsAdmin"] = true + c.Data["PageIsAdminUsers"] = true + c.Data["EnableLocalPathMigration"] = setting.Repository.EnableLocalPathMigration - u := prepareUserInfo(ctx) - if ctx.Written() { + u := prepareUserInfo(c) + if c.Written() { return } - if ctx.HasError() { - ctx.HTML(200, USER_EDIT) + if c.HasError() { + c.HTML(200, USER_EDIT) return } @@ -196,7 +196,7 @@ func EditUserPost(ctx *context.Context, f form.AdminEditUser) { u.Passwd = f.Password var err error if u.Salt, err = models.GetUserSalt(); err != nil { - ctx.Handle(500, "UpdateUser", err) + c.Handle(500, "UpdateUser", err) return } u.EncodePasswd() @@ -216,47 +216,47 @@ func EditUserPost(ctx *context.Context, f form.AdminEditUser) { if err := models.UpdateUser(u); err != nil { if models.IsErrEmailAlreadyUsed(err) { - ctx.Data["Err_Email"] = true - ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_EDIT, &f) + c.Data["Err_Email"] = true + c.RenderWithErr(c.Tr("form.email_been_used"), USER_EDIT, &f) } else { - ctx.Handle(500, "UpdateUser", err) + c.Handle(500, "UpdateUser", err) } return } - log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name) + log.Trace("Account profile updated by admin (%s): %s", c.User.Name, u.Name) - ctx.Flash.Success(ctx.Tr("admin.users.update_profile_success")) - ctx.Redirect(setting.AppSubURL + "/admin/users/" + ctx.Params(":userid")) + c.Flash.Success(c.Tr("admin.users.update_profile_success")) + c.Redirect(setting.AppSubURL + "/admin/users/" + c.Params(":userid")) } -func DeleteUser(ctx *context.Context) { - u, err := models.GetUserByID(ctx.ParamsInt64(":userid")) +func DeleteUser(c *context.Context) { + u, err := models.GetUserByID(c.ParamsInt64(":userid")) if err != nil { - ctx.Handle(500, "GetUserByID", err) + c.Handle(500, "GetUserByID", err) return } if err = models.DeleteUser(u); err != nil { switch { case models.IsErrUserOwnRepos(err): - ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo")) - ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"), + c.Flash.Error(c.Tr("admin.users.still_own_repo")) + c.JSON(200, map[string]interface{}{ + "redirect": setting.AppSubURL + "/admin/users/" + c.Params(":userid"), }) case models.IsErrUserHasOrgs(err): - ctx.Flash.Error(ctx.Tr("admin.users.still_has_org")) - ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"), + c.Flash.Error(c.Tr("admin.users.still_has_org")) + c.JSON(200, map[string]interface{}{ + "redirect": setting.AppSubURL + "/admin/users/" + c.Params(":userid"), }) default: - ctx.Handle(500, "DeleteUser", err) + c.Handle(500, "DeleteUser", err) } return } - log.Trace("Account deleted by admin (%s): %s", ctx.User.Name, u.Name) + log.Trace("Account deleted by admin (%s): %s", c.User.Name, u.Name) - ctx.Flash.Success(ctx.Tr("admin.users.deletion_success")) - ctx.JSON(200, map[string]interface{}{ + c.Flash.Success(c.Tr("admin.users.deletion_success")) + c.JSON(200, map[string]interface{}{ "redirect": setting.AppSubURL + "/admin/users", }) } diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go index f5c4a95c6..996a83bf9 100644 --- a/routers/api/v1/admin/org.go +++ b/routers/api/v1/admin/org.go @@ -14,9 +14,9 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Administration-Organizations#create-a-new-organization -func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) { - u := user.GetUserByParams(ctx) - if ctx.Written() { +func CreateOrg(c *context.APIContext, form api.CreateOrgOption) { + u := user.GetUserByParams(c) + if c.Written() { return } @@ -33,12 +33,12 @@ func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) { if models.IsErrUserAlreadyExist(err) || models.IsErrNameReserved(err) || models.IsErrNamePatternNotAllowed(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "CreateOrganization", err) + c.Error(500, "CreateOrganization", err) } return } - ctx.JSON(201, convert.ToOrganization(org)) + c.JSON(201, convert.ToOrganization(org)) } diff --git a/routers/api/v1/admin/org_repo.go b/routers/api/v1/admin/org_repo.go index 02ff35baa..7abad1a8c 100644 --- a/routers/api/v1/admin/org_repo.go +++ b/routers/api/v1/admin/org_repo.go @@ -10,41 +10,41 @@ import ( "github.com/gogits/gogs/pkg/context" ) -func GetRepositoryByParams(ctx *context.APIContext) *models.Repository { - repo, err := models.GetRepositoryByName(ctx.Org.Team.OrgID, ctx.Params(":reponame")) +func GetRepositoryByParams(c *context.APIContext) *models.Repository { + repo, err := models.GetRepositoryByName(c.Org.Team.OrgID, c.Params(":reponame")) if err != nil { if errors.IsRepoNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetRepositoryByName", err) + c.Error(500, "GetRepositoryByName", err) } return nil } return repo } -func AddTeamRepository(ctx *context.APIContext) { - repo := GetRepositoryByParams(ctx) - if ctx.Written() { +func AddTeamRepository(c *context.APIContext) { + repo := GetRepositoryByParams(c) + if c.Written() { return } - if err := ctx.Org.Team.AddRepository(repo); err != nil { - ctx.Error(500, "AddRepository", err) + if err := c.Org.Team.AddRepository(repo); err != nil { + c.Error(500, "AddRepository", err) return } - ctx.Status(204) + c.Status(204) } -func RemoveTeamRepository(ctx *context.APIContext) { - repo := GetRepositoryByParams(ctx) - if ctx.Written() { +func RemoveTeamRepository(c *context.APIContext) { + repo := GetRepositoryByParams(c) + if c.Written() { return } - if err := ctx.Org.Team.RemoveRepository(repo.ID); err != nil { - ctx.Error(500, "RemoveRepository", err) + if err := c.Org.Team.RemoveRepository(repo.ID); err != nil { + c.Error(500, "RemoveRepository", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/admin/org_team.go b/routers/api/v1/admin/org_team.go index dfed0c86a..7ec6c08a1 100644 --- a/routers/api/v1/admin/org_team.go +++ b/routers/api/v1/admin/org_team.go @@ -13,48 +13,48 @@ import ( "github.com/gogits/gogs/routers/api/v1/user" ) -func CreateTeam(ctx *context.APIContext, form api.CreateTeamOption) { +func CreateTeam(c *context.APIContext, form api.CreateTeamOption) { team := &models.Team{ - OrgID: ctx.Org.Organization.ID, + OrgID: c.Org.Organization.ID, Name: form.Name, Description: form.Description, Authorize: models.ParseAccessMode(form.Permission), } if err := models.NewTeam(team); err != nil { if models.IsErrTeamAlreadyExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "NewTeam", err) + c.Error(500, "NewTeam", err) } return } - ctx.JSON(201, convert.ToTeam(team)) + c.JSON(201, convert.ToTeam(team)) } -func AddTeamMember(ctx *context.APIContext) { - u := user.GetUserByParams(ctx) - if ctx.Written() { +func AddTeamMember(c *context.APIContext) { + u := user.GetUserByParams(c) + if c.Written() { return } - if err := ctx.Org.Team.AddMember(u.ID); err != nil { - ctx.Error(500, "AddMember", err) + if err := c.Org.Team.AddMember(u.ID); err != nil { + c.Error(500, "AddMember", err) return } - ctx.Status(204) + c.Status(204) } -func RemoveTeamMember(ctx *context.APIContext) { - u := user.GetUserByParams(ctx) - if ctx.Written() { +func RemoveTeamMember(c *context.APIContext) { + u := user.GetUserByParams(c) + if c.Written() { return } - if err := ctx.Org.Team.RemoveMember(u.ID); err != nil { - ctx.Error(500, "RemoveMember", err) + if err := c.Org.Team.RemoveMember(u.ID); err != nil { + c.Error(500, "RemoveMember", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/admin/repo.go b/routers/api/v1/admin/repo.go index 8b1999372..6c8e8e8d1 100644 --- a/routers/api/v1/admin/repo.go +++ b/routers/api/v1/admin/repo.go @@ -13,11 +13,11 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Administration-Repositories#create-a-new-repository -func CreateRepo(ctx *context.APIContext, form api.CreateRepoOption) { - owner := user.GetUserByParams(ctx) - if ctx.Written() { +func CreateRepo(c *context.APIContext, form api.CreateRepoOption) { + owner := user.GetUserByParams(c) + if c.Written() { return } - repo.CreateUserRepo(ctx, owner, form) + repo.CreateUserRepo(c, owner, form) } diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 7565ab2c4..8776217d6 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -16,7 +16,7 @@ import ( "github.com/gogits/gogs/routers/api/v1/user" ) -func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, loginName string) { +func parseLoginSource(c *context.APIContext, u *models.User, sourceID int64, loginName string) { if sourceID == 0 { return } @@ -24,9 +24,9 @@ func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, l source, err := models.GetLoginSourceByID(sourceID) if err != nil { if models.IsErrLoginSourceNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetLoginSourceByID", err) + c.Error(500, "GetLoginSourceByID", err) } return } @@ -37,7 +37,7 @@ func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, l } // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-new-user -func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { +func CreateUser(c *context.APIContext, form api.CreateUserOption) { u := &models.User{ Name: form.Username, FullName: form.FullName, @@ -47,8 +47,8 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { LoginType: models.LOGIN_PLAIN, } - parseLoginSource(ctx, u, form.SourceID, form.LoginName) - if ctx.Written() { + parseLoginSource(c, u, form.SourceID, form.LoginName) + if c.Written() { return } @@ -57,31 +57,31 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { models.IsErrEmailAlreadyUsed(err) || models.IsErrNameReserved(err) || models.IsErrNamePatternNotAllowed(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "CreateUser", err) + c.Error(500, "CreateUser", err) } return } - log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name) + log.Trace("Account created by admin (%s): %s", c.User.Name, u.Name) // Send email notification. if form.SendNotify && setting.MailService != nil { - mailer.SendRegisterNotifyMail(ctx.Context.Context, models.NewMailerUser(u)) + mailer.SendRegisterNotifyMail(c.Context.Context, models.NewMailerUser(u)) } - ctx.JSON(201, u.APIFormat()) + c.JSON(201, u.APIFormat()) } // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#edit-an-existing-user -func EditUser(ctx *context.APIContext, form api.EditUserOption) { - u := user.GetUserByParams(ctx) - if ctx.Written() { +func EditUser(c *context.APIContext, form api.EditUserOption) { + u := user.GetUserByParams(c) + if c.Written() { return } - parseLoginSource(ctx, u, form.SourceID, form.LoginName) - if ctx.Written() { + parseLoginSource(c, u, form.SourceID, form.LoginName) + if c.Written() { return } @@ -89,7 +89,7 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) { u.Passwd = form.Password var err error if u.Salt, err = models.GetUserSalt(); err != nil { - ctx.Error(500, "UpdateUser", err) + c.Error(500, "UpdateUser", err) return } u.EncodePasswd() @@ -118,43 +118,43 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) { if err := models.UpdateUser(u); err != nil { if models.IsErrEmailAlreadyUsed(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "UpdateUser", err) + c.Error(500, "UpdateUser", err) } return } - log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name) + log.Trace("Account profile updated by admin (%s): %s", c.User.Name, u.Name) - ctx.JSON(200, u.APIFormat()) + c.JSON(200, u.APIFormat()) } // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#delete-a-user -func DeleteUser(ctx *context.APIContext) { - u := user.GetUserByParams(ctx) - if ctx.Written() { +func DeleteUser(c *context.APIContext) { + u := user.GetUserByParams(c) + if c.Written() { return } if err := models.DeleteUser(u); err != nil { if models.IsErrUserOwnRepos(err) || models.IsErrUserHasOrgs(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "DeleteUser", err) + c.Error(500, "DeleteUser", err) } return } - log.Trace("Account deleted by admin(%s): %s", ctx.User.Name, u.Name) + log.Trace("Account deleted by admin(%s): %s", c.User.Name, u.Name) - ctx.Status(204) + c.Status(204) } // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-public-key-for-user -func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) { - u := user.GetUserByParams(ctx) - if ctx.Written() { +func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) { + u := user.GetUserByParams(c) + if c.Written() { return } - user.CreateUserPublicKey(ctx, form, u.ID) + user.CreateUserPublicKey(c, form, u.ID) } diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index b54e47b7d..35ca861a8 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -24,9 +24,9 @@ import ( ) func repoAssignment() macaron.Handler { - return func(ctx *context.APIContext) { - userName := ctx.Params(":username") - repoName := ctx.Params(":reponame") + return func(c *context.APIContext) { + userName := c.Params(":username") + repoName := c.Params(":reponame") var ( owner *models.User @@ -34,87 +34,87 @@ func repoAssignment() macaron.Handler { ) // Check if the user is the same as the repository owner. - if ctx.IsLogged && ctx.User.LowerName == strings.ToLower(userName) { - owner = ctx.User + if c.IsLogged && c.User.LowerName == strings.ToLower(userName) { + owner = c.User } else { owner, err = models.GetUserByName(userName) if err != nil { if errors.IsUserNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return } } - ctx.Repo.Owner = owner + c.Repo.Owner = owner // Get repository. repo, err := models.GetRepositoryByName(owner.ID, repoName) if err != nil { if errors.IsRepoNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetRepositoryByName", err) + c.Error(500, "GetRepositoryByName", err) } return } else if err = repo.GetOwner(); err != nil { - ctx.Error(500, "GetOwner", err) + c.Error(500, "GetOwner", err) return } - if ctx.IsLogged && ctx.User.IsAdmin { - ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER + if c.IsLogged && c.User.IsAdmin { + c.Repo.AccessMode = models.ACCESS_MODE_OWNER } else { - mode, err := models.AccessLevel(ctx.User.ID, repo) + mode, err := models.AccessLevel(c.User.ID, repo) if err != nil { - ctx.Error(500, "AccessLevel", err) + c.Error(500, "AccessLevel", err) return } - ctx.Repo.AccessMode = mode + c.Repo.AccessMode = mode } - if !ctx.Repo.HasAccess() { - ctx.Status(404) + if !c.Repo.HasAccess() { + c.Status(404) return } - ctx.Repo.Repository = repo + c.Repo.Repository = repo } } // Contexter middleware already checks token for user sign in process. func reqToken() macaron.Handler { - return func(ctx *context.Context) { - if !ctx.IsLogged { - ctx.Error(401) + return func(c *context.Context) { + if !c.IsLogged { + c.Error(401) return } } } func reqBasicAuth() macaron.Handler { - return func(ctx *context.Context) { - if !ctx.IsBasicAuth { - ctx.Error(401) + return func(c *context.Context) { + if !c.IsBasicAuth { + c.Error(401) return } } } func reqAdmin() macaron.Handler { - return func(ctx *context.Context) { - if !ctx.IsLogged || !ctx.User.IsAdmin { - ctx.Error(403) + return func(c *context.Context) { + if !c.IsLogged || !c.User.IsAdmin { + c.Error(403) return } } } func reqRepoWriter() macaron.Handler { - return func(ctx *context.Context) { - if !ctx.Repo.IsWriter() { - ctx.Error(403) + return func(c *context.Context) { + if !c.Repo.IsWriter() { + c.Error(403) return } } @@ -131,29 +131,29 @@ func orgAssignment(args ...bool) macaron.Handler { if len(args) > 1 { assignTeam = args[1] } - return func(ctx *context.APIContext) { - ctx.Org = new(context.APIOrganization) + return func(c *context.APIContext) { + c.Org = new(context.APIOrganization) var err error if assignOrg { - ctx.Org.Organization, err = models.GetUserByName(ctx.Params(":orgname")) + c.Org.Organization, err = models.GetUserByName(c.Params(":orgname")) if err != nil { if errors.IsUserNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return } } if assignTeam { - ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid")) + c.Org.Team, err = models.GetTeamByID(c.ParamsInt64(":teamid")) if err != nil { if errors.IsUserNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetTeamById", err) + c.Error(500, "GetTeamById", err) } return } @@ -161,9 +161,9 @@ func orgAssignment(args ...bool) macaron.Handler { } } -func mustEnableIssues(ctx *context.APIContext) { - if !ctx.Repo.Repository.EnableIssues || ctx.Repo.Repository.EnableExternalTracker { - ctx.Status(404) +func mustEnableIssues(c *context.APIContext) { + if !c.Repo.Repository.EnableIssues || c.Repo.Repository.EnableExternalTracker { + c.Status(404) return } } @@ -323,8 +323,8 @@ func RegisterRoutes(m *macaron.Macaron) { m.Combo("/teams").Get(org.ListTeams) }, orgAssignment(true)) - m.Any("/*", func(ctx *context.Context) { - ctx.Error(404) + m.Any("/*", func(c *context.Context) { + c.Error(404) }) m.Group("/admin", func() { diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index d4419d577..98bfd7d05 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -12,31 +12,31 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document -func Markdown(ctx *context.APIContext, form api.MarkdownOption) { - if ctx.HasApiError() { - ctx.Error(422, "", ctx.GetErrMsg()) +func Markdown(c *context.APIContext, form api.MarkdownOption) { + if c.HasApiError() { + c.Error(422, "", c.GetErrMsg()) return } if len(form.Text) == 0 { - ctx.Write([]byte("")) + c.Write([]byte("")) return } switch form.Mode { case "gfm": - ctx.Write(markup.Markdown([]byte(form.Text), form.Context, nil)) + c.Write(markup.Markdown([]byte(form.Text), form.Context, nil)) default: - ctx.Write(markup.RawMarkdown([]byte(form.Text), "")) + c.Write(markup.RawMarkdown([]byte(form.Text), "")) } } // https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-a-markdown-document-in-raw-mode -func MarkdownRaw(ctx *context.APIContext) { - body, err := ctx.Req.Body().Bytes() +func MarkdownRaw(c *context.APIContext) { + body, err := c.Req.Body().Bytes() if err != nil { - ctx.Error(422, "", err) + c.Error(422, "", err) return } - ctx.Write(markup.RawMarkdown(body, "")) + c.Write(markup.RawMarkdown(body, "")) } diff --git a/routers/api/v1/org/org.go b/routers/api/v1/org/org.go index 3b3576a72..107fc19ca 100644 --- a/routers/api/v1/org/org.go +++ b/routers/api/v1/org/org.go @@ -13,9 +13,9 @@ import ( "github.com/gogits/gogs/routers/api/v1/user" ) -func listUserOrgs(ctx *context.APIContext, u *models.User, all bool) { +func listUserOrgs(c *context.APIContext, u *models.User, all bool) { if err := u.GetOrganizations(all); err != nil { - ctx.Error(500, "GetOrganizations", err) + c.Error(500, "GetOrganizations", err) return } @@ -23,33 +23,33 @@ func listUserOrgs(ctx *context.APIContext, u *models.User, all bool) { for i := range u.Orgs { apiOrgs[i] = convert.ToOrganization(u.Orgs[i]) } - ctx.JSON(200, &apiOrgs) + c.JSON(200, &apiOrgs) } // https://github.com/gogits/go-gogs-client/wiki/Organizations#list-your-organizations -func ListMyOrgs(ctx *context.APIContext) { - listUserOrgs(ctx, ctx.User, true) +func ListMyOrgs(c *context.APIContext) { + listUserOrgs(c, c.User, true) } // https://github.com/gogits/go-gogs-client/wiki/Organizations#list-user-organizations -func ListUserOrgs(ctx *context.APIContext) { - u := user.GetUserByParams(ctx) - if ctx.Written() { +func ListUserOrgs(c *context.APIContext) { + u := user.GetUserByParams(c) + if c.Written() { return } - listUserOrgs(ctx, u, false) + listUserOrgs(c, u, false) } // https://github.com/gogits/go-gogs-client/wiki/Organizations#get-an-organization -func Get(ctx *context.APIContext) { - ctx.JSON(200, convert.ToOrganization(ctx.Org.Organization)) +func Get(c *context.APIContext) { + c.JSON(200, convert.ToOrganization(c.Org.Organization)) } // https://github.com/gogits/go-gogs-client/wiki/Organizations#edit-an-organization -func Edit(ctx *context.APIContext, form api.EditOrgOption) { - org := ctx.Org.Organization - if !org.IsOwnedBy(ctx.User.ID) { - ctx.Status(403) +func Edit(c *context.APIContext, form api.EditOrgOption) { + org := c.Org.Organization + if !org.IsOwnedBy(c.User.ID) { + c.Status(403) return } @@ -58,9 +58,9 @@ func Edit(ctx *context.APIContext, form api.EditOrgOption) { org.Website = form.Website org.Location = form.Location if err := models.UpdateUser(org); err != nil { - ctx.Error(500, "UpdateUser", err) + c.Error(500, "UpdateUser", err) return } - ctx.JSON(200, convert.ToOrganization(org)) + c.JSON(200, convert.ToOrganization(org)) } diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index 8b0f40087..a952ea53b 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -11,10 +11,10 @@ import ( "github.com/gogits/gogs/routers/api/v1/convert" ) -func ListTeams(ctx *context.APIContext) { - org := ctx.Org.Organization +func ListTeams(c *context.APIContext) { + org := c.Org.Organization if err := org.GetTeams(); err != nil { - ctx.Error(500, "GetTeams", err) + c.Error(500, "GetTeams", err) return } @@ -22,5 +22,5 @@ func ListTeams(ctx *context.APIContext) { for i := range org.Teams { apiTeams[i] = convert.ToTeam(org.Teams[i]) } - ctx.JSON(200, apiTeams) + c.JSON(200, apiTeams) } diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index df9500404..3d5e646c8 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -13,43 +13,43 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Repositories#get-branch -func GetBranch(ctx *context.APIContext) { - branch, err := ctx.Repo.Repository.GetBranch(ctx.Params("*")) +func GetBranch(c *context.APIContext) { + branch, err := c.Repo.Repository.GetBranch(c.Params("*")) if err != nil { if models.IsErrBranchNotExist(err) { - ctx.Error(404, "GetBranch", err) + c.Error(404, "GetBranch", err) } else { - ctx.Error(500, "GetBranch", err) + c.Error(500, "GetBranch", err) } return } - c, err := branch.GetCommit() + commit, err := branch.GetCommit() if err != nil { - ctx.Error(500, "GetCommit", err) + c.Error(500, "GetCommit", err) return } - ctx.JSON(200, convert.ToBranch(branch, c)) + c.JSON(200, convert.ToBranch(branch, commit)) } // https://github.com/gogits/go-gogs-client/wiki/Repositories#list-branches -func ListBranches(ctx *context.APIContext) { - branches, err := ctx.Repo.Repository.GetBranches() +func ListBranches(c *context.APIContext) { + branches, err := c.Repo.Repository.GetBranches() if err != nil { - ctx.Error(500, "GetBranches", err) + c.Error(500, "GetBranches", err) return } apiBranches := make([]*api.Branch, len(branches)) for i := range branches { - c, err := branches[i].GetCommit() + commit, err := branches[i].GetCommit() if err != nil { - ctx.Error(500, "GetCommit", err) + c.Error(500, "GetCommit", err) return } - apiBranches[i] = convert.ToBranch(branches[i], c) + apiBranches[i] = convert.ToBranch(branches[i], commit) } - ctx.JSON(200, &apiBranches) + c.JSON(200, &apiBranches) } diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index ff109be51..d295ac0fb 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -12,13 +12,13 @@ import ( "github.com/gogits/gogs/pkg/context" ) -func ListCollaborators(ctx *context.APIContext) { - collaborators, err := ctx.Repo.Repository.GetCollaborators() +func ListCollaborators(c *context.APIContext) { + collaborators, err := c.Repo.Repository.GetCollaborators() if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetCollaborators", err) + c.Error(500, "GetCollaborators", err) } return } @@ -27,68 +27,68 @@ func ListCollaborators(ctx *context.APIContext) { for i := range collaborators { apiCollaborators[i] = collaborators[i].APIFormat() } - ctx.JSON(200, &apiCollaborators) + c.JSON(200, &apiCollaborators) } -func AddCollaborator(ctx *context.APIContext, form api.AddCollaboratorOption) { - collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) +func AddCollaborator(c *context.APIContext, form api.AddCollaboratorOption) { + collaborator, err := models.GetUserByName(c.Params(":collaborator")) if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return } - if err := ctx.Repo.Repository.AddCollaborator(collaborator); err != nil { - ctx.Error(500, "AddCollaborator", err) + if err := c.Repo.Repository.AddCollaborator(collaborator); err != nil { + c.Error(500, "AddCollaborator", err) return } if form.Permission != nil { - if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(collaborator.ID, models.ParseAccessMode(*form.Permission)); err != nil { - ctx.Error(500, "ChangeCollaborationAccessMode", err) + if err := c.Repo.Repository.ChangeCollaborationAccessMode(collaborator.ID, models.ParseAccessMode(*form.Permission)); err != nil { + c.Error(500, "ChangeCollaborationAccessMode", err) return } } - ctx.Status(204) + c.Status(204) } -func IsCollaborator(ctx *context.APIContext) { - collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) +func IsCollaborator(c *context.APIContext) { + collaborator, err := models.GetUserByName(c.Params(":collaborator")) if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return } - if !ctx.Repo.Repository.IsCollaborator(collaborator.ID) { - ctx.Status(404) + if !c.Repo.Repository.IsCollaborator(collaborator.ID) { + c.Status(404) } else { - ctx.Status(204) + c.Status(204) } } -func DeleteCollaborator(ctx *context.APIContext) { - collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) +func DeleteCollaborator(c *context.APIContext) { + collaborator, err := models.GetUserByName(c.Params(":collaborator")) if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return } - if err := ctx.Repo.Repository.DeleteCollaboration(collaborator.ID); err != nil { - ctx.Error(500, "DeleteCollaboration", err) + if err := c.Repo.Repository.DeleteCollaboration(collaborator.ID); err != nil { + c.Error(500, "DeleteCollaboration", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 81c399f68..df6a4857b 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -13,60 +13,60 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-raw-content -func GetRawFile(ctx *context.APIContext) { - if !ctx.Repo.HasAccess() { - ctx.Status(404) +func GetRawFile(c *context.APIContext) { + if !c.Repo.HasAccess() { + c.Status(404) return } - if ctx.Repo.Repository.IsBare { - ctx.Status(404) + if c.Repo.Repository.IsBare { + c.Status(404) return } - blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath) + blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath) if err != nil { if git.IsErrNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetBlobByPath", err) + c.Error(500, "GetBlobByPath", err) } return } - if err = repo.ServeBlob(ctx.Context, blob); err != nil { - ctx.Error(500, "ServeBlob", err) + if err = repo.ServeBlob(c.Context, blob); err != nil { + c.Error(500, "ServeBlob", err) } } // https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-archive -func GetArchive(ctx *context.APIContext) { - repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) +func GetArchive(c *context.APIContext) { + repoPath := models.RepoPath(c.Params(":username"), c.Params(":reponame")) gitRepo, err := git.OpenRepository(repoPath) if err != nil { - ctx.Error(500, "OpenRepository", err) + c.Error(500, "OpenRepository", err) return } - ctx.Repo.GitRepo = gitRepo + c.Repo.GitRepo = gitRepo - repo.Download(ctx.Context) + repo.Download(c.Context) } -func GetEditorconfig(ctx *context.APIContext) { - ec, err := ctx.Repo.GetEditorconfig() +func GetEditorconfig(c *context.APIContext) { + ec, err := c.Repo.GetEditorconfig() if err != nil { if git.IsErrNotExist(err) { - ctx.Error(404, "GetEditorconfig", err) + c.Error(404, "GetEditorconfig", err) } else { - ctx.Error(500, "GetEditorconfig", err) + c.Error(500, "GetEditorconfig", err) } return } - fileName := ctx.Params("filename") + fileName := c.Params("filename") def := ec.GetDefinitionForFilename(fileName) if def == nil { - ctx.Error(404, "GetDefinitionForFilename", err) + c.Error(404, "GetDefinitionForFilename", err) return } - ctx.JSON(200, def) + c.JSON(200, def) } diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index 6a4ec85f0..7c2b293e2 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -18,34 +18,34 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Repositories#list-hooks -func ListHooks(ctx *context.APIContext) { - hooks, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID) +func ListHooks(c *context.APIContext) { + hooks, err := models.GetWebhooksByRepoID(c.Repo.Repository.ID) if err != nil { - ctx.Error(500, "GetWebhooksByRepoID", err) + c.Error(500, "GetWebhooksByRepoID", err) return } apiHooks := make([]*api.Hook, len(hooks)) for i := range hooks { - apiHooks[i] = convert.ToHook(ctx.Repo.RepoLink, hooks[i]) + apiHooks[i] = convert.ToHook(c.Repo.RepoLink, hooks[i]) } - ctx.JSON(200, &apiHooks) + c.JSON(200, &apiHooks) } // https://github.com/gogits/go-gogs-client/wiki/Repositories#create-a-hook -func CreateHook(ctx *context.APIContext, form api.CreateHookOption) { +func CreateHook(c *context.APIContext, form api.CreateHookOption) { if !models.IsValidHookTaskType(form.Type) { - ctx.Error(422, "", "Invalid hook type") + c.Error(422, "", "Invalid hook type") return } for _, name := range []string{"url", "content_type"} { if _, ok := form.Config[name]; !ok { - ctx.Error(422, "", "Missing config option: "+name) + c.Error(422, "", "Missing config option: "+name) return } } if !models.IsValidHookContentType(form.Config["content_type"]) { - ctx.Error(422, "", "Invalid content type") + c.Error(422, "", "Invalid content type") return } @@ -53,7 +53,7 @@ func CreateHook(ctx *context.APIContext, form api.CreateHookOption) { form.Events = []string{"push"} } w := &models.Webhook{ - RepoID: ctx.Repo.Repository.ID, + RepoID: c.Repo.Repository.ID, URL: form.Config["url"], ContentType: models.ToHookContentType(form.Config["content_type"]), Secret: form.Config["secret"], @@ -76,7 +76,7 @@ func CreateHook(ctx *context.APIContext, form api.CreateHookOption) { if w.HookTaskType == models.SLACK { channel, ok := form.Config["channel"] if !ok { - ctx.Error(422, "", "Missing config option: channel") + c.Error(422, "", "Missing config option: channel") return } meta, err := json.Marshal(&models.SlackMeta{ @@ -86,31 +86,31 @@ func CreateHook(ctx *context.APIContext, form api.CreateHookOption) { Color: form.Config["color"], }) if err != nil { - ctx.Error(500, "slack: JSON marshal failed", err) + c.Error(500, "slack: JSON marshal failed", err) return } w.Meta = string(meta) } if err := w.UpdateEvent(); err != nil { - ctx.Error(500, "UpdateEvent", err) + c.Error(500, "UpdateEvent", err) return } else if err := models.CreateWebhook(w); err != nil { - ctx.Error(500, "CreateWebhook", err) + c.Error(500, "CreateWebhook", err) return } - ctx.JSON(201, convert.ToHook(ctx.Repo.RepoLink, w)) + c.JSON(201, convert.ToHook(c.Repo.RepoLink, w)) } // https://github.com/gogits/go-gogs-client/wiki/Repositories#edit-a-hook -func EditHook(ctx *context.APIContext, form api.EditHookOption) { - w, err := models.GetWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) +func EditHook(c *context.APIContext, form api.EditHookOption) { + w, err := models.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if errors.IsWebhookNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetWebhookOfRepoByID", err) + c.Error(500, "GetWebhookOfRepoByID", err) } return } @@ -121,7 +121,7 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) { } if ct, ok := form.Config["content_type"]; ok { if !models.IsValidHookContentType(ct) { - ctx.Error(422, "", "Invalid content type") + c.Error(422, "", "Invalid content type") return } w.ContentType = models.ToHookContentType(ct) @@ -136,7 +136,7 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) { Color: form.Config["color"], }) if err != nil { - ctx.Error(500, "slack: JSON marshal failed", err) + c.Error(500, "slack: JSON marshal failed", err) return } w.Meta = string(meta) @@ -160,7 +160,7 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) { w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PULL_REQUEST)) w.Release = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_RELEASE)) if err = w.UpdateEvent(); err != nil { - ctx.Error(500, "UpdateEvent", err) + c.Error(500, "UpdateEvent", err) return } @@ -169,18 +169,18 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) { } if err := models.UpdateWebhook(w); err != nil { - ctx.Error(500, "UpdateWebhook", err) + c.Error(500, "UpdateWebhook", err) return } - ctx.JSON(200, convert.ToHook(ctx.Repo.RepoLink, w)) + c.JSON(200, convert.ToHook(c.Repo.RepoLink, w)) } -func DeleteHook(ctx *context.APIContext) { - if err := models.DeleteWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { - ctx.Error(500, "DeleteWebhookByRepoID", err) +func DeleteHook(c *context.APIContext) { + if err := models.DeleteWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil { + c.Error(500, "DeleteWebhookByRepoID", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 5e233a201..4a0726334 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -16,16 +16,16 @@ import ( "github.com/gogits/gogs/pkg/setting" ) -func listIssues(ctx *context.APIContext, opts *models.IssuesOptions) { +func listIssues(c *context.APIContext, opts *models.IssuesOptions) { issues, err := models.Issues(opts) if err != nil { - ctx.Error(500, "Issues", err) + c.Error(500, "Issues", err) return } count, err := models.IssuesCount(opts) if err != nil { - ctx.Error(500, "IssuesCount", err) + c.Error(500, "IssuesCount", err) return } @@ -33,64 +33,64 @@ func listIssues(ctx *context.APIContext, opts *models.IssuesOptions) { apiIssues := make([]*api.Issue, len(issues)) for i := range issues { if err = issues[i].LoadAttributes(); err != nil { - ctx.Error(500, "LoadAttributes", err) + c.Error(500, "LoadAttributes", err) return } apiIssues[i] = issues[i].APIFormat() } - ctx.SetLinkHeader(int(count), setting.UI.IssuePagingNum) - ctx.JSON(200, &apiIssues) + c.SetLinkHeader(int(count), setting.UI.IssuePagingNum) + c.JSON(200, &apiIssues) } -func ListUserIssues(ctx *context.APIContext) { +func ListUserIssues(c *context.APIContext) { opts := models.IssuesOptions{ - AssigneeID: ctx.User.ID, - Page: ctx.QueryInt("page"), + AssigneeID: c.User.ID, + Page: c.QueryInt("page"), } - listIssues(ctx, &opts) + listIssues(c, &opts) } -func ListIssues(ctx *context.APIContext) { +func ListIssues(c *context.APIContext) { opts := models.IssuesOptions{ - RepoID: ctx.Repo.Repository.ID, - Page: ctx.QueryInt("page"), + RepoID: c.Repo.Repository.ID, + Page: c.QueryInt("page"), } - listIssues(ctx, &opts) + listIssues(c, &opts) } -func GetIssue(ctx *context.APIContext) { - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) +func GetIssue(c *context.APIContext) { + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { if errors.IsIssueNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetIssueByIndex", err) + c.Error(500, "GetIssueByIndex", err) } return } - ctx.JSON(200, issue.APIFormat()) + c.JSON(200, issue.APIFormat()) } -func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { +func CreateIssue(c *context.APIContext, form api.CreateIssueOption) { issue := &models.Issue{ - RepoID: ctx.Repo.Repository.ID, + RepoID: c.Repo.Repository.ID, Title: form.Title, - PosterID: ctx.User.ID, - Poster: ctx.User, + PosterID: c.User.ID, + Poster: c.User, Content: form.Body, } - if ctx.Repo.IsWriter() { + if c.Repo.IsWriter() { if len(form.Assignee) > 0 { assignee, err := models.GetUserByName(form.Assignee) if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", form.Assignee)) + c.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", form.Assignee)) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return } @@ -101,14 +101,14 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { form.Labels = nil } - if err := models.NewIssue(ctx.Repo.Repository, issue, form.Labels, nil); err != nil { - ctx.Error(500, "NewIssue", err) + if err := models.NewIssue(c.Repo.Repository, issue, form.Labels, nil); err != nil { + c.Error(500, "NewIssue", err) return } if form.Closed { - if err := issue.ChangeStatus(ctx.User, ctx.Repo.Repository, true); err != nil { - ctx.Error(500, "ChangeStatus", err) + if err := issue.ChangeStatus(c.User, c.Repo.Repository, true); err != nil { + c.Error(500, "ChangeStatus", err) return } } @@ -117,25 +117,25 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { var err error issue, err = models.GetIssueByID(issue.ID) if err != nil { - ctx.Error(500, "GetIssueByID", err) + c.Error(500, "GetIssueByID", err) return } - ctx.JSON(201, issue.APIFormat()) + c.JSON(201, issue.APIFormat()) } -func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) +func EditIssue(c *context.APIContext, form api.EditIssueOption) { + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { if errors.IsIssueNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetIssueByIndex", err) + c.Error(500, "GetIssueByIndex", err) } return } - if !issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter() { - ctx.Status(403) + if !issue.IsPoster(c.User.ID) && !c.Repo.IsWriter() { + c.Status(403) return } @@ -146,7 +146,7 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { issue.Content = *form.Body } - if ctx.Repo.IsWriter() && form.Assignee != nil && + if c.Repo.IsWriter() && form.Assignee != nil && (issue.Assignee == nil || issue.Assignee.LowerName != strings.ToLower(*form.Assignee)) { if len(*form.Assignee) == 0 { issue.AssigneeID = 0 @@ -154,9 +154,9 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { assignee, err := models.GetUserByName(*form.Assignee) if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", fmt.Sprintf("assignee does not exist: [name: %s]", *form.Assignee)) + c.Error(422, "", fmt.Sprintf("assignee does not exist: [name: %s]", *form.Assignee)) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return } @@ -164,27 +164,27 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { } if err = models.UpdateIssueUserByAssignee(issue); err != nil { - ctx.Error(500, "UpdateIssueUserByAssignee", err) + c.Error(500, "UpdateIssueUserByAssignee", err) return } } - if ctx.Repo.IsWriter() && form.Milestone != nil && + if c.Repo.IsWriter() && form.Milestone != nil && issue.MilestoneID != *form.Milestone { oldMilestoneID := issue.MilestoneID issue.MilestoneID = *form.Milestone - if err = models.ChangeMilestoneAssign(ctx.User, issue, oldMilestoneID); err != nil { - ctx.Error(500, "ChangeMilestoneAssign", err) + if err = models.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil { + c.Error(500, "ChangeMilestoneAssign", err) return } } if err = models.UpdateIssue(issue); err != nil { - ctx.Error(500, "UpdateIssue", err) + c.Error(500, "UpdateIssue", err) return } if form.State != nil { - if err = issue.ChangeStatus(ctx.User, ctx.Repo.Repository, api.STATE_CLOSED == api.StateType(*form.State)); err != nil { - ctx.Error(500, "ChangeStatus", err) + if err = issue.ChangeStatus(c.User, c.Repo.Repository, api.STATE_CLOSED == api.StateType(*form.State)); err != nil { + c.Error(500, "ChangeStatus", err) return } } @@ -192,8 +192,8 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { // Refetch from database to assign some automatic values issue, err = models.GetIssueByID(issue.ID) if err != nil { - ctx.Error(500, "GetIssueByID", err) + c.Error(500, "GetIssueByID", err) return } - ctx.JSON(201, issue.APIFormat()) + c.JSON(201, issue.APIFormat()) } diff --git a/routers/api/v1/repo/issue_comment.go b/routers/api/v1/repo/issue_comment.go index 04ecd216f..4a057d763 100644 --- a/routers/api/v1/repo/issue_comment.go +++ b/routers/api/v1/repo/issue_comment.go @@ -12,22 +12,22 @@ import ( "github.com/gogits/gogs/pkg/context" ) -func ListIssueComments(ctx *context.APIContext) { +func ListIssueComments(c *context.APIContext) { var since time.Time - if len(ctx.Query("since")) > 0 { - since, _ = time.Parse(time.RFC3339, ctx.Query("since")) + if len(c.Query("since")) > 0 { + since, _ = time.Parse(time.RFC3339, c.Query("since")) } // comments,err:=models.GetCommentsByIssueIDSince(, since) - issue, err := models.GetRawIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) + issue, err := models.GetRawIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { - ctx.Error(500, "GetRawIssueByIndex", err) + c.Error(500, "GetRawIssueByIndex", err) return } comments, err := models.GetCommentsByIssueIDSince(issue.ID, since.Unix()) if err != nil { - ctx.Error(500, "GetCommentsByIssueIDSince", err) + c.Error(500, "GetCommentsByIssueIDSince", err) return } @@ -35,18 +35,18 @@ func ListIssueComments(ctx *context.APIContext) { for i := range comments { apiComments[i] = comments[i].APIFormat() } - ctx.JSON(200, &apiComments) + c.JSON(200, &apiComments) } -func ListRepoIssueComments(ctx *context.APIContext) { +func ListRepoIssueComments(c *context.APIContext) { var since time.Time - if len(ctx.Query("since")) > 0 { - since, _ = time.Parse(time.RFC3339, ctx.Query("since")) + if len(c.Query("since")) > 0 { + since, _ = time.Parse(time.RFC3339, c.Query("since")) } - comments, err := models.GetCommentsByRepoIDSince(ctx.Repo.Repository.ID, since.Unix()) + comments, err := models.GetCommentsByRepoIDSince(c.Repo.Repository.ID, since.Unix()) if err != nil { - ctx.Error(500, "GetCommentsByRepoIDSince", err) + c.Error(500, "GetCommentsByRepoIDSince", err) return } @@ -54,75 +54,75 @@ func ListRepoIssueComments(ctx *context.APIContext) { for i := range comments { apiComments[i] = comments[i].APIFormat() } - ctx.JSON(200, &apiComments) + c.JSON(200, &apiComments) } -func CreateIssueComment(ctx *context.APIContext, form api.CreateIssueCommentOption) { - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) +func CreateIssueComment(c *context.APIContext, form api.CreateIssueCommentOption) { + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { - ctx.Error(500, "GetIssueByIndex", err) + c.Error(500, "GetIssueByIndex", err) return } - comment, err := models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Body, nil) + comment, err := models.CreateIssueComment(c.User, c.Repo.Repository, issue, form.Body, nil) if err != nil { - ctx.Error(500, "CreateIssueComment", err) + c.Error(500, "CreateIssueComment", err) return } - ctx.JSON(201, comment.APIFormat()) + c.JSON(201, comment.APIFormat()) } -func EditIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) { - comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) +func EditIssueComment(c *context.APIContext, form api.EditIssueCommentOption) { + comment, err := models.GetCommentByID(c.ParamsInt64(":id")) if err != nil { if models.IsErrCommentNotExist(err) { - ctx.Error(404, "GetCommentByID", err) + c.Error(404, "GetCommentByID", err) } else { - ctx.Error(500, "GetCommentByID", err) + c.Error(500, "GetCommentByID", err) } return } - if ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin() { - ctx.Status(403) + if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() { + c.Status(403) return } else if comment.Type != models.COMMENT_TYPE_COMMENT { - ctx.Status(204) + c.Status(204) return } oldContent := comment.Content comment.Content = form.Body - if err := models.UpdateComment(ctx.User, comment, oldContent); err != nil { - ctx.Error(500, "UpdateComment", err) + if err := models.UpdateComment(c.User, comment, oldContent); err != nil { + c.Error(500, "UpdateComment", err) return } - ctx.JSON(200, comment.APIFormat()) + c.JSON(200, comment.APIFormat()) } -func DeleteIssueComment(ctx *context.APIContext) { - comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) +func DeleteIssueComment(c *context.APIContext) { + comment, err := models.GetCommentByID(c.ParamsInt64(":id")) if err != nil { if models.IsErrCommentNotExist(err) { - ctx.Error(404, "GetCommentByID", err) + c.Error(404, "GetCommentByID", err) } else { - ctx.Error(500, "GetCommentByID", err) + c.Error(500, "GetCommentByID", err) } return } - if ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin() { - ctx.Status(403) + if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() { + c.Status(403) return } else if comment.Type != models.COMMENT_TYPE_COMMENT { - ctx.Status(204) + c.Status(204) return } - if err = models.DeleteCommentByID(ctx.User, comment.ID); err != nil { - ctx.Error(500, "DeleteCommentByID", err) + if err = models.DeleteCommentByID(c.User, comment.ID); err != nil { + c.Error(500, "DeleteCommentByID", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go index 06c52dc58..f3f2d7300 100644 --- a/routers/api/v1/repo/issue_label.go +++ b/routers/api/v1/repo/issue_label.go @@ -12,13 +12,13 @@ import ( "github.com/gogits/gogs/pkg/context" ) -func ListIssueLabels(ctx *context.APIContext) { - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) +func ListIssueLabels(c *context.APIContext) { + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { if errors.IsIssueNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetIssueByIndex", err) + c.Error(500, "GetIssueByIndex", err) } return } @@ -27,39 +27,39 @@ func ListIssueLabels(ctx *context.APIContext) { for i := range issue.Labels { apiLabels[i] = issue.Labels[i].APIFormat() } - ctx.JSON(200, &apiLabels) + c.JSON(200, &apiLabels) } -func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { - if !ctx.Repo.IsWriter() { - ctx.Status(403) +func AddIssueLabels(c *context.APIContext, form api.IssueLabelsOption) { + if !c.Repo.IsWriter() { + c.Status(403) return } - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { if errors.IsIssueNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetIssueByIndex", err) + c.Error(500, "GetIssueByIndex", err) } return } - labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) + labels, err := models.GetLabelsInRepoByIDs(c.Repo.Repository.ID, form.Labels) if err != nil { - ctx.Error(500, "GetLabelsInRepoByIDs", err) + c.Error(500, "GetLabelsInRepoByIDs", err) return } - if err = issue.AddLabels(ctx.User, labels); err != nil { - ctx.Error(500, "AddLabels", err) + if err = issue.AddLabels(c.User, labels); err != nil { + c.Error(500, "AddLabels", err) return } labels, err = models.GetLabelsByIssueID(issue.ID) if err != nil { - ctx.Error(500, "GetLabelsByIssueID", err) + c.Error(500, "GetLabelsByIssueID", err) return } @@ -67,73 +67,73 @@ func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { for i := range labels { apiLabels[i] = issue.Labels[i].APIFormat() } - ctx.JSON(200, &apiLabels) + c.JSON(200, &apiLabels) } -func DeleteIssueLabel(ctx *context.APIContext) { - if !ctx.Repo.IsWriter() { - ctx.Status(403) +func DeleteIssueLabel(c *context.APIContext) { + if !c.Repo.IsWriter() { + c.Status(403) return } - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { if errors.IsIssueNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetIssueByIndex", err) + c.Error(500, "GetIssueByIndex", err) } return } - label, err := models.GetLabelOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) + label, err := models.GetLabelOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if models.IsErrLabelNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetLabelInRepoByID", err) + c.Error(500, "GetLabelInRepoByID", err) } return } if err := models.DeleteIssueLabel(issue, label); err != nil { - ctx.Error(500, "DeleteIssueLabel", err) + c.Error(500, "DeleteIssueLabel", err) return } - ctx.Status(204) + c.Status(204) } -func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { - if !ctx.Repo.IsWriter() { - ctx.Status(403) +func ReplaceIssueLabels(c *context.APIContext, form api.IssueLabelsOption) { + if !c.Repo.IsWriter() { + c.Status(403) return } - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { if errors.IsIssueNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetIssueByIndex", err) + c.Error(500, "GetIssueByIndex", err) } return } - labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) + labels, err := models.GetLabelsInRepoByIDs(c.Repo.Repository.ID, form.Labels) if err != nil { - ctx.Error(500, "GetLabelsInRepoByIDs", err) + c.Error(500, "GetLabelsInRepoByIDs", err) return } if err := issue.ReplaceLabels(labels); err != nil { - ctx.Error(500, "ReplaceLabels", err) + c.Error(500, "ReplaceLabels", err) return } labels, err = models.GetLabelsByIssueID(issue.ID) if err != nil { - ctx.Error(500, "GetLabelsByIssueID", err) + c.Error(500, "GetLabelsByIssueID", err) return } @@ -141,29 +141,29 @@ func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { for i := range labels { apiLabels[i] = issue.Labels[i].APIFormat() } - ctx.JSON(200, &apiLabels) + c.JSON(200, &apiLabels) } -func ClearIssueLabels(ctx *context.APIContext) { - if !ctx.Repo.IsWriter() { - ctx.Status(403) +func ClearIssueLabels(c *context.APIContext) { + if !c.Repo.IsWriter() { + c.Status(403) return } - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { if errors.IsIssueNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetIssueByIndex", err) + c.Error(500, "GetIssueByIndex", err) } return } - if err := issue.ClearLabels(ctx.User); err != nil { - ctx.Error(500, "ClearLabels", err) + if err := issue.ClearLabels(c.User); err != nil { + c.Error(500, "ClearLabels", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index 4ac180f1a..901df4c7e 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -20,95 +20,95 @@ func composeDeployKeysAPILink(repoPath string) string { } // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#list-deploy-keys -func ListDeployKeys(ctx *context.APIContext) { - keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) +func ListDeployKeys(c *context.APIContext) { + keys, err := models.ListDeployKeys(c.Repo.Repository.ID) if err != nil { - ctx.Error(500, "ListDeployKeys", err) + c.Error(500, "ListDeployKeys", err) return } - apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name) + apiLink := composeDeployKeysAPILink(c.Repo.Owner.Name + "/" + c.Repo.Repository.Name) apiKeys := make([]*api.DeployKey, len(keys)) for i := range keys { if err = keys[i].GetContent(); err != nil { - ctx.Error(500, "GetContent", err) + c.Error(500, "GetContent", err) return } apiKeys[i] = convert.ToDeployKey(apiLink, keys[i]) } - ctx.JSON(200, &apiKeys) + c.JSON(200, &apiKeys) } // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#get-a-deploy-key -func GetDeployKey(ctx *context.APIContext) { - key, err := models.GetDeployKeyByID(ctx.ParamsInt64(":id")) +func GetDeployKey(c *context.APIContext) { + key, err := models.GetDeployKeyByID(c.ParamsInt64(":id")) if err != nil { if models.IsErrDeployKeyNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetDeployKeyByID", err) + c.Error(500, "GetDeployKeyByID", err) } return } if err = key.GetContent(); err != nil { - ctx.Error(500, "GetContent", err) + c.Error(500, "GetContent", err) return } - apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name) - ctx.JSON(200, convert.ToDeployKey(apiLink, key)) + apiLink := composeDeployKeysAPILink(c.Repo.Owner.Name + "/" + c.Repo.Repository.Name) + c.JSON(200, convert.ToDeployKey(apiLink, key)) } -func HandleCheckKeyStringError(ctx *context.APIContext, err error) { +func HandleCheckKeyStringError(c *context.APIContext, err error) { if models.IsErrKeyUnableVerify(err) { - ctx.Error(422, "", "Unable to verify key content") + c.Error(422, "", "Unable to verify key content") } else { - ctx.Error(422, "", fmt.Errorf("Invalid key content: %v", err)) + c.Error(422, "", fmt.Errorf("Invalid key content: %v", err)) } } -func HandleAddKeyError(ctx *context.APIContext, err error) { +func HandleAddKeyError(c *context.APIContext, err error) { switch { case models.IsErrKeyAlreadyExist(err): - ctx.Error(422, "", "Key content has been used as non-deploy key") + c.Error(422, "", "Key content has been used as non-deploy key") case models.IsErrKeyNameAlreadyUsed(err): - ctx.Error(422, "", "Key title has been used") + c.Error(422, "", "Key title has been used") default: - ctx.Error(500, "AddKey", err) + c.Error(500, "AddKey", err) } } // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#add-a-new-deploy-key -func CreateDeployKey(ctx *context.APIContext, form api.CreateKeyOption) { +func CreateDeployKey(c *context.APIContext, form api.CreateKeyOption) { content, err := models.CheckPublicKeyString(form.Key) if err != nil { - HandleCheckKeyStringError(ctx, err) + HandleCheckKeyStringError(c, err) return } - key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content) + key, err := models.AddDeployKey(c.Repo.Repository.ID, form.Title, content) if err != nil { - HandleAddKeyError(ctx, err) + HandleAddKeyError(c, err) return } key.Content = content - apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name) - ctx.JSON(201, convert.ToDeployKey(apiLink, key)) + apiLink := composeDeployKeysAPILink(c.Repo.Owner.Name + "/" + c.Repo.Repository.Name) + c.JSON(201, convert.ToDeployKey(apiLink, key)) } // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key -func DeleteDeploykey(ctx *context.APIContext) { - if err := models.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { +func DeleteDeploykey(c *context.APIContext) { + if err := models.DeleteDeployKey(c.User, c.ParamsInt64(":id")); err != nil { if models.IsErrKeyAccessDenied(err) { - ctx.Error(403, "", "You do not have access to this key") + c.Error(403, "", "You do not have access to this key") } else { - ctx.Error(500, "DeleteDeployKey", err) + c.Error(500, "DeleteDeployKey", err) } return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/repo/label.go b/routers/api/v1/repo/label.go index 32c1924b2..289f40a41 100644 --- a/routers/api/v1/repo/label.go +++ b/routers/api/v1/repo/label.go @@ -11,10 +11,10 @@ import ( "github.com/gogits/gogs/pkg/context" ) -func ListLabels(ctx *context.APIContext) { - labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID) +func ListLabels(c *context.APIContext) { + labels, err := models.GetLabelsByRepoID(c.Repo.Repository.ID) if err != nil { - ctx.Error(500, "GetLabelsByRepoID", err) + c.Error(500, "GetLabelsByRepoID", err) return } @@ -22,53 +22,53 @@ func ListLabels(ctx *context.APIContext) { for i := range labels { apiLabels[i] = labels[i].APIFormat() } - ctx.JSON(200, &apiLabels) + c.JSON(200, &apiLabels) } -func GetLabel(ctx *context.APIContext) { - label, err := models.GetLabelOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) +func GetLabel(c *context.APIContext) { + label, err := models.GetLabelOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if models.IsErrLabelNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetLabelByRepoID", err) + c.Error(500, "GetLabelByRepoID", err) } return } - ctx.JSON(200, label.APIFormat()) + c.JSON(200, label.APIFormat()) } -func CreateLabel(ctx *context.APIContext, form api.CreateLabelOption) { - if !ctx.Repo.IsWriter() { - ctx.Status(403) +func CreateLabel(c *context.APIContext, form api.CreateLabelOption) { + if !c.Repo.IsWriter() { + c.Status(403) return } label := &models.Label{ Name: form.Name, Color: form.Color, - RepoID: ctx.Repo.Repository.ID, + RepoID: c.Repo.Repository.ID, } if err := models.NewLabels(label); err != nil { - ctx.Error(500, "NewLabel", err) + c.Error(500, "NewLabel", err) return } - ctx.JSON(201, label.APIFormat()) + c.JSON(201, label.APIFormat()) } -func EditLabel(ctx *context.APIContext, form api.EditLabelOption) { - if !ctx.Repo.IsWriter() { - ctx.Status(403) +func EditLabel(c *context.APIContext, form api.EditLabelOption) { + if !c.Repo.IsWriter() { + c.Status(403) return } - label, err := models.GetLabelOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) + label, err := models.GetLabelOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if models.IsErrLabelNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetLabelByRepoID", err) + c.Error(500, "GetLabelByRepoID", err) } return } @@ -80,22 +80,22 @@ func EditLabel(ctx *context.APIContext, form api.EditLabelOption) { label.Color = *form.Color } if err := models.UpdateLabel(label); err != nil { - ctx.Handle(500, "UpdateLabel", err) + c.Handle(500, "UpdateLabel", err) return } - ctx.JSON(200, label.APIFormat()) + c.JSON(200, label.APIFormat()) } -func DeleteLabel(ctx *context.APIContext) { - if !ctx.Repo.IsWriter() { - ctx.Status(403) +func DeleteLabel(c *context.APIContext) { + if !c.Repo.IsWriter() { + c.Status(403) return } - if err := models.DeleteLabel(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { - ctx.Error(500, "DeleteLabel", err) + if err := models.DeleteLabel(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil { + c.Error(500, "DeleteLabel", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go index 5133d19b3..baf8eb2f5 100644 --- a/routers/api/v1/repo/milestone.go +++ b/routers/api/v1/repo/milestone.go @@ -13,10 +13,10 @@ import ( "github.com/gogits/gogs/pkg/context" ) -func ListMilestones(ctx *context.APIContext) { - milestones, err := models.GetMilestonesByRepoID(ctx.Repo.Repository.ID) +func ListMilestones(c *context.APIContext) { + milestones, err := models.GetMilestonesByRepoID(c.Repo.Repository.ID) if err != nil { - ctx.Error(500, "GetMilestonesByRepoID", err) + c.Error(500, "GetMilestonesByRepoID", err) return } @@ -24,49 +24,49 @@ func ListMilestones(ctx *context.APIContext) { for i := range milestones { apiMilestones[i] = milestones[i].APIFormat() } - ctx.JSON(200, &apiMilestones) + c.JSON(200, &apiMilestones) } -func GetMilestone(ctx *context.APIContext) { - milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) +func GetMilestone(c *context.APIContext) { + milestone, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if models.IsErrMilestoneNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetMilestoneByRepoID", err) + c.Error(500, "GetMilestoneByRepoID", err) } return } - ctx.JSON(200, milestone.APIFormat()) + c.JSON(200, milestone.APIFormat()) } -func CreateMilestone(ctx *context.APIContext, form api.CreateMilestoneOption) { +func CreateMilestone(c *context.APIContext, form api.CreateMilestoneOption) { if form.Deadline == nil { defaultDeadline, _ := time.ParseInLocation("2006-01-02", "9999-12-31", time.Local) form.Deadline = &defaultDeadline } milestone := &models.Milestone{ - RepoID: ctx.Repo.Repository.ID, + RepoID: c.Repo.Repository.ID, Name: form.Title, Content: form.Description, Deadline: *form.Deadline, } if err := models.NewMilestone(milestone); err != nil { - ctx.Error(500, "NewMilestone", err) + c.Error(500, "NewMilestone", err) return } - ctx.JSON(201, milestone.APIFormat()) + c.JSON(201, milestone.APIFormat()) } -func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) { - milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) +func EditMilestone(c *context.APIContext, form api.EditMilestoneOption) { + milestone, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if models.IsErrMilestoneNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetMilestoneByRepoID", err) + c.Error(500, "GetMilestoneByRepoID", err) } return } @@ -83,21 +83,21 @@ func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) { if form.State != nil { if err = milestone.ChangeStatus(api.STATE_CLOSED == api.StateType(*form.State)); err != nil { - ctx.Error(500, "ChangeStatus", err) + c.Error(500, "ChangeStatus", err) return } } else if err = models.UpdateMilestone(milestone); err != nil { - ctx.Handle(500, "UpdateMilestone", err) + c.Handle(500, "UpdateMilestone", err) return } - ctx.JSON(200, milestone.APIFormat()) + c.JSON(200, milestone.APIFormat()) } -func DeleteMilestone(ctx *context.APIContext) { - if err := models.DeleteMilestoneOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { - ctx.Error(500, "DeleteMilestoneByRepoID", err) +func DeleteMilestone(c *context.APIContext) { + if err := models.DeleteMilestoneOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil { + c.Error(500, "DeleteMilestoneByRepoID", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index f86905d49..1095f08d3 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -20,27 +20,27 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories -func Search(ctx *context.APIContext) { +func Search(c *context.APIContext) { opts := &models.SearchRepoOptions{ - Keyword: path.Base(ctx.Query("q")), - OwnerID: ctx.QueryInt64("uid"), - PageSize: convert.ToCorrectPageSize(ctx.QueryInt("limit")), + Keyword: path.Base(c.Query("q")), + OwnerID: c.QueryInt64("uid"), + PageSize: convert.ToCorrectPageSize(c.QueryInt("limit")), } // Check visibility. - if ctx.IsLogged && opts.OwnerID > 0 { - if ctx.User.ID == opts.OwnerID { + if c.IsLogged && opts.OwnerID > 0 { + if c.User.ID == opts.OwnerID { opts.Private = true } else { u, err := models.GetUserByID(opts.OwnerID) if err != nil { - ctx.JSON(500, map[string]interface{}{ + c.JSON(500, map[string]interface{}{ "ok": false, "error": err.Error(), }) return } - if u.IsOrganization() && u.IsOwnedBy(ctx.User.ID) { + if u.IsOrganization() && u.IsOwnedBy(c.User.ID) { opts.Private = true } // FIXME: how about collaborators? @@ -49,7 +49,7 @@ func Search(ctx *context.APIContext) { repos, count, err := models.SearchRepositoryByName(opts) if err != nil { - ctx.JSON(500, map[string]interface{}{ + c.JSON(500, map[string]interface{}{ "ok": false, "error": err.Error(), }) @@ -59,7 +59,7 @@ func Search(ctx *context.APIContext) { results := make([]*api.Repository, len(repos)) for i := range repos { if err = repos[i].GetOwner(); err != nil { - ctx.JSON(500, map[string]interface{}{ + c.JSON(500, map[string]interface{}{ "ok": false, "error": err.Error(), }) @@ -71,17 +71,17 @@ func Search(ctx *context.APIContext) { } } - ctx.SetLinkHeader(int(count), setting.API.MaxResponseItems) - ctx.JSON(200, map[string]interface{}{ + c.SetLinkHeader(int(count), setting.API.MaxResponseItems) + c.JSON(200, map[string]interface{}{ "ok": true, "data": results, }) } -func listUserRepositories(ctx *context.APIContext, username string) { +func listUserRepositories(c *context.APIContext, username string) { user, err := models.GetUserByName(username) if err != nil { - ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) + c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) return } @@ -89,32 +89,32 @@ func listUserRepositories(ctx *context.APIContext, username string) { // or an organization isn't a member of. var ownRepos []*models.Repository if user.IsOrganization() { - ownRepos, _, err = user.GetUserRepositories(ctx.User.ID, 1, user.NumRepos) + ownRepos, _, err = user.GetUserRepositories(c.User.ID, 1, user.NumRepos) } else { ownRepos, err = models.GetUserRepositories(&models.UserRepoOptions{ UserID: user.ID, - Private: ctx.User.ID == user.ID, + Private: c.User.ID == user.ID, Page: 1, PageSize: user.NumRepos, }) } if err != nil { - ctx.Error(500, "GetUserRepositories", err) + c.Error(500, "GetUserRepositories", err) return } - if ctx.User.ID != user.ID { + if c.User.ID != user.ID { repos := make([]*api.Repository, len(ownRepos)) for i := range ownRepos { repos[i] = ownRepos[i].APIFormat(&api.Permission{true, true, true}) } - ctx.JSON(200, &repos) + c.JSON(200, &repos) return } accessibleRepos, err := user.GetRepositoryAccesses() if err != nil { - ctx.Error(500, "GetRepositoryAccesses", err) + c.Error(500, "GetRepositoryAccesses", err) return } @@ -134,23 +134,23 @@ func listUserRepositories(ctx *context.APIContext, username string) { i++ } - ctx.JSON(200, &repos) + c.JSON(200, &repos) } -func ListMyRepos(ctx *context.APIContext) { - listUserRepositories(ctx, ctx.User.Name) +func ListMyRepos(c *context.APIContext) { + listUserRepositories(c, c.User.Name) } -func ListUserRepositories(ctx *context.APIContext) { - listUserRepositories(ctx, ctx.Params(":username")) +func ListUserRepositories(c *context.APIContext) { + listUserRepositories(c, c.Params(":username")) } -func ListOrgRepositories(ctx *context.APIContext) { - listUserRepositories(ctx, ctx.Params(":org")) +func ListOrgRepositories(c *context.APIContext) { + listUserRepositories(c, c.Params(":org")) } -func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateRepoOption) { - repo, err := models.CreateRepository(ctx.User, owner, models.CreateRepoOptions{ +func CreateUserRepo(c *context.APIContext, owner *models.User, opt api.CreateRepoOption) { + repo, err := models.CreateRepository(c.User, owner, models.CreateRepoOptions{ Name: opt.Name, Description: opt.Description, Gitignores: opt.Gitignores, @@ -163,104 +163,104 @@ func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateR if models.IsErrRepoAlreadyExist(err) || models.IsErrNameReserved(err) || models.IsErrNamePatternNotAllowed(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { if repo != nil { - if err = models.DeleteRepository(ctx.User.ID, repo.ID); err != nil { + if err = models.DeleteRepository(c.User.ID, repo.ID); err != nil { log.Error(2, "DeleteRepository: %v", err) } } - ctx.Error(500, "CreateRepository", err) + c.Error(500, "CreateRepository", err) } return } - ctx.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) + c.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) } // https://github.com/gogits/go-gogs-client/wiki/Repositories#create -func Create(ctx *context.APIContext, opt api.CreateRepoOption) { +func Create(c *context.APIContext, opt api.CreateRepoOption) { // Shouldn't reach this condition, but just in case. - if ctx.User.IsOrganization() { - ctx.Error(422, "", "not allowed creating repository for organization") + if c.User.IsOrganization() { + c.Error(422, "", "not allowed creating repository for organization") return } - CreateUserRepo(ctx, ctx.User, opt) + CreateUserRepo(c, c.User, opt) } -func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) { - org, err := models.GetOrgByName(ctx.Params(":org")) +func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) { + org, err := models.GetOrgByName(c.Params(":org")) if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetOrgByName", err) + c.Error(500, "GetOrgByName", err) } return } - if !org.IsOwnedBy(ctx.User.ID) { - ctx.Error(403, "", "Given user is not owner of organization.") + if !org.IsOwnedBy(c.User.ID) { + c.Error(403, "", "Given user is not owner of organization.") return } - CreateUserRepo(ctx, org, opt) + CreateUserRepo(c, org, opt) } // https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate -func Migrate(ctx *context.APIContext, f form.MigrateRepo) { - ctxUser := ctx.User +func Migrate(c *context.APIContext, f form.MigrateRepo) { + ctxUser := c.User // Not equal means context user is an organization, // or is another user/organization if current user is admin. if f.Uid != ctxUser.ID { org, err := models.GetUserByID(f.Uid) if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetUserByID", err) + c.Error(500, "GetUserByID", err) } return } else if !org.IsOrganization() { - ctx.Error(403, "", "Given user is not an organization") + c.Error(403, "", "Given user is not an organization") return } ctxUser = org } - if ctx.HasError() { - ctx.Error(422, "", ctx.GetErrMsg()) + if c.HasError() { + c.Error(422, "", c.GetErrMsg()) return } - if ctxUser.IsOrganization() && !ctx.User.IsAdmin { + if ctxUser.IsOrganization() && !c.User.IsAdmin { // Check ownership of organization. - if !ctxUser.IsOwnedBy(ctx.User.ID) { - ctx.Error(403, "", "Given user is not owner of organization") + if !ctxUser.IsOwnedBy(c.User.ID) { + c.Error(403, "", "Given user is not owner of organization") return } } - remoteAddr, err := f.ParseRemoteAddr(ctx.User) + remoteAddr, err := f.ParseRemoteAddr(c.User) if err != nil { if models.IsErrInvalidCloneAddr(err) { addrErr := err.(models.ErrInvalidCloneAddr) switch { case addrErr.IsURLError: - ctx.Error(422, "", err) + c.Error(422, "", err) case addrErr.IsPermissionDenied: - ctx.Error(422, "", "You are not allowed to import local repositories") + c.Error(422, "", "You are not allowed to import local repositories") case addrErr.IsInvalidPath: - ctx.Error(422, "", "Invalid local path, it does not exist or not a directory") + c.Error(422, "", "Invalid local path, it does not exist or not a directory") default: - ctx.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error()) + c.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error()) } } else { - ctx.Error(500, "ParseRemoteAddr", err) + c.Error(500, "ParseRemoteAddr", err) } return } - repo, err := models.MigrateRepository(ctx.User, ctxUser, models.MigrateRepoOptions{ + repo, err := models.MigrateRepository(c.User, ctxUser, models.MigrateRepoOptions{ Name: f.RepoName, Description: f.Description, IsPrivate: f.Private || setting.Repository.ForcePrivate, @@ -275,34 +275,34 @@ func Migrate(ctx *context.APIContext, f form.MigrateRepo) { } if errors.IsReachLimitOfRepo(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "MigrateRepository", models.HandleMirrorCredentials(err.Error(), true)) + c.Error(500, "MigrateRepository", models.HandleMirrorCredentials(err.Error(), true)) } return } log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName) - ctx.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) + c.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) } -func parseOwnerAndRepo(ctx *context.APIContext) (*models.User, *models.Repository) { - owner, err := models.GetUserByName(ctx.Params(":username")) +func parseOwnerAndRepo(c *context.APIContext) (*models.User, *models.Repository) { + owner, err := models.GetUserByName(c.Params(":username")) if err != nil { if errors.IsUserNotExist(err) { - ctx.Error(422, "", err) + c.Error(422, "", err) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return nil, nil } - repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame")) + repo, err := models.GetRepositoryByName(owner.ID, c.Params(":reponame")) if err != nil { if errors.IsRepoNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetRepositoryByName", err) + c.Error(500, "GetRepositoryByName", err) } return nil, nil } @@ -311,72 +311,72 @@ func parseOwnerAndRepo(ctx *context.APIContext) (*models.User, *models.Repositor } // https://github.com/gogits/go-gogs-client/wiki/Repositories#get -func Get(ctx *context.APIContext) { - _, repo := parseOwnerAndRepo(ctx) - if ctx.Written() { +func Get(c *context.APIContext) { + _, repo := parseOwnerAndRepo(c) + if c.Written() { return } - ctx.JSON(200, repo.APIFormat(&api.Permission{ - Admin: ctx.Repo.IsAdmin(), - Push: ctx.Repo.IsWriter(), + c.JSON(200, repo.APIFormat(&api.Permission{ + Admin: c.Repo.IsAdmin(), + Push: c.Repo.IsWriter(), Pull: true, })) } // https://github.com/gogits/go-gogs-client/wiki/Repositories#delete -func Delete(ctx *context.APIContext) { - owner, repo := parseOwnerAndRepo(ctx) - if ctx.Written() { +func Delete(c *context.APIContext) { + owner, repo := parseOwnerAndRepo(c) + if c.Written() { return } - if owner.IsOrganization() && !owner.IsOwnedBy(ctx.User.ID) { - ctx.Error(403, "", "Given user is not owner of organization.") + if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) { + c.Error(403, "", "Given user is not owner of organization.") return } if err := models.DeleteRepository(owner.ID, repo.ID); err != nil { - ctx.Error(500, "DeleteRepository", err) + c.Error(500, "DeleteRepository", err) return } log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name) - ctx.Status(204) + c.Status(204) } -func ListForks(ctx *context.APIContext) { - forks, err := ctx.Repo.Repository.GetForks() +func ListForks(c *context.APIContext) { + forks, err := c.Repo.Repository.GetForks() if err != nil { - ctx.Error(500, "GetForks", err) + c.Error(500, "GetForks", err) return } apiForks := make([]*api.Repository, len(forks)) for i := range forks { if err := forks[i].GetOwner(); err != nil { - ctx.Error(500, "GetOwner", err) + c.Error(500, "GetOwner", err) return } apiForks[i] = forks[i].APIFormat(&api.Permission{ - Admin: ctx.User.IsAdminOfRepo(forks[i]), - Push: ctx.User.IsWriterOfRepo(forks[i]), + Admin: c.User.IsAdminOfRepo(forks[i]), + Push: c.User.IsWriterOfRepo(forks[i]), Pull: true, }) } - ctx.JSON(200, &apiForks) + c.JSON(200, &apiForks) } -func MirrorSync(ctx *context.APIContext) { - _, repo := parseOwnerAndRepo(ctx) - if ctx.Written() { +func MirrorSync(c *context.APIContext) { + _, repo := parseOwnerAndRepo(c) + if c.Written() { return } else if !repo.IsMirror { - ctx.Status(404) + c.Status(404) return } go models.MirrorQueue.Add(repo.ID) - ctx.Status(202) + c.Status(202) } diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index ebba7f099..bda1e23ff 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -12,10 +12,10 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Users#list-access-tokens-for-a-user -func ListAccessTokens(ctx *context.APIContext) { - tokens, err := models.ListAccessTokens(ctx.User.ID) +func ListAccessTokens(c *context.APIContext) { + tokens, err := models.ListAccessTokens(c.User.ID) if err != nil { - ctx.Error(500, "ListAccessTokens", err) + c.Error(500, "ListAccessTokens", err) return } @@ -23,18 +23,18 @@ func ListAccessTokens(ctx *context.APIContext) { for i := range tokens { apiTokens[i] = &api.AccessToken{tokens[i].Name, tokens[i].Sha1} } - ctx.JSON(200, &apiTokens) + c.JSON(200, &apiTokens) } // https://github.com/gogits/go-gogs-client/wiki/Users#create-a-access-token -func CreateAccessToken(ctx *context.APIContext, form api.CreateAccessTokenOption) { +func CreateAccessToken(c *context.APIContext, form api.CreateAccessTokenOption) { t := &models.AccessToken{ - UID: ctx.User.ID, + UID: c.User.ID, Name: form.Name, } if err := models.NewAccessToken(t); err != nil { - ctx.Error(500, "NewAccessToken", err) + c.Error(500, "NewAccessToken", err) return } - ctx.JSON(201, &api.AccessToken{t.Name, t.Sha1}) + c.JSON(201, &api.AccessToken{t.Name, t.Sha1}) } diff --git a/routers/api/v1/user/email.go b/routers/api/v1/user/email.go index c8b4ce1b5..7c527a1a3 100644 --- a/routers/api/v1/user/email.go +++ b/routers/api/v1/user/email.go @@ -14,30 +14,30 @@ import ( ) // https://github.com/gogits/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user -func ListEmails(ctx *context.APIContext) { - emails, err := models.GetEmailAddresses(ctx.User.ID) +func ListEmails(c *context.APIContext) { + emails, err := models.GetEmailAddresses(c.User.ID) if err != nil { - ctx.Error(500, "GetEmailAddresses", err) + c.Error(500, "GetEmailAddresses", err) return } apiEmails := make([]*api.Email, len(emails)) for i := range emails { apiEmails[i] = convert.ToEmail(emails[i]) } - ctx.JSON(200, &apiEmails) + c.JSON(200, &apiEmails) } // https://github.com/gogits/go-gogs-client/wiki/Users-Emails#add-email-addresses -func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { +func AddEmail(c *context.APIContext, form api.CreateEmailOption) { if len(form.Emails) == 0 { - ctx.Status(422) + c.Status(422) return } emails := make([]*models.EmailAddress, len(form.Emails)) for i := range form.Emails { emails[i] = &models.EmailAddress{ - UID: ctx.User.ID, + UID: c.User.ID, Email: form.Emails[i], IsActivated: !setting.Service.RegisterEmailConfirm, } @@ -45,9 +45,9 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { if err := models.AddEmailAddresses(emails); err != nil { if models.IsErrEmailAlreadyUsed(err) { - ctx.Error(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email) + c.Error(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email) } else { - ctx.Error(500, "AddEmailAddresses", err) + c.Error(500, "AddEmailAddresses", err) } return } @@ -56,27 +56,27 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { for i := range emails { apiEmails[i] = convert.ToEmail(emails[i]) } - ctx.JSON(201, &apiEmails) + c.JSON(201, &apiEmails) } // https://github.com/gogits/go-gogs-client/wiki/Users-Emails#delete-email-addresses -func DeleteEmail(ctx *context.APIContext, form api.CreateEmailOption) { +func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) { if len(form.Emails) == 0 { - ctx.Status(204) + c.Status(204) return } emails := make([]*models.EmailAddress, len(form.Emails)) for i := range form.Emails { emails[i] = &models.EmailAddress{ - UID: ctx.User.ID, + UID: c.User.ID, Email: form.Emails[i], } } if err := models.DeleteEmailAddresses(emails); err != nil { - ctx.Error(500, "DeleteEmailAddresses", err) + c.Error(500, "DeleteEmailAddresses", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/user/follower.go b/routers/api/v1/user/follower.go index 814f10f41..6bbd4c7e3 100644 --- a/routers/api/v1/user/follower.go +++ b/routers/api/v1/user/follower.go @@ -11,110 +11,110 @@ import ( "github.com/gogits/gogs/pkg/context" ) -func responseApiUsers(ctx *context.APIContext, users []*models.User) { +func responseApiUsers(c *context.APIContext, users []*models.User) { apiUsers := make([]*api.User, len(users)) for i := range users { apiUsers[i] = users[i].APIFormat() } - ctx.JSON(200, &apiUsers) + c.JSON(200, &apiUsers) } -func listUserFollowers(ctx *context.APIContext, u *models.User) { - users, err := u.GetFollowers(ctx.QueryInt("page")) +func listUserFollowers(c *context.APIContext, u *models.User) { + users, err := u.GetFollowers(c.QueryInt("page")) if err != nil { - ctx.Error(500, "GetUserFollowers", err) + c.Error(500, "GetUserFollowers", err) return } - responseApiUsers(ctx, users) + responseApiUsers(c, users) } -func ListMyFollowers(ctx *context.APIContext) { - listUserFollowers(ctx, ctx.User) +func ListMyFollowers(c *context.APIContext) { + listUserFollowers(c, c.User) } // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-followers-of-a-user -func ListFollowers(ctx *context.APIContext) { - u := GetUserByParams(ctx) - if ctx.Written() { +func ListFollowers(c *context.APIContext) { + u := GetUserByParams(c) + if c.Written() { return } - listUserFollowers(ctx, u) + listUserFollowers(c, u) } -func listUserFollowing(ctx *context.APIContext, u *models.User) { - users, err := u.GetFollowing(ctx.QueryInt("page")) +func listUserFollowing(c *context.APIContext, u *models.User) { + users, err := u.GetFollowing(c.QueryInt("page")) if err != nil { - ctx.Error(500, "GetFollowing", err) + c.Error(500, "GetFollowing", err) return } - responseApiUsers(ctx, users) + responseApiUsers(c, users) } -func ListMyFollowing(ctx *context.APIContext) { - listUserFollowing(ctx, ctx.User) +func ListMyFollowing(c *context.APIContext) { + listUserFollowing(c, c.User) } // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-users-followed-by-another-user -func ListFollowing(ctx *context.APIContext) { - u := GetUserByParams(ctx) - if ctx.Written() { +func ListFollowing(c *context.APIContext) { + u := GetUserByParams(c) + if c.Written() { return } - listUserFollowing(ctx, u) + listUserFollowing(c, u) } -func checkUserFollowing(ctx *context.APIContext, u *models.User, followID int64) { +func checkUserFollowing(c *context.APIContext, u *models.User, followID int64) { if u.IsFollowing(followID) { - ctx.Status(204) + c.Status(204) } else { - ctx.Status(404) + c.Status(404) } } // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-you-are-following-a-user -func CheckMyFollowing(ctx *context.APIContext) { - target := GetUserByParams(ctx) - if ctx.Written() { +func CheckMyFollowing(c *context.APIContext) { + target := GetUserByParams(c) + if c.Written() { return } - checkUserFollowing(ctx, ctx.User, target.ID) + checkUserFollowing(c, c.User, target.ID) } // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-one-user-follows-another -func CheckFollowing(ctx *context.APIContext) { - u := GetUserByParams(ctx) - if ctx.Written() { +func CheckFollowing(c *context.APIContext) { + u := GetUserByParams(c) + if c.Written() { return } - target := GetUserByParamsName(ctx, ":target") - if ctx.Written() { + target := GetUserByParamsName(c, ":target") + if c.Written() { return } - checkUserFollowing(ctx, u, target.ID) + checkUserFollowing(c, u, target.ID) } // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#follow-a-user -func Follow(ctx *context.APIContext) { - target := GetUserByParams(ctx) - if ctx.Written() { +func Follow(c *context.APIContext) { + target := GetUserByParams(c) + if c.Written() { return } - if err := models.FollowUser(ctx.User.ID, target.ID); err != nil { - ctx.Error(500, "FollowUser", err) + if err := models.FollowUser(c.User.ID, target.ID); err != nil { + c.Error(500, "FollowUser", err) return } - ctx.Status(204) + c.Status(204) } // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#unfollow-a-user -func Unfollow(ctx *context.APIContext) { - target := GetUserByParams(ctx) - if ctx.Written() { +func Unfollow(c *context.APIContext) { + target := GetUserByParams(c) + if c.Written() { return } - if err := models.UnfollowUser(ctx.User.ID, target.ID); err != nil { - ctx.Error(500, "UnfollowUser", err) + if err := models.UnfollowUser(c.User.ID, target.ID); err != nil { + c.Error(500, "UnfollowUser", err) return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index b9ede63ff..f0c833f58 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -15,13 +15,13 @@ import ( "github.com/gogits/gogs/routers/api/v1/repo" ) -func GetUserByParamsName(ctx *context.APIContext, name string) *models.User { - user, err := models.GetUserByName(ctx.Params(name)) +func GetUserByParamsName(c *context.APIContext, name string) *models.User { + user, err := models.GetUserByName(c.Params(name)) if err != nil { if errors.IsUserNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return nil } @@ -29,18 +29,18 @@ func GetUserByParamsName(ctx *context.APIContext, name string) *models.User { } // GetUserByParams returns user whose name is presented in URL paramenter. -func GetUserByParams(ctx *context.APIContext) *models.User { - return GetUserByParamsName(ctx, ":username") +func GetUserByParams(c *context.APIContext) *models.User { + return GetUserByParamsName(c, ":username") } func composePublicKeysAPILink() string { return setting.AppURL + "api/v1/user/keys/" } -func listPublicKeys(ctx *context.APIContext, uid int64) { +func listPublicKeys(c *context.APIContext, uid int64) { keys, err := models.ListPublicKeys(uid) if err != nil { - ctx.Error(500, "ListPublicKeys", err) + c.Error(500, "ListPublicKeys", err) return } @@ -50,71 +50,71 @@ func listPublicKeys(ctx *context.APIContext, uid int64) { apiKeys[i] = convert.ToPublicKey(apiLink, keys[i]) } - ctx.JSON(200, &apiKeys) + c.JSON(200, &apiKeys) } // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-your-public-keys -func ListMyPublicKeys(ctx *context.APIContext) { - listPublicKeys(ctx, ctx.User.ID) +func ListMyPublicKeys(c *context.APIContext) { + listPublicKeys(c, c.User.ID) } // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user -func ListPublicKeys(ctx *context.APIContext) { - user := GetUserByParams(ctx) - if ctx.Written() { +func ListPublicKeys(c *context.APIContext) { + user := GetUserByParams(c) + if c.Written() { return } - listPublicKeys(ctx, user.ID) + listPublicKeys(c, user.ID) } // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#get-a-single-public-key -func GetPublicKey(ctx *context.APIContext) { - key, err := models.GetPublicKeyByID(ctx.ParamsInt64(":id")) +func GetPublicKey(c *context.APIContext) { + key, err := models.GetPublicKeyByID(c.ParamsInt64(":id")) if err != nil { if models.IsErrKeyNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetPublicKeyByID", err) + c.Error(500, "GetPublicKeyByID", err) } return } apiLink := composePublicKeysAPILink() - ctx.JSON(200, convert.ToPublicKey(apiLink, key)) + c.JSON(200, convert.ToPublicKey(apiLink, key)) } // CreateUserPublicKey creates new public key to given user by ID. -func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid int64) { +func CreateUserPublicKey(c *context.APIContext, form api.CreateKeyOption, uid int64) { content, err := models.CheckPublicKeyString(form.Key) if err != nil { - repo.HandleCheckKeyStringError(ctx, err) + repo.HandleCheckKeyStringError(c, err) return } key, err := models.AddPublicKey(uid, form.Title, content) if err != nil { - repo.HandleAddKeyError(ctx, err) + repo.HandleAddKeyError(c, err) return } apiLink := composePublicKeysAPILink() - ctx.JSON(201, convert.ToPublicKey(apiLink, key)) + c.JSON(201, convert.ToPublicKey(apiLink, key)) } // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#create-a-public-key -func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) { - CreateUserPublicKey(ctx, form, ctx.User.ID) +func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) { + CreateUserPublicKey(c, form, c.User.ID) } // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key -func DeletePublicKey(ctx *context.APIContext) { - if err := models.DeletePublicKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { +func DeletePublicKey(c *context.APIContext) { + if err := models.DeletePublicKey(c.User, c.ParamsInt64(":id")); err != nil { if models.IsErrKeyAccessDenied(err) { - ctx.Error(403, "", "You do not have access to this key") + c.Error(403, "", "You do not have access to this key") } else { - ctx.Error(500, "DeletePublicKey", err) + c.Error(500, "DeletePublicKey", err) } return } - ctx.Status(204) + c.Status(204) } diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index 11c3b8bbf..dbf727def 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -14,11 +14,11 @@ import ( "github.com/gogits/gogs/pkg/context" ) -func Search(ctx *context.APIContext) { +func Search(c *context.APIContext) { opts := &models.SearchUserOptions{ - Keyword: ctx.Query("q"), + Keyword: c.Query("q"), Type: models.USER_TYPE_INDIVIDUAL, - PageSize: com.StrTo(ctx.Query("limit")).MustInt(), + PageSize: com.StrTo(c.Query("limit")).MustInt(), } if opts.PageSize == 0 { opts.PageSize = 10 @@ -26,7 +26,7 @@ func Search(ctx *context.APIContext) { users, _, err := models.SearchUserByName(opts) if err != nil { - ctx.JSON(500, map[string]interface{}{ + c.JSON(500, map[string]interface{}{ "ok": false, "error": err.Error(), }) @@ -41,35 +41,35 @@ func Search(ctx *context.APIContext) { AvatarUrl: users[i].AvatarLink(), FullName: users[i].FullName, } - if ctx.IsLogged { + if c.IsLogged { results[i].Email = users[i].Email } } - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ok": true, "data": results, }) } -func GetInfo(ctx *context.APIContext) { - u, err := models.GetUserByName(ctx.Params(":username")) +func GetInfo(c *context.APIContext) { + u, err := models.GetUserByName(c.Params(":username")) if err != nil { if errors.IsUserNotExist(err) { - ctx.Status(404) + c.Status(404) } else { - ctx.Error(500, "GetUserByName", err) + c.Error(500, "GetUserByName", err) } return } // Hide user e-mail when API caller isn't signed in. - if !ctx.IsLogged { + if !c.IsLogged { u.Email = "" } - ctx.JSON(200, u.APIFormat()) + c.JSON(200, u.APIFormat()) } -func GetAuthenticatedUser(ctx *context.APIContext) { - ctx.JSON(200, ctx.User.APIFormat()) +func GetAuthenticatedUser(c *context.APIContext) { + c.JSON(200, c.User.APIFormat()) } diff --git a/routers/dev/template.go b/routers/dev/template.go index 544b3f5d2..00afa5c4b 100644 --- a/routers/dev/template.go +++ b/routers/dev/template.go @@ -10,15 +10,15 @@ import ( "github.com/gogits/gogs/pkg/setting" ) -func TemplatePreview(ctx *context.Context) { - ctx.Data["User"] = models.User{Name: "Unknown"} - ctx.Data["AppName"] = setting.AppName - ctx.Data["AppVer"] = setting.AppVer - ctx.Data["AppURL"] = setting.AppURL - ctx.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374" - ctx.Data["ActiveCodeLives"] = setting.Service.ActiveCodeLives / 60 - ctx.Data["ResetPwdCodeLives"] = setting.Service.ResetPwdCodeLives / 60 - ctx.Data["CurDbValue"] = "" +func TemplatePreview(c *context.Context) { + c.Data["User"] = models.User{Name: "Unknown"} + c.Data["AppName"] = setting.AppName + c.Data["AppVer"] = setting.AppVer + c.Data["AppURL"] = setting.AppURL + c.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374" + c.Data["ActiveCodeLives"] = setting.Service.ActiveCodeLives / 60 + c.Data["ResetPwdCodeLives"] = setting.Service.ResetPwdCodeLives / 60 + c.Data["CurDbValue"] = "" - ctx.HTML(200, (ctx.Params("*"))) + c.HTML(200, (c.Params("*"))) } diff --git a/routers/home.go b/routers/home.go index 7d9ee27b7..bb43dc581 100644 --- a/routers/home.go +++ b/routers/home.go @@ -20,61 +20,61 @@ const ( EXPLORE_ORGANIZATIONS = "explore/organizations" ) -func Home(ctx *context.Context) { - if ctx.IsLogged { - if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { - ctx.Data["Title"] = ctx.Tr("auth.active_your_account") - ctx.HTML(200, user.ACTIVATE) +func Home(c *context.Context) { + if c.IsLogged { + if !c.User.IsActive && setting.Service.RegisterEmailConfirm { + c.Data["Title"] = c.Tr("auth.active_your_account") + c.HTML(200, user.ACTIVATE) } else { - user.Dashboard(ctx) + user.Dashboard(c) } return } // Check auto-login. - uname := ctx.GetCookie(setting.CookieUserName) + uname := c.GetCookie(setting.CookieUserName) if len(uname) != 0 { - ctx.Redirect(setting.AppSubURL + "/user/login") + c.Redirect(setting.AppSubURL + "/user/login") return } - ctx.Data["PageIsHome"] = true - ctx.HTML(200, HOME) + c.Data["PageIsHome"] = true + c.HTML(200, HOME) } -func ExploreRepos(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("explore") - ctx.Data["PageIsExplore"] = true - ctx.Data["PageIsExploreRepositories"] = true +func ExploreRepos(c *context.Context) { + c.Data["Title"] = c.Tr("explore") + c.Data["PageIsExplore"] = true + c.Data["PageIsExploreRepositories"] = true - page := ctx.QueryInt("page") + page := c.QueryInt("page") if page <= 0 { page = 1 } - keyword := ctx.Query("q") + keyword := c.Query("q") repos, count, err := models.SearchRepositoryByName(&models.SearchRepoOptions{ Keyword: keyword, - UserID: ctx.UserID(), + UserID: c.UserID(), OrderBy: "updated_unix DESC", Page: page, PageSize: setting.UI.ExplorePagingNum, }) if err != nil { - ctx.Handle(500, "SearchRepositoryByName", err) + c.Handle(500, "SearchRepositoryByName", err) return } - ctx.Data["Keyword"] = keyword - ctx.Data["Total"] = count - ctx.Data["Page"] = paginater.New(int(count), setting.UI.ExplorePagingNum, page, 5) + c.Data["Keyword"] = keyword + c.Data["Total"] = count + c.Data["Page"] = paginater.New(int(count), setting.UI.ExplorePagingNum, page, 5) if err = models.RepositoryList(repos).LoadAttributes(); err != nil { - ctx.Handle(500, "LoadAttributes", err) + c.Handle(500, "LoadAttributes", err) return } - ctx.Data["Repos"] = repos + c.Data["Repos"] = repos - ctx.HTML(200, EXPLORE_REPOS) + c.HTML(200, EXPLORE_REPOS) } type UserSearchOptions struct { @@ -86,8 +86,8 @@ type UserSearchOptions struct { TplName string } -func RenderUserSearch(ctx *context.Context, opts *UserSearchOptions) { - page := ctx.QueryInt("page") +func RenderUserSearch(c *context.Context, opts *UserSearchOptions) { + page := c.QueryInt("page") if page <= 1 { page = 1 } @@ -98,11 +98,11 @@ func RenderUserSearch(ctx *context.Context, opts *UserSearchOptions) { err error ) - keyword := ctx.Query("q") + keyword := c.Query("q") if len(keyword) == 0 { users, err = opts.Ranger(page, opts.PageSize) if err != nil { - ctx.Handle(500, "opts.Ranger", err) + c.Handle(500, "opts.Ranger", err) return } count = opts.Counter() @@ -115,24 +115,24 @@ func RenderUserSearch(ctx *context.Context, opts *UserSearchOptions) { PageSize: opts.PageSize, }) if err != nil { - ctx.Handle(500, "SearchUserByName", err) + c.Handle(500, "SearchUserByName", err) return } } - ctx.Data["Keyword"] = keyword - ctx.Data["Total"] = count - ctx.Data["Page"] = paginater.New(int(count), opts.PageSize, page, 5) - ctx.Data["Users"] = users + c.Data["Keyword"] = keyword + c.Data["Total"] = count + c.Data["Page"] = paginater.New(int(count), opts.PageSize, page, 5) + c.Data["Users"] = users - ctx.HTML(200, opts.TplName) + c.HTML(200, opts.TplName) } -func ExploreUsers(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("explore") - ctx.Data["PageIsExplore"] = true - ctx.Data["PageIsExploreUsers"] = true +func ExploreUsers(c *context.Context) { + c.Data["Title"] = c.Tr("explore") + c.Data["PageIsExplore"] = true + c.Data["PageIsExploreUsers"] = true - RenderUserSearch(ctx, &UserSearchOptions{ + RenderUserSearch(c, &UserSearchOptions{ Type: models.USER_TYPE_INDIVIDUAL, Counter: models.CountUsers, Ranger: models.Users, @@ -142,12 +142,12 @@ func ExploreUsers(ctx *context.Context) { }) } -func ExploreOrganizations(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("explore") - ctx.Data["PageIsExplore"] = true - ctx.Data["PageIsExploreOrganizations"] = true +func ExploreOrganizations(c *context.Context) { + c.Data["Title"] = c.Tr("explore") + c.Data["PageIsExplore"] = true + c.Data["PageIsExploreOrganizations"] = true - RenderUserSearch(ctx, &UserSearchOptions{ + RenderUserSearch(c, &UserSearchOptions{ Type: models.USER_TYPE_ORGANIZATION, Counter: models.CountOrganizations, Ranger: models.Organizations, @@ -157,7 +157,7 @@ func ExploreOrganizations(ctx *context.Context) { }) } -func NotFound(ctx *context.Context) { - ctx.Data["Title"] = "Page Not Found" - ctx.Handle(404, "home.NotFound", nil) +func NotFound(c *context.Context) { + c.Data["Title"] = "Page Not Found" + c.NotFound() } diff --git a/routers/org/members.go b/routers/org/members.go index b63f2f473..b529748c6 100644 --- a/routers/org/members.go +++ b/routers/org/members.go @@ -19,105 +19,105 @@ const ( MEMBER_INVITE = "org/member/invite" ) -func Members(ctx *context.Context) { - org := ctx.Org.Organization - ctx.Data["Title"] = org.FullName - ctx.Data["PageIsOrgMembers"] = true +func Members(c *context.Context) { + org := c.Org.Organization + c.Data["Title"] = org.FullName + c.Data["PageIsOrgMembers"] = true if err := org.GetMembers(); err != nil { - ctx.Handle(500, "GetMembers", err) + c.Handle(500, "GetMembers", err) return } - ctx.Data["Members"] = org.Members + c.Data["Members"] = org.Members - ctx.HTML(200, MEMBERS) + c.HTML(200, MEMBERS) } -func MembersAction(ctx *context.Context) { - uid := com.StrTo(ctx.Query("uid")).MustInt64() +func MembersAction(c *context.Context) { + uid := com.StrTo(c.Query("uid")).MustInt64() if uid == 0 { - ctx.Redirect(ctx.Org.OrgLink + "/members") + c.Redirect(c.Org.OrgLink + "/members") return } - org := ctx.Org.Organization + org := c.Org.Organization var err error - switch ctx.Params(":action") { + switch c.Params(":action") { case "private": - if ctx.User.ID != uid && !ctx.Org.IsOwner { - ctx.Error(404) + if c.User.ID != uid && !c.Org.IsOwner { + c.Error(404) return } err = models.ChangeOrgUserStatus(org.ID, uid, false) case "public": - if ctx.User.ID != uid && !ctx.Org.IsOwner { - ctx.Error(404) + if c.User.ID != uid && !c.Org.IsOwner { + c.Error(404) return } err = models.ChangeOrgUserStatus(org.ID, uid, true) case "remove": - if !ctx.Org.IsOwner { - ctx.Error(404) + if !c.Org.IsOwner { + c.Error(404) return } err = org.RemoveMember(uid) if models.IsErrLastOrgOwner(err) { - ctx.Flash.Error(ctx.Tr("form.last_org_owner")) - ctx.Redirect(ctx.Org.OrgLink + "/members") + c.Flash.Error(c.Tr("form.last_org_owner")) + c.Redirect(c.Org.OrgLink + "/members") return } case "leave": - err = org.RemoveMember(ctx.User.ID) + err = org.RemoveMember(c.User.ID) if models.IsErrLastOrgOwner(err) { - ctx.Flash.Error(ctx.Tr("form.last_org_owner")) - ctx.Redirect(ctx.Org.OrgLink + "/members") + c.Flash.Error(c.Tr("form.last_org_owner")) + c.Redirect(c.Org.OrgLink + "/members") return } } if err != nil { - log.Error(4, "Action(%s): %v", ctx.Params(":action"), err) - ctx.JSON(200, map[string]interface{}{ + log.Error(4, "Action(%s): %v", c.Params(":action"), err) + c.JSON(200, map[string]interface{}{ "ok": false, "err": err.Error(), }) return } - if ctx.Params(":action") != "leave" { - ctx.Redirect(ctx.Org.OrgLink + "/members") + if c.Params(":action") != "leave" { + c.Redirect(c.Org.OrgLink + "/members") } else { - ctx.Redirect(setting.AppSubURL + "/") + c.Redirect(setting.AppSubURL + "/") } } -func Invitation(ctx *context.Context) { - org := ctx.Org.Organization - ctx.Data["Title"] = org.FullName - ctx.Data["PageIsOrgMembers"] = true +func Invitation(c *context.Context) { + org := c.Org.Organization + c.Data["Title"] = org.FullName + c.Data["PageIsOrgMembers"] = true - if ctx.Req.Method == "POST" { - uname := ctx.Query("uname") + if c.Req.Method == "POST" { + uname := c.Query("uname") u, err := models.GetUserByName(uname) if err != nil { if errors.IsUserNotExist(err) { - ctx.Flash.Error(ctx.Tr("form.user_not_exist")) - ctx.Redirect(ctx.Org.OrgLink + "/invitations/new") + c.Flash.Error(c.Tr("form.user_not_exist")) + c.Redirect(c.Org.OrgLink + "/invitations/new") } else { - ctx.Handle(500, " GetUserByName", err) + c.Handle(500, " GetUserByName", err) } return } if err = org.AddMember(u.ID); err != nil { - ctx.Handle(500, " AddMember", err) + c.Handle(500, " AddMember", err) return } log.Trace("New member added(%s): %s", org.Name, u.Name) - ctx.Redirect(ctx.Org.OrgLink + "/members") + c.Redirect(c.Org.OrgLink + "/members") return } - ctx.HTML(200, MEMBER_INVITE) + c.HTML(200, MEMBER_INVITE) } diff --git a/routers/org/org.go b/routers/org/org.go index 8e6665619..775e9915d 100644 --- a/routers/org/org.go +++ b/routers/org/org.go @@ -17,16 +17,16 @@ const ( CREATE = "org/create" ) -func Create(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("new_org") - ctx.HTML(200, CREATE) +func Create(c *context.Context) { + c.Data["Title"] = c.Tr("new_org") + c.HTML(200, CREATE) } -func CreatePost(ctx *context.Context, f form.CreateOrg) { - ctx.Data["Title"] = ctx.Tr("new_org") +func CreatePost(c *context.Context, f form.CreateOrg) { + c.Data["Title"] = c.Tr("new_org") - if ctx.HasError() { - ctx.HTML(200, CREATE) + if c.HasError() { + c.HTML(200, CREATE) return } @@ -36,21 +36,21 @@ func CreatePost(ctx *context.Context, f form.CreateOrg) { Type: models.USER_TYPE_ORGANIZATION, } - if err := models.CreateOrganization(org, ctx.User); err != nil { - ctx.Data["Err_OrgName"] = true + if err := models.CreateOrganization(org, c.User); err != nil { + c.Data["Err_OrgName"] = true switch { case models.IsErrUserAlreadyExist(err): - ctx.RenderWithErr(ctx.Tr("form.org_name_been_taken"), CREATE, &f) + c.RenderWithErr(c.Tr("form.org_name_been_taken"), CREATE, &f) case models.IsErrNameReserved(err): - ctx.RenderWithErr(ctx.Tr("org.form.name_reserved", err.(models.ErrNameReserved).Name), CREATE, &f) + c.RenderWithErr(c.Tr("org.form.name_reserved", err.(models.ErrNameReserved).Name), CREATE, &f) case models.IsErrNamePatternNotAllowed(err): - ctx.RenderWithErr(ctx.Tr("org.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), CREATE, &f) + c.RenderWithErr(c.Tr("org.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), CREATE, &f) default: - ctx.Handle(500, "CreateOrganization", err) + c.Handle(500, "CreateOrganization", err) } return } log.Trace("Organization created: %s", org.Name) - ctx.Redirect(setting.AppSubURL + "/org/" + f.OrgName + "/dashboard") + c.Redirect(setting.AppSubURL + "/org/" + f.OrgName + "/dashboard") } diff --git a/routers/org/setting.go b/routers/org/setting.go index 0d934892b..8e2e556f2 100644 --- a/routers/org/setting.go +++ b/routers/org/setting.go @@ -23,54 +23,54 @@ const ( SETTINGS_WEBHOOKS = "org/settings/webhooks" ) -func Settings(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("org.settings") - ctx.Data["PageIsSettingsOptions"] = true - ctx.HTML(200, SETTINGS_OPTIONS) +func Settings(c *context.Context) { + c.Data["Title"] = c.Tr("org.settings") + c.Data["PageIsSettingsOptions"] = true + c.HTML(200, SETTINGS_OPTIONS) } -func SettingsPost(ctx *context.Context, f form.UpdateOrgSetting) { - ctx.Data["Title"] = ctx.Tr("org.settings") - ctx.Data["PageIsSettingsOptions"] = true +func SettingsPost(c *context.Context, f form.UpdateOrgSetting) { + c.Data["Title"] = c.Tr("org.settings") + c.Data["PageIsSettingsOptions"] = true - if ctx.HasError() { - ctx.HTML(200, SETTINGS_OPTIONS) + if c.HasError() { + c.HTML(200, SETTINGS_OPTIONS) return } - org := ctx.Org.Organization + org := c.Org.Organization // Check if organization name has been changed. if org.LowerName != strings.ToLower(f.Name) { isExist, err := models.IsUserExist(org.ID, f.Name) if err != nil { - ctx.Handle(500, "IsUserExist", err) + c.Handle(500, "IsUserExist", err) return } else if isExist { - ctx.Data["OrgName"] = true - ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &f) + c.Data["OrgName"] = true + c.RenderWithErr(c.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &f) return } else if err = models.ChangeUserName(org, f.Name); err != nil { - ctx.Data["OrgName"] = true + c.Data["OrgName"] = true switch { case models.IsErrNameReserved(err): - ctx.RenderWithErr(ctx.Tr("user.form.name_reserved"), SETTINGS_OPTIONS, &f) + c.RenderWithErr(c.Tr("user.form.name_reserved"), SETTINGS_OPTIONS, &f) case models.IsErrNamePatternNotAllowed(err): - ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed"), SETTINGS_OPTIONS, &f) + c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed"), SETTINGS_OPTIONS, &f) default: - ctx.Handle(500, "ChangeUserName", err) + c.Handle(500, "ChangeUserName", err) } return } - // reset ctx.org.OrgLink with new name - ctx.Org.OrgLink = setting.AppSubURL + "/org/" + f.Name + // reset c.org.OrgLink with new name + c.Org.OrgLink = setting.AppSubURL + "/org/" + f.Name log.Trace("Organization name changed: %s -> %s", org.Name, f.Name) } // In case it's just a case change. org.Name = f.Name org.LowerName = strings.ToLower(f.Name) - if ctx.User.IsAdmin { + if c.User.IsAdmin { org.MaxRepoCreation = f.MaxRepoCreation } @@ -79,90 +79,90 @@ func SettingsPost(ctx *context.Context, f form.UpdateOrgSetting) { org.Website = f.Website org.Location = f.Location if err := models.UpdateUser(org); err != nil { - ctx.Handle(500, "UpdateUser", err) + c.Handle(500, "UpdateUser", err) return } log.Trace("Organization setting updated: %s", org.Name) - ctx.Flash.Success(ctx.Tr("org.settings.update_setting_success")) - ctx.Redirect(ctx.Org.OrgLink + "/settings") + c.Flash.Success(c.Tr("org.settings.update_setting_success")) + c.Redirect(c.Org.OrgLink + "/settings") } -func SettingsAvatar(ctx *context.Context, f form.Avatar) { +func SettingsAvatar(c *context.Context, f form.Avatar) { f.Source = form.AVATAR_LOCAL - if err := user.UpdateAvatarSetting(ctx, f, ctx.Org.Organization); err != nil { - ctx.Flash.Error(err.Error()) + if err := user.UpdateAvatarSetting(c, f, c.Org.Organization); err != nil { + c.Flash.Error(err.Error()) } else { - ctx.Flash.Success(ctx.Tr("org.settings.update_avatar_success")) + c.Flash.Success(c.Tr("org.settings.update_avatar_success")) } - ctx.Redirect(ctx.Org.OrgLink + "/settings") + c.Redirect(c.Org.OrgLink + "/settings") } -func SettingsDeleteAvatar(ctx *context.Context) { - if err := ctx.Org.Organization.DeleteAvatar(); err != nil { - ctx.Flash.Error(err.Error()) +func SettingsDeleteAvatar(c *context.Context) { + if err := c.Org.Organization.DeleteAvatar(); err != nil { + c.Flash.Error(err.Error()) } - ctx.Redirect(ctx.Org.OrgLink + "/settings") + c.Redirect(c.Org.OrgLink + "/settings") } -func SettingsDelete(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("org.settings") - ctx.Data["PageIsSettingsDelete"] = true +func SettingsDelete(c *context.Context) { + c.Data["Title"] = c.Tr("org.settings") + c.Data["PageIsSettingsDelete"] = true - org := ctx.Org.Organization - if ctx.Req.Method == "POST" { - if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil { + org := c.Org.Organization + if c.Req.Method == "POST" { + if _, err := models.UserSignIn(c.User.Name, c.Query("password")); err != nil { if errors.IsUserNotExist(err) { - ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil) + c.RenderWithErr(c.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil) } else { - ctx.Handle(500, "UserSignIn", err) + c.Handle(500, "UserSignIn", err) } return } if err := models.DeleteOrganization(org); err != nil { if models.IsErrUserOwnRepos(err) { - ctx.Flash.Error(ctx.Tr("form.org_still_own_repo")) - ctx.Redirect(ctx.Org.OrgLink + "/settings/delete") + c.Flash.Error(c.Tr("form.org_still_own_repo")) + c.Redirect(c.Org.OrgLink + "/settings/delete") } else { - ctx.Handle(500, "DeleteOrganization", err) + c.Handle(500, "DeleteOrganization", err) } } else { log.Trace("Organization deleted: %s", org.Name) - ctx.Redirect(setting.AppSubURL + "/") + c.Redirect(setting.AppSubURL + "/") } return } - ctx.HTML(200, SETTINGS_DELETE) + c.HTML(200, SETTINGS_DELETE) } -func Webhooks(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("org.settings") - ctx.Data["PageIsSettingsHooks"] = true - ctx.Data["BaseLink"] = ctx.Org.OrgLink - ctx.Data["Description"] = ctx.Tr("org.settings.hooks_desc") - ctx.Data["Types"] = setting.Webhook.Types +func Webhooks(c *context.Context) { + c.Data["Title"] = c.Tr("org.settings") + c.Data["PageIsSettingsHooks"] = true + c.Data["BaseLink"] = c.Org.OrgLink + c.Data["Description"] = c.Tr("org.settings.hooks_desc") + c.Data["Types"] = setting.Webhook.Types - ws, err := models.GetWebhooksByOrgID(ctx.Org.Organization.ID) + ws, err := models.GetWebhooksByOrgID(c.Org.Organization.ID) if err != nil { - ctx.Handle(500, "GetWebhooksByOrgId", err) + c.Handle(500, "GetWebhooksByOrgId", err) return } - ctx.Data["Webhooks"] = ws - ctx.HTML(200, SETTINGS_WEBHOOKS) + c.Data["Webhooks"] = ws + c.HTML(200, SETTINGS_WEBHOOKS) } -func DeleteWebhook(ctx *context.Context) { - if err := models.DeleteWebhookOfOrgByID(ctx.Org.Organization.ID, ctx.QueryInt64("id")); err != nil { - ctx.Flash.Error("DeleteWebhookByOrgID: " + err.Error()) +func DeleteWebhook(c *context.Context) { + if err := models.DeleteWebhookOfOrgByID(c.Org.Organization.ID, c.QueryInt64("id")); err != nil { + c.Flash.Error("DeleteWebhookByOrgID: " + err.Error()) } else { - ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success")) + c.Flash.Success(c.Tr("repo.settings.webhook_deletion_success")) } - ctx.JSON(200, map[string]interface{}{ - "redirect": ctx.Org.OrgLink + "/settings/hooks", + c.JSON(200, map[string]interface{}{ + "redirect": c.Org.OrgLink + "/settings/hooks", }) } diff --git a/routers/org/teams.go b/routers/org/teams.go index 0c16043a0..c97d470d0 100644 --- a/routers/org/teams.go +++ b/routers/org/teams.go @@ -23,75 +23,75 @@ const ( TEAM_REPOSITORIES = "org/team/repositories" ) -func Teams(ctx *context.Context) { - org := ctx.Org.Organization - ctx.Data["Title"] = org.FullName - ctx.Data["PageIsOrgTeams"] = true +func Teams(c *context.Context) { + org := c.Org.Organization + c.Data["Title"] = org.FullName + c.Data["PageIsOrgTeams"] = true for _, t := range org.Teams { if err := t.GetMembers(); err != nil { - ctx.Handle(500, "GetMembers", err) + c.Handle(500, "GetMembers", err) return } } - ctx.Data["Teams"] = org.Teams + c.Data["Teams"] = org.Teams - ctx.HTML(200, TEAMS) + c.HTML(200, TEAMS) } -func TeamsAction(ctx *context.Context) { - uid := com.StrTo(ctx.Query("uid")).MustInt64() +func TeamsAction(c *context.Context) { + uid := com.StrTo(c.Query("uid")).MustInt64() if uid == 0 { - ctx.Redirect(ctx.Org.OrgLink + "/teams") + c.Redirect(c.Org.OrgLink + "/teams") return } - page := ctx.Query("page") + page := c.Query("page") var err error - switch ctx.Params(":action") { + switch c.Params(":action") { case "join": - if !ctx.Org.IsOwner { - ctx.Error(404) + if !c.Org.IsOwner { + c.Error(404) return } - err = ctx.Org.Team.AddMember(ctx.User.ID) + err = c.Org.Team.AddMember(c.User.ID) case "leave": - err = ctx.Org.Team.RemoveMember(ctx.User.ID) + err = c.Org.Team.RemoveMember(c.User.ID) case "remove": - if !ctx.Org.IsOwner { - ctx.Error(404) + if !c.Org.IsOwner { + c.Error(404) return } - err = ctx.Org.Team.RemoveMember(uid) + err = c.Org.Team.RemoveMember(uid) page = "team" case "add": - if !ctx.Org.IsOwner { - ctx.Error(404) + if !c.Org.IsOwner { + c.Error(404) return } - uname := ctx.Query("uname") + uname := c.Query("uname") var u *models.User u, err = models.GetUserByName(uname) if err != nil { if errors.IsUserNotExist(err) { - ctx.Flash.Error(ctx.Tr("form.user_not_exist")) - ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName) + c.Flash.Error(c.Tr("form.user_not_exist")) + c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName) } else { - ctx.Handle(500, " GetUserByName", err) + c.Handle(500, " GetUserByName", err) } return } - err = ctx.Org.Team.AddMember(u.ID) + err = c.Org.Team.AddMember(u.ID) page = "team" } if err != nil { if models.IsErrLastOrgOwner(err) { - ctx.Flash.Error(ctx.Tr("form.last_org_owner")) + c.Flash.Error(c.Tr("form.last_org_owner")) } else { - log.Error(3, "Action(%s): %v", ctx.Params(":action"), err) - ctx.JSON(200, map[string]interface{}{ + log.Error(3, "Action(%s): %v", c.Params(":action"), err) + c.JSON(200, map[string]interface{}{ "ok": false, "err": err.Error(), }) @@ -101,124 +101,124 @@ func TeamsAction(ctx *context.Context) { switch page { case "team": - ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName) + c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName) default: - ctx.Redirect(ctx.Org.OrgLink + "/teams") + c.Redirect(c.Org.OrgLink + "/teams") } } -func TeamsRepoAction(ctx *context.Context) { - if !ctx.Org.IsOwner { - ctx.Error(404) +func TeamsRepoAction(c *context.Context) { + if !c.Org.IsOwner { + c.Error(404) return } var err error - switch ctx.Params(":action") { + switch c.Params(":action") { case "add": - repoName := path.Base(ctx.Query("repo_name")) + repoName := path.Base(c.Query("repo_name")) var repo *models.Repository - repo, err = models.GetRepositoryByName(ctx.Org.Organization.ID, repoName) + repo, err = models.GetRepositoryByName(c.Org.Organization.ID, repoName) if err != nil { if errors.IsRepoNotExist(err) { - ctx.Flash.Error(ctx.Tr("org.teams.add_nonexistent_repo")) - ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories") + c.Flash.Error(c.Tr("org.teams.add_nonexistent_repo")) + c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName + "/repositories") return } - ctx.Handle(500, "GetRepositoryByName", err) + c.Handle(500, "GetRepositoryByName", err) return } - err = ctx.Org.Team.AddRepository(repo) + err = c.Org.Team.AddRepository(repo) case "remove": - err = ctx.Org.Team.RemoveRepository(com.StrTo(ctx.Query("repoid")).MustInt64()) + err = c.Org.Team.RemoveRepository(com.StrTo(c.Query("repoid")).MustInt64()) } if err != nil { - log.Error(3, "Action(%s): '%s' %v", ctx.Params(":action"), ctx.Org.Team.Name, err) - ctx.Handle(500, "TeamsRepoAction", err) + log.Error(3, "Action(%s): '%s' %v", c.Params(":action"), c.Org.Team.Name, err) + c.Handle(500, "TeamsRepoAction", err) return } - ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories") + c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName + "/repositories") } -func NewTeam(ctx *context.Context) { - ctx.Data["Title"] = ctx.Org.Organization.FullName - ctx.Data["PageIsOrgTeams"] = true - ctx.Data["PageIsOrgTeamsNew"] = true - ctx.Data["Team"] = &models.Team{} - ctx.HTML(200, TEAM_NEW) +func NewTeam(c *context.Context) { + c.Data["Title"] = c.Org.Organization.FullName + c.Data["PageIsOrgTeams"] = true + c.Data["PageIsOrgTeamsNew"] = true + c.Data["Team"] = &models.Team{} + c.HTML(200, TEAM_NEW) } -func NewTeamPost(ctx *context.Context, f form.CreateTeam) { - ctx.Data["Title"] = ctx.Org.Organization.FullName - ctx.Data["PageIsOrgTeams"] = true - ctx.Data["PageIsOrgTeamsNew"] = true +func NewTeamPost(c *context.Context, f form.CreateTeam) { + c.Data["Title"] = c.Org.Organization.FullName + c.Data["PageIsOrgTeams"] = true + c.Data["PageIsOrgTeamsNew"] = true t := &models.Team{ - OrgID: ctx.Org.Organization.ID, + OrgID: c.Org.Organization.ID, Name: f.TeamName, Description: f.Description, Authorize: models.ParseAccessMode(f.Permission), } - ctx.Data["Team"] = t + c.Data["Team"] = t - if ctx.HasError() { - ctx.HTML(200, TEAM_NEW) + if c.HasError() { + c.HTML(200, TEAM_NEW) return } if err := models.NewTeam(t); err != nil { - ctx.Data["Err_TeamName"] = true + c.Data["Err_TeamName"] = true switch { case models.IsErrTeamAlreadyExist(err): - ctx.RenderWithErr(ctx.Tr("form.team_name_been_taken"), TEAM_NEW, &f) + c.RenderWithErr(c.Tr("form.team_name_been_taken"), TEAM_NEW, &f) case models.IsErrNameReserved(err): - ctx.RenderWithErr(ctx.Tr("org.form.team_name_reserved", err.(models.ErrNameReserved).Name), TEAM_NEW, &f) + c.RenderWithErr(c.Tr("org.form.team_name_reserved", err.(models.ErrNameReserved).Name), TEAM_NEW, &f) default: - ctx.Handle(500, "NewTeam", err) + c.Handle(500, "NewTeam", err) } return } - log.Trace("Team created: %s/%s", ctx.Org.Organization.Name, t.Name) - ctx.Redirect(ctx.Org.OrgLink + "/teams/" + t.LowerName) + log.Trace("Team created: %s/%s", c.Org.Organization.Name, t.Name) + c.Redirect(c.Org.OrgLink + "/teams/" + t.LowerName) } -func TeamMembers(ctx *context.Context) { - ctx.Data["Title"] = ctx.Org.Team.Name - ctx.Data["PageIsOrgTeams"] = true - if err := ctx.Org.Team.GetMembers(); err != nil { - ctx.Handle(500, "GetMembers", err) +func TeamMembers(c *context.Context) { + c.Data["Title"] = c.Org.Team.Name + c.Data["PageIsOrgTeams"] = true + if err := c.Org.Team.GetMembers(); err != nil { + c.Handle(500, "GetMembers", err) return } - ctx.HTML(200, TEAM_MEMBERS) + c.HTML(200, TEAM_MEMBERS) } -func TeamRepositories(ctx *context.Context) { - ctx.Data["Title"] = ctx.Org.Team.Name - ctx.Data["PageIsOrgTeams"] = true - if err := ctx.Org.Team.GetRepositories(); err != nil { - ctx.Handle(500, "GetRepositories", err) +func TeamRepositories(c *context.Context) { + c.Data["Title"] = c.Org.Team.Name + c.Data["PageIsOrgTeams"] = true + if err := c.Org.Team.GetRepositories(); err != nil { + c.Handle(500, "GetRepositories", err) return } - ctx.HTML(200, TEAM_REPOSITORIES) + c.HTML(200, TEAM_REPOSITORIES) } -func EditTeam(ctx *context.Context) { - ctx.Data["Title"] = ctx.Org.Organization.FullName - ctx.Data["PageIsOrgTeams"] = true - ctx.Data["team_name"] = ctx.Org.Team.Name - ctx.Data["desc"] = ctx.Org.Team.Description - ctx.HTML(200, TEAM_NEW) +func EditTeam(c *context.Context) { + c.Data["Title"] = c.Org.Organization.FullName + c.Data["PageIsOrgTeams"] = true + c.Data["team_name"] = c.Org.Team.Name + c.Data["desc"] = c.Org.Team.Description + c.HTML(200, TEAM_NEW) } -func EditTeamPost(ctx *context.Context, f form.CreateTeam) { - t := ctx.Org.Team - ctx.Data["Title"] = ctx.Org.Organization.FullName - ctx.Data["PageIsOrgTeams"] = true - ctx.Data["Team"] = t +func EditTeamPost(c *context.Context, f form.CreateTeam) { + t := c.Org.Team + c.Data["Title"] = c.Org.Organization.FullName + c.Data["PageIsOrgTeams"] = true + c.Data["Team"] = t - if ctx.HasError() { - ctx.HTML(200, TEAM_NEW) + if c.HasError() { + c.HTML(200, TEAM_NEW) return } @@ -234,7 +234,7 @@ func EditTeamPost(ctx *context.Context, f form.CreateTeam) { case "admin": auth = models.ACCESS_MODE_ADMIN default: - ctx.Error(401) + c.Error(401) return } @@ -246,26 +246,26 @@ func EditTeamPost(ctx *context.Context, f form.CreateTeam) { } t.Description = f.Description if err := models.UpdateTeam(t, isAuthChanged); err != nil { - ctx.Data["Err_TeamName"] = true + c.Data["Err_TeamName"] = true switch { case models.IsErrTeamAlreadyExist(err): - ctx.RenderWithErr(ctx.Tr("form.team_name_been_taken"), TEAM_NEW, &f) + c.RenderWithErr(c.Tr("form.team_name_been_taken"), TEAM_NEW, &f) default: - ctx.Handle(500, "UpdateTeam", err) + c.Handle(500, "UpdateTeam", err) } return } - ctx.Redirect(ctx.Org.OrgLink + "/teams/" + t.LowerName) + c.Redirect(c.Org.OrgLink + "/teams/" + t.LowerName) } -func DeleteTeam(ctx *context.Context) { - if err := models.DeleteTeam(ctx.Org.Team); err != nil { - ctx.Flash.Error("DeleteTeam: " + err.Error()) +func DeleteTeam(c *context.Context) { + if err := models.DeleteTeam(c.Org.Team); err != nil { + c.Flash.Error("DeleteTeam: " + err.Error()) } else { - ctx.Flash.Success(ctx.Tr("org.teams.delete_team_success")) + c.Flash.Success(c.Tr("org.teams.delete_team_success")) } - ctx.JSON(200, map[string]interface{}{ - "redirect": ctx.Org.OrgLink + "/teams", + c.JSON(200, map[string]interface{}{ + "redirect": c.Org.OrgLink + "/teams", }) } diff --git a/routers/repo/branch.go b/routers/repo/branch.go index 71e9337e0..685df2e74 100644 --- a/routers/repo/branch.go +++ b/routers/repo/branch.go @@ -26,16 +26,16 @@ type Branch struct { IsProtected bool } -func loadBranches(ctx *context.Context) []*Branch { - rawBranches, err := ctx.Repo.Repository.GetBranches() +func loadBranches(c *context.Context) []*Branch { + rawBranches, err := c.Repo.Repository.GetBranches() if err != nil { - ctx.Handle(500, "GetBranches", err) + c.Handle(500, "GetBranches", err) return nil } - protectBranches, err := models.GetProtectBranchesByRepoID(ctx.Repo.Repository.ID) + protectBranches, err := models.GetProtectBranchesByRepoID(c.Repo.Repository.ID) if err != nil { - ctx.Handle(500, "GetProtectBranchesByRepoID", err) + c.Handle(500, "GetProtectBranchesByRepoID", err) return nil } @@ -43,7 +43,7 @@ func loadBranches(ctx *context.Context) []*Branch { for i := range rawBranches { commit, err := rawBranches[i].GetCommit() if err != nil { - ctx.Handle(500, "GetCommit", err) + c.Handle(500, "GetCommit", err) return nil } @@ -60,16 +60,16 @@ func loadBranches(ctx *context.Context) []*Branch { } } - ctx.Data["AllowPullRequest"] = ctx.Repo.Repository.AllowsPulls() + c.Data["AllowPullRequest"] = c.Repo.Repository.AllowsPulls() return branches } -func Branches(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("repo.git_branches") - ctx.Data["PageIsBranchesOverview"] = true +func Branches(c *context.Context) { + c.Data["Title"] = c.Tr("repo.git_branches") + c.Data["PageIsBranchesOverview"] = true - branches := loadBranches(ctx) - if ctx.Written() { + branches := loadBranches(c) + if c.Written() { return } @@ -78,8 +78,8 @@ func Branches(ctx *context.Context) { staleBranches := make([]*Branch, 0, 3) for i := range branches { switch { - case branches[i].Name == ctx.Repo.BranchName: - ctx.Data["DefaultBranch"] = branches[i] + case branches[i].Name == c.Repo.BranchName: + c.Data["DefaultBranch"] = branches[i] case branches[i].Commit.Committer.When.Add(30 * 24 * time.Hour).After(now): // 30 days activeBranches = append(activeBranches, branches[i]) case branches[i].Commit.Committer.When.Add(3 * 30 * 24 * time.Hour).Before(now): // 90 days @@ -87,53 +87,53 @@ func Branches(ctx *context.Context) { } } - ctx.Data["ActiveBranches"] = activeBranches - ctx.Data["StaleBranches"] = staleBranches - ctx.HTML(200, BRANCHES_OVERVIEW) + c.Data["ActiveBranches"] = activeBranches + c.Data["StaleBranches"] = staleBranches + c.HTML(200, BRANCHES_OVERVIEW) } -func AllBranches(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("repo.git_branches") - ctx.Data["PageIsBranchesAll"] = true +func AllBranches(c *context.Context) { + c.Data["Title"] = c.Tr("repo.git_branches") + c.Data["PageIsBranchesAll"] = true - branches := loadBranches(ctx) - if ctx.Written() { + branches := loadBranches(c) + if c.Written() { return } - ctx.Data["Branches"] = branches + c.Data["Branches"] = branches - ctx.HTML(200, BRANCHES_ALL) + c.HTML(200, BRANCHES_ALL) } -func DeleteBranchPost(ctx *context.Context) { - branchName := ctx.Params("*") - commitID := ctx.Query("commit") +func DeleteBranchPost(c *context.Context) { + branchName := c.Params("*") + commitID := c.Query("commit") defer func() { - redirectTo := ctx.Query("redirect_to") + redirectTo := c.Query("redirect_to") if len(redirectTo) == 0 { - redirectTo = ctx.Repo.RepoLink + redirectTo = c.Repo.RepoLink } - ctx.Redirect(redirectTo) + c.Redirect(redirectTo) }() - if !ctx.Repo.GitRepo.IsBranchExist(branchName) { + if !c.Repo.GitRepo.IsBranchExist(branchName) { return } if len(commitID) > 0 { - branchCommitID, err := ctx.Repo.GitRepo.GetBranchCommitID(branchName) + branchCommitID, err := c.Repo.GitRepo.GetBranchCommitID(branchName) if err != nil { log.Error(2, "GetBranchCommitID: %v", err) return } if branchCommitID != commitID { - ctx.Flash.Error(ctx.Tr("repo.pulls.delete_branch_has_new_commits")) + c.Flash.Error(c.Tr("repo.pulls.delete_branch_has_new_commits")) return } } - if err := ctx.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{ + if err := c.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{ Force: true, }); err != nil { log.Error(2, "DeleteBranch '%s': %v", branchName, err) diff --git a/routers/repo/commit.go b/routers/repo/commit.go index 992b35f5d..17ea5dbe3 100644 --- a/routers/repo/commit.go +++ b/routers/repo/commit.go @@ -21,15 +21,15 @@ const ( DIFF = "repo/diff/page" ) -func RefCommits(ctx *context.Context) { - ctx.Data["PageIsViewFiles"] = true +func RefCommits(c *context.Context) { + c.Data["PageIsViewFiles"] = true switch { - case len(ctx.Repo.TreePath) == 0: - Commits(ctx) - case ctx.Repo.TreePath == "search": - SearchCommits(ctx) + case len(c.Repo.TreePath) == 0: + Commits(c) + case c.Repo.TreePath == "search": + SearchCommits(c) default: - FileHistory(ctx) + FileHistory(c) } } @@ -42,15 +42,15 @@ func RenderIssueLinks(oldCommits *list.List, repoLink string) *list.List { return newCommits } -func renderCommits(ctx *context.Context, filename string) { - ctx.Data["Title"] = ctx.Tr("repo.commits.commit_history") + " · " + ctx.Repo.Repository.FullName() - ctx.Data["PageIsCommits"] = true +func renderCommits(c *context.Context, filename string) { + c.Data["Title"] = c.Tr("repo.commits.commit_history") + " · " + c.Repo.Repository.FullName() + c.Data["PageIsCommits"] = true - page := ctx.QueryInt("page") + page := c.QueryInt("page") if page < 1 { page = 1 } - pageSize := ctx.QueryInt("pageSize") + pageSize := c.QueryInt("pageSize") if pageSize < 1 { pageSize = git.DefaultCommitsPageSize } @@ -59,80 +59,80 @@ func renderCommits(ctx *context.Context, filename string) { var err error var commits *list.List if len(filename) == 0 { - commits, err = ctx.Repo.Commit.CommitsByRangeSize(page, pageSize) + commits, err = c.Repo.Commit.CommitsByRangeSize(page, pageSize) } else { - commits, err = ctx.Repo.GitRepo.CommitsByFileAndRangeSize(ctx.Repo.BranchName, filename, page, pageSize) + commits, err = c.Repo.GitRepo.CommitsByFileAndRangeSize(c.Repo.BranchName, filename, page, pageSize) } if err != nil { - ctx.Handle(500, "CommitsByRangeSize/CommitsByFileAndRangeSize", err) + c.Handle(500, "CommitsByRangeSize/CommitsByFileAndRangeSize", err) return } - commits = RenderIssueLinks(commits, ctx.Repo.RepoLink) + commits = RenderIssueLinks(commits, c.Repo.RepoLink) commits = models.ValidateCommitsWithEmails(commits) - ctx.Data["Commits"] = commits + c.Data["Commits"] = commits if page > 1 { - ctx.Data["HasPrevious"] = true - ctx.Data["PreviousPage"] = page - 1 + c.Data["HasPrevious"] = true + c.Data["PreviousPage"] = page - 1 } if commits.Len() == pageSize { - ctx.Data["HasNext"] = true - ctx.Data["NextPage"] = page + 1 + c.Data["HasNext"] = true + c.Data["NextPage"] = page + 1 } - ctx.Data["PageSize"] = pageSize + c.Data["PageSize"] = pageSize - ctx.Data["Username"] = ctx.Repo.Owner.Name - ctx.Data["Reponame"] = ctx.Repo.Repository.Name - ctx.HTML(200, COMMITS) + c.Data["Username"] = c.Repo.Owner.Name + c.Data["Reponame"] = c.Repo.Repository.Name + c.HTML(200, COMMITS) } -func Commits(ctx *context.Context) { - renderCommits(ctx, "") +func Commits(c *context.Context) { + renderCommits(c, "") } -func SearchCommits(ctx *context.Context) { - ctx.Data["PageIsCommits"] = true +func SearchCommits(c *context.Context) { + c.Data["PageIsCommits"] = true - keyword := ctx.Query("q") + keyword := c.Query("q") if len(keyword) == 0 { - ctx.Redirect(ctx.Repo.RepoLink + "/commits/" + ctx.Repo.BranchName) + c.Redirect(c.Repo.RepoLink + "/commits/" + c.Repo.BranchName) return } - commits, err := ctx.Repo.Commit.SearchCommits(keyword) + commits, err := c.Repo.Commit.SearchCommits(keyword) if err != nil { - ctx.Handle(500, "SearchCommits", err) + c.Handle(500, "SearchCommits", err) return } - commits = RenderIssueLinks(commits, ctx.Repo.RepoLink) + commits = RenderIssueLinks(commits, c.Repo.RepoLink) commits = models.ValidateCommitsWithEmails(commits) - ctx.Data["Commits"] = commits + c.Data["Commits"] = commits - ctx.Data["Keyword"] = keyword - ctx.Data["Username"] = ctx.Repo.Owner.Name - ctx.Data["Reponame"] = ctx.Repo.Repository.Name - ctx.Data["Branch"] = ctx.Repo.BranchName - ctx.HTML(200, COMMITS) + c.Data["Keyword"] = keyword + c.Data["Username"] = c.Repo.Owner.Name + c.Data["Reponame"] = c.Repo.Repository.Name + c.Data["Branch"] = c.Repo.BranchName + c.HTML(200, COMMITS) } -func FileHistory(ctx *context.Context) { - renderCommits(ctx, ctx.Repo.TreePath) +func FileHistory(c *context.Context) { + renderCommits(c, c.Repo.TreePath) } -func Diff(ctx *context.Context) { - ctx.Data["PageIsDiff"] = true - ctx.Data["RequireHighlightJS"] = true +func Diff(c *context.Context) { + c.Data["PageIsDiff"] = true + c.Data["RequireHighlightJS"] = true - userName := ctx.Repo.Owner.Name - repoName := ctx.Repo.Repository.Name - commitID := ctx.Params(":sha") + userName := c.Repo.Owner.Name + repoName := c.Repo.Repository.Name + commitID := c.Params(":sha") - commit, err := ctx.Repo.GitRepo.GetCommit(commitID) + commit, err := c.Repo.GitRepo.GetCommit(commitID) if err != nil { if git.IsErrNotExist(err) { - ctx.Handle(404, "Repo.GitRepo.GetCommit", err) + c.Handle(404, "Repo.GitRepo.GetCommit", err) } else { - ctx.Handle(500, "Repo.GitRepo.GetCommit", err) + c.Handle(500, "Repo.GitRepo.GetCommit", err) } return } @@ -141,7 +141,7 @@ func Diff(ctx *context.Context) { commitID, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles) if err != nil { - ctx.NotFoundOrServerError("GetDiffCommit", git.IsErrNotExist, err) + c.NotFoundOrServerError("GetDiffCommit", git.IsErrNotExist, err) return } @@ -150,33 +150,33 @@ func Diff(ctx *context.Context) { sha, err := commit.ParentID(i) parents[i] = sha.String() if err != nil { - ctx.Handle(404, "repo.Diff", err) + c.Handle(404, "repo.Diff", err) return } } - setEditorconfigIfExists(ctx) - if ctx.Written() { + setEditorconfigIfExists(c) + if c.Written() { return } - ctx.Data["CommitID"] = commitID - ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split" - ctx.Data["Username"] = userName - ctx.Data["Reponame"] = repoName - ctx.Data["IsImageFile"] = commit.IsImageFile - ctx.Data["Title"] = commit.Summary() + " · " + tool.ShortSHA1(commitID) - ctx.Data["Commit"] = commit - ctx.Data["Author"] = models.ValidateCommitWithEmail(commit) - ctx.Data["Diff"] = diff - ctx.Data["Parents"] = parents - ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 - ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", commitID) + c.Data["CommitID"] = commitID + c.Data["IsSplitStyle"] = c.Query("style") == "split" + c.Data["Username"] = userName + c.Data["Reponame"] = repoName + c.Data["IsImageFile"] = commit.IsImageFile + c.Data["Title"] = commit.Summary() + " · " + tool.ShortSHA1(commitID) + c.Data["Commit"] = commit + c.Data["Author"] = models.ValidateCommitWithEmail(commit) + c.Data["Diff"] = diff + c.Data["Parents"] = parents + c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 + c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", commitID) if commit.ParentCount() > 0 { - ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", parents[0]) + c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", parents[0]) } - ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", commitID) - ctx.HTML(200, DIFF) + c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", commitID) + c.HTML(200, DIFF) } func RawDiff(c *context.Context) { @@ -191,16 +191,16 @@ func RawDiff(c *context.Context) { } } -func CompareDiff(ctx *context.Context) { - ctx.Data["IsDiffCompare"] = true - userName := ctx.Repo.Owner.Name - repoName := ctx.Repo.Repository.Name - beforeCommitID := ctx.Params(":before") - afterCommitID := ctx.Params(":after") +func CompareDiff(c *context.Context) { + c.Data["IsDiffCompare"] = true + userName := c.Repo.Owner.Name + repoName := c.Repo.Repository.Name + beforeCommitID := c.Params(":before") + afterCommitID := c.Params(":after") - commit, err := ctx.Repo.GitRepo.GetCommit(afterCommitID) + commit, err := c.Repo.GitRepo.GetCommit(afterCommitID) if err != nil { - ctx.Handle(404, "GetCommit", err) + c.Handle(404, "GetCommit", err) return } @@ -208,32 +208,32 @@ func CompareDiff(ctx *context.Context) { afterCommitID, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles) if err != nil { - ctx.Handle(404, "GetDiffRange", err) + c.Handle(404, "GetDiffRange", err) return } commits, err := commit.CommitsBeforeUntil(beforeCommitID) if err != nil { - ctx.Handle(500, "CommitsBeforeUntil", err) + c.Handle(500, "CommitsBeforeUntil", err) return } commits = models.ValidateCommitsWithEmails(commits) - ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split" - ctx.Data["CommitRepoLink"] = ctx.Repo.RepoLink - ctx.Data["Commits"] = commits - ctx.Data["CommitsCount"] = commits.Len() - ctx.Data["BeforeCommitID"] = beforeCommitID - ctx.Data["AfterCommitID"] = afterCommitID - ctx.Data["Username"] = userName - ctx.Data["Reponame"] = repoName - ctx.Data["IsImageFile"] = commit.IsImageFile - ctx.Data["Title"] = "Comparing " + tool.ShortSHA1(beforeCommitID) + "..." + tool.ShortSHA1(afterCommitID) + " · " + userName + "/" + repoName - ctx.Data["Commit"] = commit - ctx.Data["Diff"] = diff - ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 - ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", afterCommitID) - ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", beforeCommitID) - ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", afterCommitID) - ctx.HTML(200, DIFF) + c.Data["IsSplitStyle"] = c.Query("style") == "split" + c.Data["CommitRepoLink"] = c.Repo.RepoLink + c.Data["Commits"] = commits + c.Data["CommitsCount"] = commits.Len() + c.Data["BeforeCommitID"] = beforeCommitID + c.Data["AfterCommitID"] = afterCommitID + c.Data["Username"] = userName + c.Data["Reponame"] = repoName + c.Data["IsImageFile"] = commit.IsImageFile + c.Data["Title"] = "Comparing " + tool.ShortSHA1(beforeCommitID) + "..." + tool.ShortSHA1(afterCommitID) + " · " + userName + "/" + repoName + c.Data["Commit"] = commit + c.Data["Diff"] = diff + c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 + c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", afterCommitID) + c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", beforeCommitID) + c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", afterCommitID) + c.HTML(200, DIFF) } diff --git a/routers/repo/download.go b/routers/repo/download.go index f5fa1fc44..e9a29989a 100644 --- a/routers/repo/download.go +++ b/routers/repo/download.go @@ -15,7 +15,7 @@ import ( "github.com/gogits/gogs/pkg/setting" ) -func ServeData(ctx *context.Context, name string, reader io.Reader) error { +func ServeData(c *context.Context, name string, reader io.Reader) error { buf := make([]byte, 1024) n, _ := reader.Read(buf) if n >= 0 { @@ -24,37 +24,37 @@ func ServeData(ctx *context.Context, name string, reader io.Reader) error { if !tool.IsTextFile(buf) { if !tool.IsImageFile(buf) { - ctx.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"") - ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary") + c.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"") + c.Resp.Header().Set("Content-Transfer-Encoding", "binary") } - } else if !setting.Repository.EnableRawFileRenderMode || !ctx.QueryBool("render") { - ctx.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8") + } else if !setting.Repository.EnableRawFileRenderMode || !c.QueryBool("render") { + c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8") } - ctx.Resp.Write(buf) - _, err := io.Copy(ctx.Resp, reader) + c.Resp.Write(buf) + _, err := io.Copy(c.Resp, reader) return err } -func ServeBlob(ctx *context.Context, blob *git.Blob) error { +func ServeBlob(c *context.Context, blob *git.Blob) error { dataRc, err := blob.Data() if err != nil { return err } - return ServeData(ctx, path.Base(ctx.Repo.TreePath), dataRc) + return ServeData(c, path.Base(c.Repo.TreePath), dataRc) } -func SingleDownload(ctx *context.Context) { - blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath) +func SingleDownload(c *context.Context) { + blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath) if err != nil { if git.IsErrNotExist(err) { - ctx.Handle(404, "GetBlobByPath", nil) + c.Handle(404, "GetBlobByPath", nil) } else { - ctx.Handle(500, "GetBlobByPath", err) + c.Handle(500, "GetBlobByPath", err) } return } - if err = ServeBlob(ctx, blob); err != nil { - ctx.Handle(500, "ServeBlob", err) + if err = ServeBlob(c, blob); err != nil { + c.Handle(500, "ServeBlob", err) } } diff --git a/routers/repo/editor.go b/routers/repo/editor.go index 6d7c524be..4cd78d70f 100644 --- a/routers/repo/editor.go +++ b/routers/repo/editor.go @@ -288,84 +288,84 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { } } -func EditFilePost(ctx *context.Context, f form.EditRepoFile) { - editFilePost(ctx, f, false) +func EditFilePost(c *context.Context, f form.EditRepoFile) { + editFilePost(c, f, false) } -func NewFilePost(ctx *context.Context, f form.EditRepoFile) { - editFilePost(ctx, f, true) +func NewFilePost(c *context.Context, f form.EditRepoFile) { + editFilePost(c, f, true) } -func DiffPreviewPost(ctx *context.Context, f form.EditPreviewDiff) { - treePath := ctx.Repo.TreePath +func DiffPreviewPost(c *context.Context, f form.EditPreviewDiff) { + treePath := c.Repo.TreePath - entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath) + entry, err := c.Repo.Commit.GetTreeEntryByPath(treePath) if err != nil { - ctx.Error(500, "GetTreeEntryByPath: "+err.Error()) + c.Error(500, "GetTreeEntryByPath: "+err.Error()) return } else if entry.IsDir() { - ctx.Error(422) + c.Error(422) return } - diff, err := ctx.Repo.Repository.GetDiffPreview(ctx.Repo.BranchName, treePath, f.Content) + diff, err := c.Repo.Repository.GetDiffPreview(c.Repo.BranchName, treePath, f.Content) if err != nil { - ctx.Error(500, "GetDiffPreview: "+err.Error()) + c.Error(500, "GetDiffPreview: "+err.Error()) return } if diff.NumFiles() == 0 { - ctx.PlainText(200, []byte(ctx.Tr("repo.editor.no_changes_to_show"))) + c.PlainText(200, []byte(c.Tr("repo.editor.no_changes_to_show"))) return } - ctx.Data["File"] = diff.Files[0] + c.Data["File"] = diff.Files[0] - ctx.HTML(200, EDIT_DIFF_PREVIEW) + c.HTML(200, EDIT_DIFF_PREVIEW) } -func DeleteFile(ctx *context.Context) { - ctx.Data["PageIsDelete"] = true - ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName - ctx.Data["TreePath"] = ctx.Repo.TreePath - ctx.Data["commit_summary"] = "" - ctx.Data["commit_message"] = "" - ctx.Data["commit_choice"] = "direct" - ctx.Data["new_branch_name"] = "" - ctx.HTML(200, DELETE_FILE) +func DeleteFile(c *context.Context) { + c.Data["PageIsDelete"] = true + c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName + c.Data["TreePath"] = c.Repo.TreePath + c.Data["commit_summary"] = "" + c.Data["commit_message"] = "" + c.Data["commit_choice"] = "direct" + c.Data["new_branch_name"] = "" + c.HTML(200, DELETE_FILE) } -func DeleteFilePost(ctx *context.Context, f form.DeleteRepoFile) { - ctx.Data["PageIsDelete"] = true - ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName - ctx.Data["TreePath"] = ctx.Repo.TreePath +func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) { + c.Data["PageIsDelete"] = true + c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName + c.Data["TreePath"] = c.Repo.TreePath - oldBranchName := ctx.Repo.BranchName + oldBranchName := c.Repo.BranchName branchName := oldBranchName if f.IsNewBrnach() { branchName = f.NewBranchName } - ctx.Data["commit_summary"] = f.CommitSummary - ctx.Data["commit_message"] = f.CommitMessage - ctx.Data["commit_choice"] = f.CommitChoice - ctx.Data["new_branch_name"] = branchName + c.Data["commit_summary"] = f.CommitSummary + c.Data["commit_message"] = f.CommitMessage + c.Data["commit_choice"] = f.CommitChoice + c.Data["new_branch_name"] = branchName - if ctx.HasError() { - ctx.HTML(200, DELETE_FILE) + if c.HasError() { + c.HTML(200, DELETE_FILE) return } if oldBranchName != branchName { - if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { - ctx.Data["Err_NewBranchName"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &f) + if _, err := c.Repo.Repository.GetBranch(branchName); err == nil { + c.Data["Err_NewBranchName"] = true + c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &f) return } } message := strings.TrimSpace(f.CommitSummary) if len(message) == 0 { - message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath) + message = c.Tr("repo.editor.delete", c.Repo.TreePath) } f.CommitMessage = strings.TrimSpace(f.CommitMessage) @@ -373,58 +373,58 @@ func DeleteFilePost(ctx *context.Context, f form.DeleteRepoFile) { message += "\n\n" + f.CommitMessage } - if err := ctx.Repo.Repository.DeleteRepoFile(ctx.User, models.DeleteRepoFileOptions{ - LastCommitID: ctx.Repo.CommitID, + if err := c.Repo.Repository.DeleteRepoFile(c.User, models.DeleteRepoFileOptions{ + LastCommitID: c.Repo.CommitID, OldBranch: oldBranchName, NewBranch: branchName, - TreePath: ctx.Repo.TreePath, + TreePath: c.Repo.TreePath, Message: message, }); err != nil { - ctx.Handle(500, "DeleteRepoFile", err) + c.Handle(500, "DeleteRepoFile", err) return } - if f.IsNewBrnach() && ctx.Repo.PullRequest.Allowed { - ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) + if f.IsNewBrnach() && c.Repo.PullRequest.Allowed { + c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) } else { - ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath)) - ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName) + c.Flash.Success(c.Tr("repo.editor.file_delete_success", c.Repo.TreePath)) + c.Redirect(c.Repo.RepoLink + "/src/" + branchName) } } -func renderUploadSettings(ctx *context.Context) { - ctx.Data["RequireDropzone"] = true - ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",") - ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize - ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles +func renderUploadSettings(c *context.Context) { + c.Data["RequireDropzone"] = true + c.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",") + c.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize + c.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles } -func UploadFile(ctx *context.Context) { - ctx.Data["PageIsUpload"] = true - renderUploadSettings(ctx) +func UploadFile(c *context.Context) { + c.Data["PageIsUpload"] = true + renderUploadSettings(c) - treeNames, treePaths := getParentTreeFields(ctx.Repo.TreePath) + treeNames, treePaths := getParentTreeFields(c.Repo.TreePath) if len(treeNames) == 0 { // We must at least have one element for user to input. treeNames = []string{""} } - ctx.Data["TreeNames"] = treeNames - ctx.Data["TreePaths"] = treePaths - ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName - ctx.Data["commit_summary"] = "" - ctx.Data["commit_message"] = "" - ctx.Data["commit_choice"] = "direct" - ctx.Data["new_branch_name"] = "" + c.Data["TreeNames"] = treeNames + c.Data["TreePaths"] = treePaths + c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName + c.Data["commit_summary"] = "" + c.Data["commit_message"] = "" + c.Data["commit_choice"] = "direct" + c.Data["new_branch_name"] = "" - ctx.HTML(200, UPLOAD_FILE) + c.HTML(200, UPLOAD_FILE) } -func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) { - ctx.Data["PageIsUpload"] = true - renderUploadSettings(ctx) +func UploadFilePost(c *context.Context, f form.UploadRepoFile) { + c.Data["PageIsUpload"] = true + renderUploadSettings(c) - oldBranchName := ctx.Repo.BranchName + oldBranchName := c.Repo.BranchName branchName := oldBranchName if f.IsNewBrnach() { @@ -438,24 +438,24 @@ func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) { treeNames = []string{""} } - ctx.Data["TreePath"] = f.TreePath - ctx.Data["TreeNames"] = treeNames - ctx.Data["TreePaths"] = treePaths - ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName - ctx.Data["commit_summary"] = f.CommitSummary - ctx.Data["commit_message"] = f.CommitMessage - ctx.Data["commit_choice"] = f.CommitChoice - ctx.Data["new_branch_name"] = branchName + c.Data["TreePath"] = f.TreePath + c.Data["TreeNames"] = treeNames + c.Data["TreePaths"] = treePaths + c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + branchName + c.Data["commit_summary"] = f.CommitSummary + c.Data["commit_message"] = f.CommitMessage + c.Data["commit_choice"] = f.CommitChoice + c.Data["new_branch_name"] = branchName - if ctx.HasError() { - ctx.HTML(200, UPLOAD_FILE) + if c.HasError() { + c.HTML(200, UPLOAD_FILE) return } if oldBranchName != branchName { - if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { - ctx.Data["Err_NewBranchName"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &f) + if _, err := c.Repo.Repository.GetBranch(branchName); err == nil { + c.Data["Err_NewBranchName"] = true + c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &f) return } } @@ -463,28 +463,28 @@ func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) { var newTreePath string for _, part := range treeNames { newTreePath = path.Join(newTreePath, part) - entry, err := ctx.Repo.Commit.GetTreeEntryByPath(newTreePath) + entry, err := c.Repo.Commit.GetTreeEntryByPath(newTreePath) if err != nil { if git.IsErrNotExist(err) { // Means there is no item with that name, so we're good break } - ctx.Handle(500, "Repo.Commit.GetTreeEntryByPath", err) + c.Handle(500, "Repo.Commit.GetTreeEntryByPath", err) return } // User can only upload files to a directory. if !entry.IsDir() { - ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &f) + c.Data["Err_TreePath"] = true + c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &f) return } } message := strings.TrimSpace(f.CommitSummary) if len(message) == 0 { - message = ctx.Tr("repo.editor.upload_files_to_dir", f.TreePath) + message = c.Tr("repo.editor.upload_files_to_dir", f.TreePath) } f.CommitMessage = strings.TrimSpace(f.CommitMessage) @@ -492,30 +492,30 @@ func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) { message += "\n\n" + f.CommitMessage } - if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, models.UploadRepoFileOptions{ - LastCommitID: ctx.Repo.CommitID, + if err := c.Repo.Repository.UploadRepoFiles(c.User, models.UploadRepoFileOptions{ + LastCommitID: c.Repo.CommitID, OldBranch: oldBranchName, NewBranch: branchName, TreePath: f.TreePath, Message: message, Files: f.Files, }); err != nil { - ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", f.TreePath, err), UPLOAD_FILE, &f) + c.Data["Err_TreePath"] = true + c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, err), UPLOAD_FILE, &f) return } - if f.IsNewBrnach() && ctx.Repo.PullRequest.Allowed { - ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) + if f.IsNewBrnach() && c.Repo.PullRequest.Allowed { + c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) } else { - ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath) + c.Redirect(c.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath) } } -func UploadFileToServer(ctx *context.Context) { - file, header, err := ctx.Req.FormFile("file") +func UploadFileToServer(c *context.Context) { + file, header, err := c.Req.FormFile("file") if err != nil { - ctx.Error(500, fmt.Sprintf("FormFile: %v", err)) + c.Error(500, fmt.Sprintf("FormFile: %v", err)) return } defer file.Close() @@ -538,34 +538,34 @@ func UploadFileToServer(ctx *context.Context) { } if !allowed { - ctx.Error(400, ErrFileTypeForbidden.Error()) + c.Error(400, ErrFileTypeForbidden.Error()) return } } upload, err := models.NewUpload(header.Filename, buf, file) if err != nil { - ctx.Error(500, fmt.Sprintf("NewUpload: %v", err)) + c.Error(500, fmt.Sprintf("NewUpload: %v", err)) return } log.Trace("New file uploaded: %s", upload.UUID) - ctx.JSON(200, map[string]string{ + c.JSON(200, map[string]string{ "uuid": upload.UUID, }) } -func RemoveUploadFileFromServer(ctx *context.Context, f form.RemoveUploadFile) { +func RemoveUploadFileFromServer(c *context.Context, f form.RemoveUploadFile) { if len(f.File) == 0 { - ctx.Status(204) + c.Status(204) return } if err := models.DeleteUploadByUUID(f.File); err != nil { - ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err)) + c.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err)) return } log.Trace("Upload file removed: %s", f.File) - ctx.Status(204) + c.Status(204) } diff --git a/routers/repo/http.go b/routers/repo/http.go index 786fa542b..b8f519ba4 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -399,9 +399,9 @@ func getGitRepoPath(dir string) (string, error) { return filename, nil } -func HTTP(ctx *HTTPContext) { +func HTTP(c *HTTPContext) { for _, route := range routes { - reqPath := strings.ToLower(ctx.Req.URL.Path) + reqPath := strings.ToLower(c.Req.URL.Path) m := route.reg.FindStringSubmatch(reqPath) if m == nil { continue @@ -411,12 +411,12 @@ func HTTP(ctx *HTTPContext) { // but we only want to output this message only if user is really trying to access // Git HTTP endpoints. if setting.Repository.DisableHTTPGit { - ctx.HandleText(http.StatusForbidden, "Interacting with repositories by HTTP protocol is not disabled") + c.HandleText(http.StatusForbidden, "Interacting with repositories by HTTP protocol is not disabled") return } - if route.method != ctx.Req.Method { - ctx.NotFound() + if route.method != c.Req.Method { + c.NotFound() return } @@ -424,24 +424,24 @@ func HTTP(ctx *HTTPContext) { dir, err := getGitRepoPath(m[1]) if err != nil { log.Warn("HTTP.getGitRepoPath: %v", err) - ctx.NotFound() + c.NotFound() return } route.handler(serviceHandler{ - w: ctx.Resp, - r: ctx.Req.Request, + w: c.Resp, + r: c.Req.Request, dir: dir, file: file, - authUser: ctx.AuthUser, - ownerName: ctx.OwnerName, - ownerSalt: ctx.OwnerSalt, - repoID: ctx.RepoID, - repoName: ctx.RepoName, + authUser: c.AuthUser, + ownerName: c.OwnerName, + ownerSalt: c.OwnerSalt, + repoID: c.RepoID, + repoName: c.RepoName, }) return } - ctx.NotFound() + c.NotFound() } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 03d29d24a..8920bc323 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -51,101 +51,101 @@ var ( } ) -func MustEnableIssues(ctx *context.Context) { - if !ctx.Repo.Repository.EnableIssues { - ctx.Handle(404, "MustEnableIssues", nil) +func MustEnableIssues(c *context.Context) { + if !c.Repo.Repository.EnableIssues { + c.Handle(404, "MustEnableIssues", nil) return } - if ctx.Repo.Repository.EnableExternalTracker { - ctx.Redirect(ctx.Repo.Repository.ExternalTrackerURL) + if c.Repo.Repository.EnableExternalTracker { + c.Redirect(c.Repo.Repository.ExternalTrackerURL) return } } -func MustAllowPulls(ctx *context.Context) { - if !ctx.Repo.Repository.AllowsPulls() { - ctx.Handle(404, "MustAllowPulls", nil) +func MustAllowPulls(c *context.Context) { + if !c.Repo.Repository.AllowsPulls() { + c.Handle(404, "MustAllowPulls", nil) return } // User can send pull request if owns a forked repository. - if ctx.IsLogged && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID) { - ctx.Repo.PullRequest.Allowed = true - ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName + if c.IsLogged && c.User.HasForkedRepo(c.Repo.Repository.ID) { + c.Repo.PullRequest.Allowed = true + c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName } } -func RetrieveLabels(ctx *context.Context) { - labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID) +func RetrieveLabels(c *context.Context) { + labels, err := models.GetLabelsByRepoID(c.Repo.Repository.ID) if err != nil { - ctx.Handle(500, "RetrieveLabels.GetLabels", err) + c.Handle(500, "RetrieveLabels.GetLabels", err) return } for _, l := range labels { l.CalOpenIssues() } - ctx.Data["Labels"] = labels - ctx.Data["NumLabels"] = len(labels) + c.Data["Labels"] = labels + c.Data["NumLabels"] = len(labels) } -func issues(ctx *context.Context, isPullList bool) { +func issues(c *context.Context, isPullList bool) { if isPullList { - MustAllowPulls(ctx) - if ctx.Written() { + MustAllowPulls(c) + if c.Written() { return } - ctx.Data["Title"] = ctx.Tr("repo.pulls") - ctx.Data["PageIsPullList"] = true + c.Data["Title"] = c.Tr("repo.pulls") + c.Data["PageIsPullList"] = true } else { - MustEnableIssues(ctx) - if ctx.Written() { + MustEnableIssues(c) + if c.Written() { return } - ctx.Data["Title"] = ctx.Tr("repo.issues") - ctx.Data["PageIsIssueList"] = true + c.Data["Title"] = c.Tr("repo.issues") + c.Data["PageIsIssueList"] = true } - viewType := ctx.Query("type") - sortType := ctx.Query("sort") + viewType := c.Query("type") + sortType := c.Query("sort") types := []string{"assigned", "created_by", "mentioned"} if !com.IsSliceContainsStr(types, viewType) { viewType = "all" } // Must sign in to see issues about you. - if viewType != "all" && !ctx.IsLogged { - ctx.SetCookie("redirect_to", "/"+url.QueryEscape(setting.AppSubURL+ctx.Req.RequestURI), 0, setting.AppSubURL) - ctx.Redirect(setting.AppSubURL + "/user/login") + if viewType != "all" && !c.IsLogged { + c.SetCookie("redirect_to", "/"+url.QueryEscape(setting.AppSubURL+c.Req.RequestURI), 0, setting.AppSubURL) + c.Redirect(setting.AppSubURL + "/user/login") return } var ( - assigneeID = ctx.QueryInt64("assignee") + assigneeID = c.QueryInt64("assignee") posterID int64 ) filterMode := models.FILTER_MODE_YOUR_REPOS switch viewType { case "assigned": filterMode = models.FILTER_MODE_ASSIGN - assigneeID = ctx.User.ID + assigneeID = c.User.ID case "created_by": filterMode = models.FILTER_MODE_CREATE - posterID = ctx.User.ID + posterID = c.User.ID case "mentioned": filterMode = models.FILTER_MODE_MENTION } var uid int64 = -1 - if ctx.IsLogged { - uid = ctx.User.ID + if c.IsLogged { + uid = c.User.ID } - repo := ctx.Repo.Repository - selectLabels := ctx.Query("labels") - milestoneID := ctx.QueryInt64("milestone") - isShowClosed := ctx.Query("state") == "closed" + repo := c.Repo.Repository + selectLabels := c.Query("labels") + milestoneID := c.QueryInt64("milestone") + isShowClosed := c.Query("state") == "closed" issueStats := models.GetIssueStats(&models.IssueStatsOptions{ RepoID: repo.ID, UserID: uid, @@ -156,7 +156,7 @@ func issues(ctx *context.Context, isPullList bool) { IsPull: isPullList, }) - page := ctx.QueryInt("page") + page := c.QueryInt("page") if page <= 1 { page = 1 } @@ -168,7 +168,7 @@ func issues(ctx *context.Context, isPullList bool) { total = int(issueStats.ClosedCount) } pager := paginater.New(total, setting.UI.IssuePagingNum, page, 5) - ctx.Data["Page"] = pager + c.Data["Page"] = pager issues, err := models.Issues(&models.IssuesOptions{ UserID: uid, @@ -184,45 +184,45 @@ func issues(ctx *context.Context, isPullList bool) { SortType: sortType, }) if err != nil { - ctx.Handle(500, "Issues", err) + c.Handle(500, "Issues", err) return } // Get issue-user relations. pairs, err := models.GetIssueUsers(repo.ID, posterID, isShowClosed) if err != nil { - ctx.Handle(500, "GetIssueUsers", err) + c.Handle(500, "GetIssueUsers", err) return } // Get posters. for i := range issues { - if !ctx.IsLogged { + if !c.IsLogged { issues[i].IsRead = true continue } // Check read status. - idx := models.PairsContains(pairs, issues[i].ID, ctx.User.ID) + idx := models.PairsContains(pairs, issues[i].ID, c.User.ID) if idx > -1 { issues[i].IsRead = pairs[idx].IsRead } else { issues[i].IsRead = true } } - ctx.Data["Issues"] = issues + c.Data["Issues"] = issues // Get milestones. - ctx.Data["Milestones"], err = models.GetMilestonesByRepoID(repo.ID) + c.Data["Milestones"], err = models.GetMilestonesByRepoID(repo.ID) if err != nil { - ctx.Handle(500, "GetAllRepoMilestones", err) + c.Handle(500, "GetAllRepoMilestones", err) return } // Get assignees. - ctx.Data["Assignees"], err = repo.GetAssignees() + c.Data["Assignees"], err = repo.GetAssignees() if err != nil { - ctx.Handle(500, "GetAssignees", err) + c.Handle(500, "GetAssignees", err) return } @@ -230,91 +230,91 @@ func issues(ctx *context.Context, isPullList bool) { assigneeID = 0 // Reset ID to prevent unexpected selection of assignee. } - ctx.Data["IssueStats"] = issueStats - ctx.Data["SelectLabels"] = com.StrTo(selectLabels).MustInt64() - ctx.Data["ViewType"] = viewType - ctx.Data["SortType"] = sortType - ctx.Data["MilestoneID"] = milestoneID - ctx.Data["AssigneeID"] = assigneeID - ctx.Data["IsShowClosed"] = isShowClosed + c.Data["IssueStats"] = issueStats + c.Data["SelectLabels"] = com.StrTo(selectLabels).MustInt64() + c.Data["ViewType"] = viewType + c.Data["SortType"] = sortType + c.Data["MilestoneID"] = milestoneID + c.Data["AssigneeID"] = assigneeID + c.Data["IsShowClosed"] = isShowClosed if isShowClosed { - ctx.Data["State"] = "closed" + c.Data["State"] = "closed" } else { - ctx.Data["State"] = "open" + c.Data["State"] = "open" } - ctx.HTML(200, ISSUES) + c.HTML(200, ISSUES) } -func Issues(ctx *context.Context) { - issues(ctx, false) +func Issues(c *context.Context) { + issues(c, false) } -func Pulls(ctx *context.Context) { - issues(ctx, true) +func Pulls(c *context.Context) { + issues(c, true) } -func renderAttachmentSettings(ctx *context.Context) { - ctx.Data["RequireDropzone"] = true - ctx.Data["IsAttachmentEnabled"] = setting.AttachmentEnabled - ctx.Data["AttachmentAllowedTypes"] = setting.AttachmentAllowedTypes - ctx.Data["AttachmentMaxSize"] = setting.AttachmentMaxSize - ctx.Data["AttachmentMaxFiles"] = setting.AttachmentMaxFiles +func renderAttachmentSettings(c *context.Context) { + c.Data["RequireDropzone"] = true + c.Data["IsAttachmentEnabled"] = setting.AttachmentEnabled + c.Data["AttachmentAllowedTypes"] = setting.AttachmentAllowedTypes + c.Data["AttachmentMaxSize"] = setting.AttachmentMaxSize + c.Data["AttachmentMaxFiles"] = setting.AttachmentMaxFiles } -func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) { +func RetrieveRepoMilestonesAndAssignees(c *context.Context, repo *models.Repository) { var err error - ctx.Data["OpenMilestones"], err = models.GetMilestones(repo.ID, -1, false) + c.Data["OpenMilestones"], err = models.GetMilestones(repo.ID, -1, false) if err != nil { - ctx.Handle(500, "GetMilestones", err) + c.Handle(500, "GetMilestones", err) return } - ctx.Data["ClosedMilestones"], err = models.GetMilestones(repo.ID, -1, true) + c.Data["ClosedMilestones"], err = models.GetMilestones(repo.ID, -1, true) if err != nil { - ctx.Handle(500, "GetMilestones", err) + c.Handle(500, "GetMilestones", err) return } - ctx.Data["Assignees"], err = repo.GetAssignees() + c.Data["Assignees"], err = repo.GetAssignees() if err != nil { - ctx.Handle(500, "GetAssignees", err) + c.Handle(500, "GetAssignees", err) return } } -func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository) []*models.Label { - if !ctx.Repo.IsWriter() { +func RetrieveRepoMetas(c *context.Context, repo *models.Repository) []*models.Label { + if !c.Repo.IsWriter() { return nil } labels, err := models.GetLabelsByRepoID(repo.ID) if err != nil { - ctx.Handle(500, "GetLabelsByRepoID", err) + c.Handle(500, "GetLabelsByRepoID", err) return nil } - ctx.Data["Labels"] = labels + c.Data["Labels"] = labels - RetrieveRepoMilestonesAndAssignees(ctx, repo) - if ctx.Written() { + RetrieveRepoMilestonesAndAssignees(c, repo) + if c.Written() { return nil } return labels } -func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (string, bool) { +func getFileContentFromDefaultBranch(c *context.Context, filename string) (string, bool) { var r io.Reader var bytes []byte - if ctx.Repo.Commit == nil { + if c.Repo.Commit == nil { var err error - ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch) + c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(c.Repo.Repository.DefaultBranch) if err != nil { return "", false } } - entry, err := ctx.Repo.Commit.GetTreeEntryByPath(filename) + entry, err := c.Repo.Commit.GetTreeEntryByPath(filename) if err != nil { return "", false } @@ -329,44 +329,44 @@ func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (str return string(bytes), true } -func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles []string) { +func setTemplateIfExists(c *context.Context, ctxDataKey string, possibleFiles []string) { for _, filename := range possibleFiles { - content, found := getFileContentFromDefaultBranch(ctx, filename) + content, found := getFileContentFromDefaultBranch(c, filename) if found { - ctx.Data[ctxDataKey] = content + c.Data[ctxDataKey] = content return } } } -func NewIssue(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("repo.issues.new") - ctx.Data["PageIsIssueList"] = true - ctx.Data["RequireHighlightJS"] = true - ctx.Data["RequireSimpleMDE"] = true - setTemplateIfExists(ctx, ISSUE_TEMPLATE_KEY, IssueTemplateCandidates) - renderAttachmentSettings(ctx) +func NewIssue(c *context.Context) { + c.Data["Title"] = c.Tr("repo.issues.new") + c.Data["PageIsIssueList"] = true + c.Data["RequireHighlightJS"] = true + c.Data["RequireSimpleMDE"] = true + setTemplateIfExists(c, ISSUE_TEMPLATE_KEY, IssueTemplateCandidates) + renderAttachmentSettings(c) - RetrieveRepoMetas(ctx, ctx.Repo.Repository) - if ctx.Written() { + RetrieveRepoMetas(c, c.Repo.Repository) + if c.Written() { return } - ctx.HTML(200, ISSUE_NEW) + c.HTML(200, ISSUE_NEW) } -func ValidateRepoMetas(ctx *context.Context, f form.NewIssue) ([]int64, int64, int64) { +func ValidateRepoMetas(c *context.Context, f form.NewIssue) ([]int64, int64, int64) { var ( - repo = ctx.Repo.Repository + repo = c.Repo.Repository err error ) - labels := RetrieveRepoMetas(ctx, ctx.Repo.Repository) - if ctx.Written() { + labels := RetrieveRepoMetas(c, c.Repo.Repository) + if c.Written() { return nil, 0, 0 } - if !ctx.Repo.IsWriter() { + if !c.Repo.IsWriter() { return nil, 0, 0 } @@ -380,49 +380,49 @@ func ValidateRepoMetas(ctx *context.Context, f form.NewIssue) ([]int64, int64, i hasSelected = true } } - ctx.Data["HasSelectedLabel"] = hasSelected - ctx.Data["label_ids"] = f.LabelIDs - ctx.Data["Labels"] = labels + c.Data["HasSelectedLabel"] = hasSelected + c.Data["label_ids"] = f.LabelIDs + c.Data["Labels"] = labels // Check milestone. milestoneID := f.MilestoneID if milestoneID > 0 { - ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID) + c.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID) if err != nil { - ctx.Handle(500, "GetMilestoneByID", err) + c.Handle(500, "GetMilestoneByID", err) return nil, 0, 0 } - ctx.Data["milestone_id"] = milestoneID + c.Data["milestone_id"] = milestoneID } // Check assignee. assigneeID := f.AssigneeID if assigneeID > 0 { - ctx.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID) + c.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID) if err != nil { - ctx.Handle(500, "GetAssigneeByID", err) + c.Handle(500, "GetAssigneeByID", err) return nil, 0, 0 } - ctx.Data["assignee_id"] = assigneeID + c.Data["assignee_id"] = assigneeID } return labelIDs, milestoneID, assigneeID } -func NewIssuePost(ctx *context.Context, f form.NewIssue) { - ctx.Data["Title"] = ctx.Tr("repo.issues.new") - ctx.Data["PageIsIssueList"] = true - ctx.Data["RequireHighlightJS"] = true - ctx.Data["RequireSimpleMDE"] = true - renderAttachmentSettings(ctx) +func NewIssuePost(c *context.Context, f form.NewIssue) { + c.Data["Title"] = c.Tr("repo.issues.new") + c.Data["PageIsIssueList"] = true + c.Data["RequireHighlightJS"] = true + c.Data["RequireSimpleMDE"] = true + renderAttachmentSettings(c) - labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, f) - if ctx.Written() { + labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f) + if c.Written() { return } - if ctx.HasError() { - ctx.HTML(200, ISSUE_NEW) + if c.HasError() { + c.HTML(200, ISSUE_NEW) return } @@ -432,27 +432,27 @@ func NewIssuePost(ctx *context.Context, f form.NewIssue) { } issue := &models.Issue{ - RepoID: ctx.Repo.Repository.ID, + RepoID: c.Repo.Repository.ID, Title: f.Title, - PosterID: ctx.User.ID, - Poster: ctx.User, + PosterID: c.User.ID, + Poster: c.User, MilestoneID: milestoneID, AssigneeID: assigneeID, Content: f.Content, } - if err := models.NewIssue(ctx.Repo.Repository, issue, labelIDs, attachments); err != nil { - ctx.Handle(500, "NewIssue", err) + if err := models.NewIssue(c.Repo.Repository, issue, labelIDs, attachments); err != nil { + c.Handle(500, "NewIssue", err) return } - log.Trace("Issue created: %d/%d", ctx.Repo.Repository.ID, issue.ID) - ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) + log.Trace("Issue created: %d/%d", c.Repo.Repository.ID, issue.ID) + c.Redirect(c.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) } -func uploadAttachment(ctx *context.Context, allowedTypes []string) { - file, header, err := ctx.Req.FormFile("file") +func uploadAttachment(c *context.Context, allowedTypes []string) { + file, header, err := c.Req.FormFile("file") if err != nil { - ctx.Error(500, fmt.Sprintf("FormFile: %v", err)) + c.Error(500, fmt.Sprintf("FormFile: %v", err)) return } defer file.Close() @@ -474,86 +474,86 @@ func uploadAttachment(ctx *context.Context, allowedTypes []string) { } if !allowed { - ctx.Error(400, ErrFileTypeForbidden.Error()) + c.Error(400, ErrFileTypeForbidden.Error()) return } attach, err := models.NewAttachment(header.Filename, buf, file) if err != nil { - ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err)) + c.Error(500, fmt.Sprintf("NewAttachment: %v", err)) return } log.Trace("New attachment uploaded: %s", attach.UUID) - ctx.JSON(200, map[string]string{ + c.JSON(200, map[string]string{ "uuid": attach.UUID, }) } -func UploadIssueAttachment(ctx *context.Context) { +func UploadIssueAttachment(c *context.Context) { if !setting.AttachmentEnabled { - ctx.NotFound() + c.NotFound() return } - uploadAttachment(ctx, strings.Split(setting.AttachmentAllowedTypes, ",")) + uploadAttachment(c, strings.Split(setting.AttachmentAllowedTypes, ",")) } -func viewIssue(ctx *context.Context, isPullList bool) { - ctx.Data["RequireHighlightJS"] = true - ctx.Data["RequireDropzone"] = true - renderAttachmentSettings(ctx) +func viewIssue(c *context.Context, isPullList bool) { + c.Data["RequireHighlightJS"] = true + c.Data["RequireDropzone"] = true + renderAttachmentSettings(c) - index := ctx.ParamsInt64(":index") + index := c.ParamsInt64(":index") if index <= 0 { - ctx.NotFound() + c.NotFound() return } - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, index) + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, index) if err != nil { - ctx.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err) + c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err) return } - ctx.Data["Title"] = issue.Title + c.Data["Title"] = issue.Title // Make sure type and URL matches. if !isPullList && issue.IsPull { - ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) + c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) return } else if isPullList && !issue.IsPull { - ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) + c.Redirect(c.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) return } if issue.IsPull { - MustAllowPulls(ctx) - if ctx.Written() { + MustAllowPulls(c) + if c.Written() { return } - ctx.Data["PageIsPullList"] = true - ctx.Data["PageIsPullConversation"] = true + c.Data["PageIsPullList"] = true + c.Data["PageIsPullConversation"] = true } else { - MustEnableIssues(ctx) - if ctx.Written() { + MustEnableIssues(c) + if c.Written() { return } - ctx.Data["PageIsIssueList"] = true + c.Data["PageIsIssueList"] = true } - issue.RenderedContent = string(markup.Markdown(issue.Content, ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas())) + issue.RenderedContent = string(markup.Markdown(issue.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) - repo := ctx.Repo.Repository + repo := c.Repo.Repository // Get more information if it's a pull request. if issue.IsPull { if issue.PullRequest.HasMerged { - ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged - PrepareMergedViewPullInfo(ctx, issue) + c.Data["DisableStatusChange"] = issue.PullRequest.HasMerged + PrepareMergedViewPullInfo(c, issue) } else { - PrepareViewPullInfo(ctx, issue) + PrepareViewPullInfo(c, issue) } - if ctx.Written() { + if c.Written() { return } } @@ -566,7 +566,7 @@ func viewIssue(ctx *context.Context, isPullList bool) { } labels, err := models.GetLabelsByRepoID(repo.ID) if err != nil { - ctx.Handle(500, "GetLabelsByRepoID", err) + c.Handle(500, "GetLabelsByRepoID", err) return } hasSelected := false @@ -576,21 +576,21 @@ func viewIssue(ctx *context.Context, isPullList bool) { hasSelected = true } } - ctx.Data["HasSelectedLabel"] = hasSelected - ctx.Data["Labels"] = labels + c.Data["HasSelectedLabel"] = hasSelected + c.Data["Labels"] = labels // Check milestone and assignee. - if ctx.Repo.IsWriter() { - RetrieveRepoMilestonesAndAssignees(ctx, repo) - if ctx.Written() { + if c.Repo.IsWriter() { + RetrieveRepoMilestonesAndAssignees(c, repo) + if c.Written() { return } } - if ctx.IsLogged { + if c.IsLogged { // Update issue-user. - if err = issue.ReadBy(ctx.User.ID); err != nil { - ctx.Handle(500, "ReadBy", err) + if err = issue.ReadBy(c.User.ID); err != nil { + c.Handle(500, "ReadBy", err) return } } @@ -607,7 +607,7 @@ func viewIssue(ctx *context.Context, isPullList bool) { participants[0] = issue.Poster for _, comment = range issue.Comments { if comment.Type == models.COMMENT_TYPE_COMMENT { - comment.RenderedContent = string(markup.Markdown(comment.Content, ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas())) + comment.RenderedContent = string(markup.Markdown(comment.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) // Check tag. tag, ok = marked[comment.PosterID] @@ -642,145 +642,145 @@ func viewIssue(ctx *context.Context, isPullList bool) { if issue.IsPull && issue.PullRequest.HasMerged { pull := issue.PullRequest - ctx.Data["IsPullBranchDeletable"] = pull.BaseRepoID == pull.HeadRepoID && - ctx.Repo.IsWriter() && ctx.Repo.GitRepo.IsBranchExist(pull.HeadBranch) + c.Data["IsPullBranchDeletable"] = pull.BaseRepoID == pull.HeadRepoID && + c.Repo.IsWriter() && c.Repo.GitRepo.IsBranchExist(pull.HeadBranch) - deleteBranchUrl := ctx.Repo.RepoLink + "/branches/delete/" + pull.HeadBranch - ctx.Data["DeleteBranchLink"] = fmt.Sprintf("%s?commit=%s&redirect_to=%s", deleteBranchUrl, pull.MergedCommitID, ctx.Data["Link"]) + deleteBranchUrl := c.Repo.RepoLink + "/branches/delete/" + pull.HeadBranch + c.Data["DeleteBranchLink"] = fmt.Sprintf("%s?commit=%s&redirect_to=%s", deleteBranchUrl, pull.MergedCommitID, c.Data["Link"]) } - ctx.Data["Participants"] = participants - ctx.Data["NumParticipants"] = len(participants) - ctx.Data["Issue"] = issue - ctx.Data["IsIssueOwner"] = ctx.Repo.IsWriter() || (ctx.IsLogged && issue.IsPoster(ctx.User.ID)) - ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string) - ctx.HTML(200, ISSUE_VIEW) + c.Data["Participants"] = participants + c.Data["NumParticipants"] = len(participants) + c.Data["Issue"] = issue + c.Data["IsIssueOwner"] = c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID)) + c.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + c.Data["Link"].(string) + c.HTML(200, ISSUE_VIEW) } -func ViewIssue(ctx *context.Context) { - viewIssue(ctx, false) +func ViewIssue(c *context.Context) { + viewIssue(c, false) } -func ViewPull(ctx *context.Context) { - viewIssue(ctx, true) +func ViewPull(c *context.Context) { + viewIssue(c, true) } -func getActionIssue(ctx *context.Context) *models.Issue { - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) +func getActionIssue(c *context.Context) *models.Issue { + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { - ctx.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err) + c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err) return nil } // Prevent guests accessing pull requests - if !ctx.Repo.HasAccess() && issue.IsPull { - ctx.NotFound() + if !c.Repo.HasAccess() && issue.IsPull { + c.NotFound() return nil } return issue } -func UpdateIssueTitle(ctx *context.Context) { - issue := getActionIssue(ctx) - if ctx.Written() { +func UpdateIssueTitle(c *context.Context) { + issue := getActionIssue(c) + if c.Written() { return } - if !ctx.IsLogged || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter()) { - ctx.Error(403) + if !c.IsLogged || (!issue.IsPoster(c.User.ID) && !c.Repo.IsWriter()) { + c.Error(403) return } - title := ctx.QueryTrim("title") + title := c.QueryTrim("title") if len(title) == 0 { - ctx.Error(204) + c.Error(204) return } - if err := issue.ChangeTitle(ctx.User, title); err != nil { - ctx.Handle(500, "ChangeTitle", err) + if err := issue.ChangeTitle(c.User, title); err != nil { + c.Handle(500, "ChangeTitle", err) return } - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "title": issue.Title, }) } -func UpdateIssueContent(ctx *context.Context) { - issue := getActionIssue(ctx) - if ctx.Written() { +func UpdateIssueContent(c *context.Context) { + issue := getActionIssue(c) + if c.Written() { return } - if !ctx.IsLogged || (ctx.User.ID != issue.PosterID && !ctx.Repo.IsWriter()) { - ctx.Error(403) + if !c.IsLogged || (c.User.ID != issue.PosterID && !c.Repo.IsWriter()) { + c.Error(403) return } - content := ctx.Query("content") - if err := issue.ChangeContent(ctx.User, content); err != nil { - ctx.Handle(500, "ChangeContent", err) + content := c.Query("content") + if err := issue.ChangeContent(c.User, content); err != nil { + c.Handle(500, "ChangeContent", err) return } - ctx.JSON(200, map[string]string{ - "content": string(markup.Markdown(issue.Content, ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())), + c.JSON(200, map[string]string{ + "content": string(markup.Markdown(issue.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())), }) } -func UpdateIssueLabel(ctx *context.Context) { - issue := getActionIssue(ctx) - if ctx.Written() { +func UpdateIssueLabel(c *context.Context) { + issue := getActionIssue(c) + if c.Written() { return } - if ctx.Query("action") == "clear" { - if err := issue.ClearLabels(ctx.User); err != nil { - ctx.Handle(500, "ClearLabels", err) + if c.Query("action") == "clear" { + if err := issue.ClearLabels(c.User); err != nil { + c.Handle(500, "ClearLabels", err) return } } else { - isAttach := ctx.Query("action") == "attach" - label, err := models.GetLabelOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")) + isAttach := c.Query("action") == "attach" + label, err := models.GetLabelOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")) if err != nil { if models.IsErrLabelNotExist(err) { - ctx.Error(404, "GetLabelByID") + c.Error(404, "GetLabelByID") } else { - ctx.Handle(500, "GetLabelByID", err) + c.Handle(500, "GetLabelByID", err) } return } if isAttach && !issue.HasLabel(label.ID) { - if err = issue.AddLabel(ctx.User, label); err != nil { - ctx.Handle(500, "AddLabel", err) + if err = issue.AddLabel(c.User, label); err != nil { + c.Handle(500, "AddLabel", err) return } } else if !isAttach && issue.HasLabel(label.ID) { - if err = issue.RemoveLabel(ctx.User, label); err != nil { - ctx.Handle(500, "RemoveLabel", err) + if err = issue.RemoveLabel(c.User, label); err != nil { + c.Handle(500, "RemoveLabel", err) return } } } - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ok": true, }) } -func UpdateIssueMilestone(ctx *context.Context) { - issue := getActionIssue(ctx) - if ctx.Written() { +func UpdateIssueMilestone(c *context.Context) { + issue := getActionIssue(c) + if c.Written() { return } oldMilestoneID := issue.MilestoneID - milestoneID := ctx.QueryInt64("id") + milestoneID := c.QueryInt64("id") if oldMilestoneID == milestoneID { - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ok": true, }) return @@ -788,36 +788,36 @@ func UpdateIssueMilestone(ctx *context.Context) { // Not check for invalid milestone id and give responsibility to owners. issue.MilestoneID = milestoneID - if err := models.ChangeMilestoneAssign(ctx.User, issue, oldMilestoneID); err != nil { - ctx.Handle(500, "ChangeMilestoneAssign", err) + if err := models.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil { + c.Handle(500, "ChangeMilestoneAssign", err) return } - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ok": true, }) } -func UpdateIssueAssignee(ctx *context.Context) { - issue := getActionIssue(ctx) - if ctx.Written() { +func UpdateIssueAssignee(c *context.Context) { + issue := getActionIssue(c) + if c.Written() { return } - assigneeID := ctx.QueryInt64("id") + assigneeID := c.QueryInt64("id") if issue.AssigneeID == assigneeID { - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ok": true, }) return } - if err := issue.ChangeAssignee(ctx.User, assigneeID); err != nil { - ctx.Handle(500, "ChangeAssignee", err) + if err := issue.ChangeAssignee(c.User, assigneeID); err != nil { + c.Handle(500, "ChangeAssignee", err) return } - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "ok": true, }) } @@ -908,128 +908,128 @@ func NewComment(c *context.Context, f form.CreateComment) { log.Trace("Comment created: %d/%d/%d", c.Repo.Repository.ID, issue.ID, comment.ID) } -func UpdateCommentContent(ctx *context.Context) { - comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) +func UpdateCommentContent(c *context.Context) { + comment, err := models.GetCommentByID(c.ParamsInt64(":id")) if err != nil { - ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err) + c.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err) return } - if ctx.UserID() != comment.PosterID && !ctx.Repo.IsAdmin() { - ctx.Error(404) + if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() { + c.Error(404) return } else if comment.Type != models.COMMENT_TYPE_COMMENT { - ctx.Error(204) + c.Error(204) return } oldContent := comment.Content - comment.Content = ctx.Query("content") + comment.Content = c.Query("content") if len(comment.Content) == 0 { - ctx.JSON(200, map[string]interface{}{ + c.JSON(200, map[string]interface{}{ "content": "", }) return } - if err = models.UpdateComment(ctx.User, comment, oldContent); err != nil { - ctx.Handle(500, "UpdateComment", err) + if err = models.UpdateComment(c.User, comment, oldContent); err != nil { + c.Handle(500, "UpdateComment", err) return } - ctx.JSON(200, map[string]string{ - "content": string(markup.Markdown(comment.Content, ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())), + c.JSON(200, map[string]string{ + "content": string(markup.Markdown(comment.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())), }) } -func DeleteComment(ctx *context.Context) { - comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) +func DeleteComment(c *context.Context) { + comment, err := models.GetCommentByID(c.ParamsInt64(":id")) if err != nil { - ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err) + c.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err) return } - if ctx.UserID() != comment.PosterID && !ctx.Repo.IsAdmin() { - ctx.Error(404) + if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() { + c.Error(404) return } else if comment.Type != models.COMMENT_TYPE_COMMENT { - ctx.Error(204) + c.Error(204) return } - if err = models.DeleteCommentByID(ctx.User, comment.ID); err != nil { - ctx.Handle(500, "DeleteCommentByID", err) + if err = models.DeleteCommentByID(c.User, comment.ID); err != nil { + c.Handle(500, "DeleteCommentByID", err) return } - ctx.Status(200) + c.Status(200) } -func Labels(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("repo.labels") - ctx.Data["PageIsIssueList"] = true - ctx.Data["PageIsLabels"] = true - ctx.Data["RequireMinicolors"] = true - ctx.Data["LabelTemplates"] = models.LabelTemplates - ctx.HTML(200, LABELS) +func Labels(c *context.Context) { + c.Data["Title"] = c.Tr("repo.labels") + c.Data["PageIsIssueList"] = true + c.Data["PageIsLabels"] = true + c.Data["RequireMinicolors"] = true + c.Data["LabelTemplates"] = models.LabelTemplates + c.HTML(200, LABELS) } -func InitializeLabels(ctx *context.Context, f form.InitializeLabels) { - if ctx.HasError() { - ctx.Redirect(ctx.Repo.RepoLink + "/labels") +func InitializeLabels(c *context.Context, f form.InitializeLabels) { + if c.HasError() { + c.Redirect(c.Repo.RepoLink + "/labels") return } list, err := models.GetLabelTemplateFile(f.TemplateName) if err != nil { - ctx.Flash.Error(ctx.Tr("repo.issues.label_templates.fail_to_load_file", f.TemplateName, err)) - ctx.Redirect(ctx.Repo.RepoLink + "/labels") + c.Flash.Error(c.Tr("repo.issues.label_templates.fail_to_load_file", f.TemplateName, err)) + c.Redirect(c.Repo.RepoLink + "/labels") return } labels := make([]*models.Label, len(list)) for i := 0; i < len(list); i++ { labels[i] = &models.Label{ - RepoID: ctx.Repo.Repository.ID, + RepoID: c.Repo.Repository.ID, Name: list[i][0], Color: list[i][1], } } if err := models.NewLabels(labels...); err != nil { - ctx.Handle(500, "NewLabels", err) + c.Handle(500, "NewLabels", err) return } - ctx.Redirect(ctx.Repo.RepoLink + "/labels") + c.Redirect(c.Repo.RepoLink + "/labels") } -func NewLabel(ctx *context.Context, f form.CreateLabel) { - ctx.Data["Title"] = ctx.Tr("repo.labels") - ctx.Data["PageIsLabels"] = true +func NewLabel(c *context.Context, f form.CreateLabel) { + c.Data["Title"] = c.Tr("repo.labels") + c.Data["PageIsLabels"] = true - if ctx.HasError() { - ctx.Flash.Error(ctx.Data["ErrorMsg"].(string)) - ctx.Redirect(ctx.Repo.RepoLink + "/labels") + if c.HasError() { + c.Flash.Error(c.Data["ErrorMsg"].(string)) + c.Redirect(c.Repo.RepoLink + "/labels") return } l := &models.Label{ - RepoID: ctx.Repo.Repository.ID, + RepoID: c.Repo.Repository.ID, Name: f.Title, Color: f.Color, } if err := models.NewLabels(l); err != nil { - ctx.Handle(500, "NewLabel", err) + c.Handle(500, "NewLabel", err) return } - ctx.Redirect(ctx.Repo.RepoLink + "/labels") + c.Redirect(c.Repo.RepoLink + "/labels") } -func UpdateLabel(ctx *context.Context, f form.CreateLabel) { +func UpdateLabel(c *context.Context, f form.CreateLabel) { l, err := models.GetLabelByID(f.ID) if err != nil { switch { case models.IsErrLabelNotExist(err): - ctx.Error(404) + c.Error(404) default: - ctx.Handle(500, "UpdateLabel", err) + c.Handle(500, "UpdateLabel", err) } return } @@ -1037,36 +1037,36 @@ func UpdateLabel(ctx *context.Context, f form.CreateLabel) { l.Name = f.Title l.Color = f.Color if err := models.UpdateLabel(l); err != nil { - ctx.Handle(500, "UpdateLabel", err) + c.Handle(500, "UpdateLabel", err) return } - ctx.Redirect(ctx.Repo.RepoLink + "/labels") + c.Redirect(c.Repo.RepoLink + "/labels") } -func DeleteLabel(ctx *context.Context) { - if err := models.DeleteLabel(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil { - ctx.Flash.Error("DeleteLabel: " + err.Error()) +func DeleteLabel(c *context.Context) { + if err := models.DeleteLabel(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil { + c.Flash.Error("DeleteLabel: " + err.Error()) } else { - ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success")) + c.Flash.Success(c.Tr("repo.issues.label_deletion_success")) } - ctx.JSON(200, map[string]interface{}{ - "redirect": ctx.Repo.RepoLink + "/labels", + c.JSON(200, map[string]interface{}{ + "redirect": c.Repo.RepoLink + "/labels", }) return } -func Milestones(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("repo.milestones") - ctx.Data["PageIsIssueList"] = true - ctx.Data["PageIsMilestones"] = true +func Milestones(c *context.Context) { + c.Data["Title"] = c.Tr("repo.milestones") + c.Data["PageIsIssueList"] = true + c.Data["PageIsMilestones"] = true - isShowClosed := ctx.Query("state") == "closed" - openCount, closedCount := models.MilestoneStats(ctx.Repo.Repository.ID) - ctx.Data["OpenCount"] = openCount - ctx.Data["ClosedCount"] = closedCount + isShowClosed := c.Query("state") == "closed" + openCount, closedCount := models.MilestoneStats(c.Repo.Repository.ID) + c.Data["OpenCount"] = openCount + c.Data["ClosedCount"] = closedCount - page := ctx.QueryInt("page") + page := c.QueryInt("page") if page <= 1 { page = 1 } @@ -1077,11 +1077,11 @@ func Milestones(ctx *context.Context) { } else { total = int(closedCount) } - ctx.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5) + c.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5) - miles, err := models.GetMilestones(ctx.Repo.Repository.ID, page, isShowClosed) + miles, err := models.GetMilestones(c.Repo.Repository.ID, page, isShowClosed) if err != nil { - ctx.Handle(500, "GetMilestones", err) + c.Handle(500, "GetMilestones", err) return } for _, m := range miles { @@ -1090,38 +1090,38 @@ func Milestones(ctx *context.Context) { if m.NumOpenIssues+m.NumClosedIssues > 0 { m.Completeness = m.NumClosedIssues * 100 / (m.NumOpenIssues + m.NumClosedIssues) } - m.RenderedContent = string(markup.Markdown(m.Content, ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas())) + m.RenderedContent = string(markup.Markdown(m.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) } - ctx.Data["Milestones"] = miles + c.Data["Milestones"] = miles if isShowClosed { - ctx.Data["State"] = "closed" + c.Data["State"] = "closed" } else { - ctx.Data["State"] = "open" + c.Data["State"] = "open" } - ctx.Data["IsShowClosed"] = isShowClosed - ctx.HTML(200, MILESTONE) + c.Data["IsShowClosed"] = isShowClosed + c.HTML(200, MILESTONE) } -func NewMilestone(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("repo.milestones.new") - ctx.Data["PageIsIssueList"] = true - ctx.Data["PageIsMilestones"] = true - ctx.Data["RequireDatetimepicker"] = true - ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) - ctx.HTML(200, MILESTONE_NEW) +func NewMilestone(c *context.Context) { + c.Data["Title"] = c.Tr("repo.milestones.new") + c.Data["PageIsIssueList"] = true + c.Data["PageIsMilestones"] = true + c.Data["RequireDatetimepicker"] = true + c.Data["DateLang"] = setting.DateLang(c.Locale.Language()) + c.HTML(200, MILESTONE_NEW) } -func NewMilestonePost(ctx *context.Context, f form.CreateMilestone) { - ctx.Data["Title"] = ctx.Tr("repo.milestones.new") - ctx.Data["PageIsIssueList"] = true - ctx.Data["PageIsMilestones"] = true - ctx.Data["RequireDatetimepicker"] = true - ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) +func NewMilestonePost(c *context.Context, f form.CreateMilestone) { + c.Data["Title"] = c.Tr("repo.milestones.new") + c.Data["PageIsIssueList"] = true + c.Data["PageIsMilestones"] = true + c.Data["RequireDatetimepicker"] = true + c.Data["DateLang"] = setting.DateLang(c.Locale.Language()) - if ctx.HasError() { - ctx.HTML(200, MILESTONE_NEW) + if c.HasError() { + c.HTML(200, MILESTONE_NEW) return } @@ -1130,58 +1130,58 @@ func NewMilestonePost(ctx *context.Context, f form.CreateMilestone) { } deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local) if err != nil { - ctx.Data["Err_Deadline"] = true - ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f) + c.Data["Err_Deadline"] = true + c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f) return } if err = models.NewMilestone(&models.Milestone{ - RepoID: ctx.Repo.Repository.ID, + RepoID: c.Repo.Repository.ID, Name: f.Title, Content: f.Content, Deadline: deadline, }); err != nil { - ctx.Handle(500, "NewMilestone", err) + c.Handle(500, "NewMilestone", err) return } - ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", f.Title)) - ctx.Redirect(ctx.Repo.RepoLink + "/milestones") + c.Flash.Success(c.Tr("repo.milestones.create_success", f.Title)) + c.Redirect(c.Repo.RepoLink + "/milestones") } -func EditMilestone(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("repo.milestones.edit") - ctx.Data["PageIsMilestones"] = true - ctx.Data["PageIsEditMilestone"] = true - ctx.Data["RequireDatetimepicker"] = true - ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) +func EditMilestone(c *context.Context) { + c.Data["Title"] = c.Tr("repo.milestones.edit") + c.Data["PageIsMilestones"] = true + c.Data["PageIsEditMilestone"] = true + c.Data["RequireDatetimepicker"] = true + c.Data["DateLang"] = setting.DateLang(c.Locale.Language()) - m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) + m, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if models.IsErrMilestoneNotExist(err) { - ctx.Handle(404, "", nil) + c.Handle(404, "", nil) } else { - ctx.Handle(500, "GetMilestoneByRepoID", err) + c.Handle(500, "GetMilestoneByRepoID", err) } return } - ctx.Data["title"] = m.Name - ctx.Data["content"] = m.Content + c.Data["title"] = m.Name + c.Data["content"] = m.Content if len(m.DeadlineString) > 0 { - ctx.Data["deadline"] = m.DeadlineString + c.Data["deadline"] = m.DeadlineString } - ctx.HTML(200, MILESTONE_NEW) + c.HTML(200, MILESTONE_NEW) } -func EditMilestonePost(ctx *context.Context, f form.CreateMilestone) { - ctx.Data["Title"] = ctx.Tr("repo.milestones.edit") - ctx.Data["PageIsMilestones"] = true - ctx.Data["PageIsEditMilestone"] = true - ctx.Data["RequireDatetimepicker"] = true - ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) +func EditMilestonePost(c *context.Context, f form.CreateMilestone) { + c.Data["Title"] = c.Tr("repo.milestones.edit") + c.Data["PageIsMilestones"] = true + c.Data["PageIsEditMilestone"] = true + c.Data["RequireDatetimepicker"] = true + c.Data["DateLang"] = setting.DateLang(c.Locale.Language()) - if ctx.HasError() { - ctx.HTML(200, MILESTONE_NEW) + if c.HasError() { + c.HTML(200, MILESTONE_NEW) return } @@ -1190,17 +1190,17 @@ func EditMilestonePost(ctx *context.Context, f form.CreateMilestone) { } deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local) if err != nil { - ctx.Data["Err_Deadline"] = true - ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f) + c.Data["Err_Deadline"] = true + c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f) return } - m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) + m, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if models.IsErrMilestoneNotExist(err) { - ctx.Handle(404, "", nil) + c.Handle(404, "", nil) } else { - ctx.Handle(500, "GetMilestoneByRepoID", err) + c.Handle(500, "GetMilestoneByRepoID", err) } return } @@ -1208,56 +1208,56 @@ func EditMilestonePost(ctx *context.Context, f form.CreateMilestone) { m.Content = f.Content m.Deadline = deadline if err = models.UpdateMilestone(m); err != nil { - ctx.Handle(500, "UpdateMilestone", err) + c.Handle(500, "UpdateMilestone", err) return } - ctx.Flash.Success(ctx.Tr("repo.milestones.edit_success", m.Name)) - ctx.Redirect(ctx.Repo.RepoLink + "/milestones") + c.Flash.Success(c.Tr("repo.milestones.edit_success", m.Name)) + c.Redirect(c.Repo.RepoLink + "/milestones") } -func ChangeMilestonStatus(ctx *context.Context) { - m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) +func ChangeMilestonStatus(c *context.Context) { + m, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if models.IsErrMilestoneNotExist(err) { - ctx.Handle(404, "", err) + c.Handle(404, "", err) } else { - ctx.Handle(500, "GetMilestoneByRepoID", err) + c.Handle(500, "GetMilestoneByRepoID", err) } return } - switch ctx.Params(":action") { + switch c.Params(":action") { case "open": if m.IsClosed { if err = models.ChangeMilestoneStatus(m, false); err != nil { - ctx.Handle(500, "ChangeMilestoneStatus", err) + c.Handle(500, "ChangeMilestoneStatus", err) return } } - ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=open") + c.Redirect(c.Repo.RepoLink + "/milestones?state=open") case "close": if !m.IsClosed { m.ClosedDate = time.Now() if err = models.ChangeMilestoneStatus(m, true); err != nil { - ctx.Handle(500, "ChangeMilestoneStatus", err) + c.Handle(500, "ChangeMilestoneStatus", err) return } } - ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=closed") + c.Redirect(c.Repo.RepoLink + "/milestones?state=closed") default: - ctx.Redirect(ctx.Repo.RepoLink + "/milestones") + c.Redirect(c.Repo.RepoLink + "/milestones") } } -func DeleteMilestone(ctx *context.Context) { - if err := models.DeleteMilestoneOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil { - ctx.Flash.Error("DeleteMilestoneByRepoID: " + err.Error()) +func DeleteMilestone(c *context.Context) { + if err := models.DeleteMilestoneOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil { + c.Flash.Error("DeleteMilestoneByRepoID: " + err.Error()) } else { - ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success")) + c.Flash.Success(c.Tr("repo.milestones.deletion_success")) } - ctx.JSON(200, map[string]interface{}{ - "redirect": ctx.Repo.RepoLink + "/milestones", + c.JSON(200, map[string]interface{}{ + "redirect": c.Repo.RepoLink + "/milestones", }) } diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 15e283d13..f3fcd5dc6 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -39,124 +39,124 @@ var ( } ) -func parseBaseRepository(ctx *context.Context) *models.Repository { - baseRepo, err := models.GetRepositoryByID(ctx.ParamsInt64(":repoid")) +func parseBaseRepository(c *context.Context) *models.Repository { + baseRepo, err := models.GetRepositoryByID(c.ParamsInt64(":repoid")) if err != nil { - ctx.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err) + c.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err) return nil } - if !baseRepo.CanBeForked() || !baseRepo.HasAccess(ctx.User.ID) { - ctx.NotFound() + if !baseRepo.CanBeForked() || !baseRepo.HasAccess(c.User.ID) { + c.NotFound() return nil } - ctx.Data["repo_name"] = baseRepo.Name - ctx.Data["description"] = baseRepo.Description - ctx.Data["IsPrivate"] = baseRepo.IsPrivate + c.Data["repo_name"] = baseRepo.Name + c.Data["description"] = baseRepo.Description + c.Data["IsPrivate"] = baseRepo.IsPrivate if err = baseRepo.GetOwner(); err != nil { - ctx.Handle(500, "GetOwner", err) + c.Handle(500, "GetOwner", err) return nil } - ctx.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name + c.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name - if err := ctx.User.GetOrganizations(true); err != nil { - ctx.Handle(500, "GetOrganizations", err) + if err := c.User.GetOrganizations(true); err != nil { + c.Handle(500, "GetOrganizations", err) return nil } - ctx.Data["Orgs"] = ctx.User.Orgs + c.Data["Orgs"] = c.User.Orgs return baseRepo } -func Fork(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("new_fork") +func Fork(c *context.Context) { + c.Data["Title"] = c.Tr("new_fork") - parseBaseRepository(ctx) - if ctx.Written() { + parseBaseRepository(c) + if c.Written() { return } - ctx.Data["ContextUser"] = ctx.User - ctx.HTML(200, FORK) + c.Data["ContextUser"] = c.User + c.HTML(200, FORK) } -func ForkPost(ctx *context.Context, f form.CreateRepo) { - ctx.Data["Title"] = ctx.Tr("new_fork") +func ForkPost(c *context.Context, f form.CreateRepo) { + c.Data["Title"] = c.Tr("new_fork") - baseRepo := parseBaseRepository(ctx) - if ctx.Written() { + baseRepo := parseBaseRepository(c) + if c.Written() { return } - ctxUser := checkContextUser(ctx, f.UserID) - if ctx.Written() { + ctxUser := checkContextUser(c, f.UserID) + if c.Written() { return } - ctx.Data["ContextUser"] = ctxUser + c.Data["ContextUser"] = ctxUser - if ctx.HasError() { - ctx.HTML(200, FORK) + if c.HasError() { + c.HTML(200, FORK) return } repo, has := models.HasForkedRepo(ctxUser.ID, baseRepo.ID) if has { - ctx.Redirect(repo.Link()) + c.Redirect(repo.Link()) return } // Check ownership of organization. - if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(ctx.User.ID) { - ctx.Error(403) + if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(c.User.ID) { + c.Error(403) return } // Cannot fork to same owner if ctxUser.ID == baseRepo.OwnerID { - ctx.RenderWithErr(ctx.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &f) + c.RenderWithErr(c.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &f) return } - repo, err := models.ForkRepository(ctx.User, ctxUser, baseRepo, f.RepoName, f.Description) + repo, err := models.ForkRepository(c.User, ctxUser, baseRepo, f.RepoName, f.Description) if err != nil { - ctx.Data["Err_RepoName"] = true + c.Data["Err_RepoName"] = true switch { case models.IsErrRepoAlreadyExist(err): - ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), FORK, &f) + c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), FORK, &f) case models.IsErrNameReserved(err): - ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &f) + c.RenderWithErr(c.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &f) case models.IsErrNamePatternNotAllowed(err): - ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &f) + c.RenderWithErr(c.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &f) default: - ctx.Handle(500, "ForkPost", err) + c.Handle(500, "ForkPost", err) } return } log.Trace("Repository forked from '%s' -> '%s'", baseRepo.FullName(), repo.FullName()) - ctx.Redirect(repo.Link()) + c.Redirect(repo.Link()) } -func checkPullInfo(ctx *context.Context) *models.Issue { - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) +func checkPullInfo(c *context.Context) *models.Issue { + issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { - ctx.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err) + c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err) return nil } - ctx.Data["Title"] = issue.Title - ctx.Data["Issue"] = issue + c.Data["Title"] = issue.Title + c.Data["Issue"] = issue if !issue.IsPull { - ctx.Handle(404, "ViewPullCommits", nil) + c.Handle(404, "ViewPullCommits", nil) return nil } - if ctx.IsLogged { + if c.IsLogged { // Update issue-user. - if err = issue.ReadBy(ctx.User.ID); err != nil { - ctx.Handle(500, "ReadBy", err) + if err = issue.ReadBy(c.User.ID); err != nil { + c.Handle(500, "ReadBy", err) return nil } } @@ -164,31 +164,31 @@ func checkPullInfo(ctx *context.Context) *models.Issue { return issue } -func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) { +func PrepareMergedViewPullInfo(c *context.Context, issue *models.Issue) { pull := issue.PullRequest - ctx.Data["HasMerged"] = true - ctx.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch - ctx.Data["BaseTarget"] = ctx.Repo.Owner.Name + "/" + pull.BaseBranch + c.Data["HasMerged"] = true + c.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch + c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch var err error - ctx.Data["NumCommits"], err = ctx.Repo.GitRepo.CommitsCountBetween(pull.MergeBase, pull.MergedCommitID) + c.Data["NumCommits"], err = c.Repo.GitRepo.CommitsCountBetween(pull.MergeBase, pull.MergedCommitID) if err != nil { - ctx.Handle(500, "Repo.GitRepo.CommitsCountBetween", err) + c.Handle(500, "Repo.GitRepo.CommitsCountBetween", err) return } - ctx.Data["NumFiles"], err = ctx.Repo.GitRepo.FilesCountBetween(pull.MergeBase, pull.MergedCommitID) + c.Data["NumFiles"], err = c.Repo.GitRepo.FilesCountBetween(pull.MergeBase, pull.MergedCommitID) if err != nil { - ctx.Handle(500, "Repo.GitRepo.FilesCountBetween", err) + c.Handle(500, "Repo.GitRepo.FilesCountBetween", err) return } } -func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullRequestInfo { - repo := ctx.Repo.Repository +func PrepareViewPullInfo(c *context.Context, issue *models.Issue) *git.PullRequestInfo { + repo := c.Repo.Repository pull := issue.PullRequest - ctx.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch - ctx.Data["BaseTarget"] = ctx.Repo.Owner.Name + "/" + pull.BaseBranch + c.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch + c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch var ( headGitRepo *git.Repository @@ -198,16 +198,16 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullReq if pull.HeadRepo != nil { headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath()) if err != nil { - ctx.Handle(500, "OpenRepository", err) + c.Handle(500, "OpenRepository", err) return nil } } if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) { - ctx.Data["IsPullReuqestBroken"] = true - ctx.Data["HeadTarget"] = "deleted" - ctx.Data["NumCommits"] = 0 - ctx.Data["NumFiles"] = 0 + c.Data["IsPullReuqestBroken"] = true + c.Data["HeadTarget"] = "deleted" + c.Data["NumCommits"] = 0 + c.Data["NumFiles"] = 0 return nil } @@ -215,82 +215,82 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullReq pull.BaseBranch, pull.HeadBranch) if err != nil { if strings.Contains(err.Error(), "fatal: Not a valid object name") { - ctx.Data["IsPullReuqestBroken"] = true - ctx.Data["BaseTarget"] = "deleted" - ctx.Data["NumCommits"] = 0 - ctx.Data["NumFiles"] = 0 + c.Data["IsPullReuqestBroken"] = true + c.Data["BaseTarget"] = "deleted" + c.Data["NumCommits"] = 0 + c.Data["NumFiles"] = 0 return nil } - ctx.Handle(500, "GetPullRequestInfo", err) + c.Handle(500, "GetPullRequestInfo", err) return nil } - ctx.Data["NumCommits"] = prInfo.Commits.Len() - ctx.Data["NumFiles"] = prInfo.NumFiles + c.Data["NumCommits"] = prInfo.Commits.Len() + c.Data["NumFiles"] = prInfo.NumFiles return prInfo } -func ViewPullCommits(ctx *context.Context) { - ctx.Data["PageIsPullList"] = true - ctx.Data["PageIsPullCommits"] = true +func ViewPullCommits(c *context.Context) { + c.Data["PageIsPullList"] = true + c.Data["PageIsPullCommits"] = true - issue := checkPullInfo(ctx) - if ctx.Written() { + issue := checkPullInfo(c) + if c.Written() { return } pull := issue.PullRequest if pull.HeadRepo != nil { - ctx.Data["Username"] = pull.HeadUserName - ctx.Data["Reponame"] = pull.HeadRepo.Name + c.Data["Username"] = pull.HeadUserName + c.Data["Reponame"] = pull.HeadRepo.Name } var commits *list.List if pull.HasMerged { - PrepareMergedViewPullInfo(ctx, issue) - if ctx.Written() { + PrepareMergedViewPullInfo(c, issue) + if c.Written() { return } - startCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergeBase) + startCommit, err := c.Repo.GitRepo.GetCommit(pull.MergeBase) if err != nil { - ctx.Handle(500, "Repo.GitRepo.GetCommit", err) + c.Handle(500, "Repo.GitRepo.GetCommit", err) return } - endCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergedCommitID) + endCommit, err := c.Repo.GitRepo.GetCommit(pull.MergedCommitID) if err != nil { - ctx.Handle(500, "Repo.GitRepo.GetCommit", err) + c.Handle(500, "Repo.GitRepo.GetCommit", err) return } - commits, err = ctx.Repo.GitRepo.CommitsBetween(endCommit, startCommit) + commits, err = c.Repo.GitRepo.CommitsBetween(endCommit, startCommit) if err != nil { - ctx.Handle(500, "Repo.GitRepo.CommitsBetween", err) + c.Handle(500, "Repo.GitRepo.CommitsBetween", err) return } } else { - prInfo := PrepareViewPullInfo(ctx, issue) - if ctx.Written() { + prInfo := PrepareViewPullInfo(c, issue) + if c.Written() { return } else if prInfo == nil { - ctx.Handle(404, "ViewPullCommits", nil) + c.Handle(404, "ViewPullCommits", nil) return } commits = prInfo.Commits } commits = models.ValidateCommitsWithEmails(commits) - ctx.Data["Commits"] = commits - ctx.Data["CommitsCount"] = commits.Len() + c.Data["Commits"] = commits + c.Data["CommitsCount"] = commits.Len() - ctx.HTML(200, PULL_COMMITS) + c.HTML(200, PULL_COMMITS) } -func ViewPullFiles(ctx *context.Context) { - ctx.Data["PageIsPullList"] = true - ctx.Data["PageIsPullFiles"] = true +func ViewPullFiles(c *context.Context) { + c.Data["PageIsPullList"] = true + c.Data["PageIsPullFiles"] = true - issue := checkPullInfo(ctx) - if ctx.Written() { + issue := checkPullInfo(c) + if c.Written() { return } pull := issue.PullRequest @@ -303,21 +303,21 @@ func ViewPullFiles(ctx *context.Context) { ) if pull.HasMerged { - PrepareMergedViewPullInfo(ctx, issue) - if ctx.Written() { + PrepareMergedViewPullInfo(c, issue) + if c.Written() { return } - diffRepoPath = ctx.Repo.GitRepo.Path + diffRepoPath = c.Repo.GitRepo.Path startCommitID = pull.MergeBase endCommitID = pull.MergedCommitID - gitRepo = ctx.Repo.GitRepo + gitRepo = c.Repo.GitRepo } else { - prInfo := PrepareViewPullInfo(ctx, issue) - if ctx.Written() { + prInfo := PrepareViewPullInfo(c, issue) + if c.Written() { return } else if prInfo == nil { - ctx.Handle(404, "ViewPullFiles", nil) + c.Handle(404, "ViewPullFiles", nil) return } @@ -325,13 +325,13 @@ func ViewPullFiles(ctx *context.Context) { headGitRepo, err := git.OpenRepository(headRepoPath) if err != nil { - ctx.Handle(500, "OpenRepository", err) + c.Handle(500, "OpenRepository", err) return } headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch) if err != nil { - ctx.Handle(500, "GetBranchCommitID", err) + c.Handle(500, "GetBranchCommitID", err) return } @@ -345,89 +345,89 @@ func ViewPullFiles(ctx *context.Context) { startCommitID, endCommitID, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles) if err != nil { - ctx.Handle(500, "GetDiffRange", err) + c.Handle(500, "GetDiffRange", err) return } - ctx.Data["Diff"] = diff - ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 + c.Data["Diff"] = diff + c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 commit, err := gitRepo.GetCommit(endCommitID) if err != nil { - ctx.Handle(500, "GetCommit", err) + c.Handle(500, "GetCommit", err) return } - setEditorconfigIfExists(ctx) - if ctx.Written() { + setEditorconfigIfExists(c) + if c.Written() { return } - ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split" - ctx.Data["IsImageFile"] = commit.IsImageFile + c.Data["IsSplitStyle"] = c.Query("style") == "split" + c.Data["IsImageFile"] = commit.IsImageFile // It is possible head repo has been deleted for merged pull requests if pull.HeadRepo != nil { - ctx.Data["Username"] = pull.HeadUserName - ctx.Data["Reponame"] = pull.HeadRepo.Name + c.Data["Username"] = pull.HeadUserName + c.Data["Reponame"] = pull.HeadRepo.Name headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name) - ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID) - ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID) - ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID) + c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID) + c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID) + c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID) } - ctx.Data["RequireHighlightJS"] = true - ctx.HTML(200, PULL_FILES) + c.Data["RequireHighlightJS"] = true + c.HTML(200, PULL_FILES) } -func MergePullRequest(ctx *context.Context) { - issue := checkPullInfo(ctx) - if ctx.Written() { +func MergePullRequest(c *context.Context) { + issue := checkPullInfo(c) + if c.Written() { return } if issue.IsClosed { - ctx.Handle(404, "MergePullRequest", nil) + c.Handle(404, "MergePullRequest", nil) return } pr, err := models.GetPullRequestByIssueID(issue.ID) if err != nil { - ctx.NotFoundOrServerError("GetPullRequestByIssueID", models.IsErrPullRequestNotExist, err) + c.NotFoundOrServerError("GetPullRequestByIssueID", models.IsErrPullRequestNotExist, err) return } if !pr.CanAutoMerge() || pr.HasMerged { - ctx.Handle(404, "MergePullRequest", nil) + c.Handle(404, "MergePullRequest", nil) return } pr.Issue = issue - pr.Issue.Repo = ctx.Repo.Repository - if err = pr.Merge(ctx.User, ctx.Repo.GitRepo); err != nil { - ctx.Handle(500, "Merge", err) + pr.Issue.Repo = c.Repo.Repository + if err = pr.Merge(c.User, c.Repo.GitRepo); err != nil { + c.Handle(500, "Merge", err) return } log.Trace("Pull request merged: %d", pr.ID) - ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) + c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) } -func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) { - baseRepo := ctx.Repo.Repository +func ParseCompareInfo(c *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) { + baseRepo := c.Repo.Repository // Get compared branches information // format: