Browse Source

Refactoring: rename ctx -> c

pull/4548/head
Unknwon 8 years ago
parent
commit
2478b87432
No known key found for this signature in database
GPG Key ID: 25B575AE3213B2B3
  1. 82
      cmd/web.go
  2. 26
      pkg/context/api.go
  3. 54
      pkg/context/auth.go
  4. 78
      pkg/context/context.go
  5. 94
      pkg/context/org.go
  6. 270
      pkg/context/repo.go
  7. 126
      routers/admin/admin.go
  8. 156
      routers/admin/auths.go
  9. 42
      routers/admin/notice.go
  10. 10
      routers/admin/orgs.go
  11. 42
      routers/admin/repos.go
  12. 164
      routers/admin/users.go
  13. 12
      routers/api/v1/admin/org.go
  14. 32
      routers/api/v1/admin/org_repo.go
  15. 34
      routers/api/v1/admin/org_team.go
  16. 8
      routers/api/v1/admin/repo.go
  17. 64
      routers/api/v1/admin/user.go
  18. 88
      routers/api/v1/api.go
  19. 20
      routers/api/v1/misc/markdown.go
  20. 34
      routers/api/v1/org/org.go
  21. 8
      routers/api/v1/org/team.go
  22. 28
      routers/api/v1/repo/branch.go
  23. 56
      routers/api/v1/repo/collaborators.go
  24. 44
      routers/api/v1/repo/file.go
  25. 56
      routers/api/v1/repo/hook.go
  26. 100
      routers/api/v1/repo/issue.go
  27. 78
      routers/api/v1/repo/issue_comment.go
  28. 96
      routers/api/v1/repo/issue_label.go
  29. 62
      routers/api/v1/repo/key.go
  30. 58
      routers/api/v1/repo/label.go
  31. 48
      routers/api/v1/repo/milestone.go
  32. 192
      routers/api/v1/repo/repo.go
  33. 16
      routers/api/v1/user/app.go
  34. 30
      routers/api/v1/user/email.go
  35. 94
      routers/api/v1/user/follower.go
  36. 62
      routers/api/v1/user/key.go
  37. 28
      routers/api/v1/user/user.go
  38. 20
      routers/dev/template.go
  39. 94
      routers/home.go
  40. 80
      routers/org/members.go
  41. 28
      routers/org/org.go
  42. 122
      routers/org/setting.go
  43. 202
      routers/org/teams.go
  44. 68
      routers/repo/branch.go
  45. 194
      routers/repo/commit.go
  46. 30
      routers/repo/download.go
  47. 204
      routers/repo/editor.go
  48. 28
      routers/repo/http.go
  49. 768
      routers/repo/issue.go
  50. 430
      routers/repo/pull.go
  51. 218
      routers/repo/release.go
  52. 212
      routers/repo/repo.go
  53. 476
      routers/repo/setting.go
  54. 192
      routers/repo/view.go
  55. 338
      routers/repo/webhook.go
  56. 178
      routers/repo/wiki.go
  57. 230
      routers/user/auth.go
  58. 204
      routers/user/home.go
  59. 108
      routers/user/profile.go

82
cmd/web.go

@ -156,9 +156,9 @@ func newMacaron() *macaron.Macaron {
return m return m
} }
func runWeb(ctx *cli.Context) error { func runWeb(c *cli.Context) error {
if ctx.IsSet("config") { if c.IsSet("config") {
setting.CustomConf = ctx.String("config") setting.CustomConf = c.String("config")
} }
routers.GlobalInit() routers.GlobalInit()
checkVersion() checkVersion()
@ -177,8 +177,8 @@ func runWeb(ctx *cli.Context) error {
// Routers. // Routers.
m.Get("/", ignSignIn, routers.Home) m.Get("/", ignSignIn, routers.Home)
m.Group("/explore", func() { m.Group("/explore", func() {
m.Get("", func(ctx *context.Context) { m.Get("", func(c *context.Context) {
ctx.Redirect(setting.AppSubURL + "/explore/repos") c.Redirect(setting.AppSubURL + "/explore/repos")
}) })
m.Get("/repos", routers.ExploreRepos) m.Get("/repos", routers.ExploreRepos)
m.Get("/users", routers.ExploreUsers) m.Get("/users", routers.ExploreUsers)
@ -237,8 +237,8 @@ func runWeb(ctx *cli.Context) error {
Post(bindIgnErr(form.NewAccessToken{}), user.SettingsApplicationsPost) Post(bindIgnErr(form.NewAccessToken{}), user.SettingsApplicationsPost)
m.Post("/applications/delete", user.SettingsDeleteApplication) m.Post("/applications/delete", user.SettingsDeleteApplication)
m.Route("/delete", "GET,POST", user.SettingsDelete) m.Route("/delete", "GET,POST", user.SettingsDelete)
}, reqSignIn, func(ctx *context.Context) { }, reqSignIn, func(c *context.Context) {
ctx.Data["PageIsUserSettings"] = true c.Data["PageIsUserSettings"] = true
}) })
m.Group("/user", func() { m.Group("/user", func() {
@ -300,28 +300,28 @@ func runWeb(ctx *cli.Context) error {
m.Get("/stars", user.Stars) m.Get("/stars", user.Stars)
}) })
m.Get("/attachments/:uuid", func(ctx *context.Context) { m.Get("/attachments/:uuid", func(c *context.Context) {
attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid")) attach, err := models.GetAttachmentByUUID(c.Params(":uuid"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetAttachmentByUUID", models.IsErrAttachmentNotExist, err) c.NotFoundOrServerError("GetAttachmentByUUID", models.IsErrAttachmentNotExist, err)
return return
} else if !com.IsFile(attach.LocalPath()) { } else if !com.IsFile(attach.LocalPath()) {
ctx.NotFound() c.NotFound()
return return
} }
fr, err := os.Open(attach.LocalPath()) fr, err := os.Open(attach.LocalPath())
if err != nil { if err != nil {
ctx.Handle(500, "Open", err) c.Handle(500, "Open", err)
return return
} }
defer fr.Close() 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) fmt.Println("attach.Name:", attach.Name)
ctx.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name)) c.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
if err = repo.ServeData(ctx, attach.Name, fr); err != nil { if err = repo.ServeData(c, attach.Name, fr); err != nil {
ctx.Handle(500, "ServeData", err) c.Handle(500, "ServeData", err)
return return
} }
}) })
@ -345,9 +345,9 @@ func runWeb(ctx *cli.Context) error {
m.Group("", func() { m.Group("", func() {
m.Get("/create", org.Create) m.Get("/create", org.Create)
m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost) m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost)
}, func(ctx *context.Context) { }, func(c *context.Context) {
if !ctx.User.CanCreateOrganization() { if !c.User.CanCreateOrganization() {
ctx.NotFound() c.NotFound()
} }
}) })
@ -425,9 +425,9 @@ func runWeb(ctx *cli.Context) error {
m.Post("/default_branch", repo.UpdateDefaultBranch) m.Post("/default_branch", repo.UpdateDefaultBranch)
m.Combo("/*").Get(repo.SettingsProtectedBranch). m.Combo("/*").Get(repo.SettingsProtectedBranch).
Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost) Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
}, func(ctx *context.Context) { }, func(c *context.Context) {
if ctx.Repo.Repository.IsMirror { if c.Repo.Repository.IsMirror {
ctx.NotFound() c.NotFound()
return return
} }
}) })
@ -462,8 +462,8 @@ func runWeb(ctx *cli.Context) error {
m.Post("/delete", repo.DeleteDeployKey) m.Post("/delete", repo.DeleteDeployKey)
}) })
}, func(ctx *context.Context) { }, func(c *context.Context) {
ctx.Data["PageIsSettings"] = true c.Data["PageIsSettings"] = true
}) })
}, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef()) }, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
@ -530,11 +530,11 @@ func runWeb(ctx *cli.Context) error {
m.Post("/delete", repo.DeleteRelease) m.Post("/delete", repo.DeleteRelease)
m.Get("/edit/*", repo.EditRelease) m.Get("/edit/*", repo.EditRelease)
m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost) m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost)
}, repo.MustBeNotBare, reqRepoWriter, func(ctx *context.Context) { }, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) {
ctx.Data["PageIsViewFiles"] = true 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. // 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 // e.g. /org1/test-repo/compare/master...org1:develop
// which should be /org1/test-repo/compare/master...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) Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost)
m.Post("/upload-file", repo.UploadFileToServer) m.Post("/upload-file", repo.UploadFileToServer)
m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer) m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
}, func(ctx *context.Context) { }, func(c *context.Context) {
if !setting.Repository.Upload.Enabled { if !setting.Repository.Upload.Enabled {
ctx.NotFound() c.NotFound()
return return
} }
}) })
}, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) { }, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) {
if !ctx.Repo.CanEnableEditor() { if !c.Repo.CanEnableEditor() {
ctx.NotFound() c.NotFound()
return return
} }
ctx.Data["PageIsViewFiles"] = true c.Data["PageIsViewFiles"] = true
}) })
}, reqSignIn, context.RepoAssignment()) }, reqSignIn, context.RepoAssignment())
@ -582,8 +582,8 @@ func runWeb(ctx *cli.Context) error {
m.Get("", repo.Branches) m.Get("", repo.Branches)
m.Get("/all", repo.AllBranches) m.Get("/all", repo.AllBranches)
m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost) m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
}, repo.MustBeNotBare, func(ctx *context.Context) { }, repo.MustBeNotBare, func(c *context.Context) {
ctx.Data["PageIsViewFiles"] = true c.Data["PageIsViewFiles"] = true
}) })
m.Group("/wiki", func() { m.Group("/wiki", func() {
@ -642,11 +642,11 @@ func runWeb(ctx *cli.Context) error {
}, ignSignIn) }, ignSignIn)
// robots.txt // robots.txt
m.Get("/robots.txt", func(ctx *context.Context) { m.Get("/robots.txt", func(c *context.Context) {
if setting.HasRobotsTxt { if setting.HasRobotsTxt {
ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt")) c.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
} else { } else {
ctx.Error(404) c.NotFound()
} }
}) })
@ -654,9 +654,9 @@ func runWeb(ctx *cli.Context) error {
m.NotFound(routers.NotFound) m.NotFound(routers.NotFound)
// Flag for port number in case first time run conflict. // Flag for port number in case first time run conflict.
if ctx.IsSet("port") { if c.IsSet("port") {
setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, ctx.String("port"), 1) setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, c.String("port"), 1)
setting.HTTPPort = ctx.String("port") setting.HTTPPort = c.String("port")
} }
var listenAddr string var listenAddr string

26
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. // Error responses error message to client with given message.
// If status is 500, also it prints error to log. // 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 var message string
if err, ok := obj.(error); ok { if err, ok := obj.(error); ok {
message = err.Error() message = err.Error()
@ -37,39 +37,39 @@ func (ctx *APIContext) Error(status int, title string, obj interface{}) {
log.Error(3, "%s: %s", title, message) log.Error(3, "%s: %s", title, message)
} }
ctx.JSON(status, map[string]string{ c.JSON(status, map[string]string{
"message": message, "message": message,
"url": DOC_URL, "url": DOC_URL,
}) })
} }
// SetLinkHeader sets pagination link header by given totol number and page size. // SetLinkHeader sets pagination link header by given totol number and page size.
func (ctx *APIContext) SetLinkHeader(total, pageSize int) { func (c *APIContext) SetLinkHeader(total, pageSize int) {
page := paginater.New(total, pageSize, ctx.QueryInt("page"), 0) page := paginater.New(total, pageSize, c.QueryInt("page"), 0)
links := make([]string, 0, 4) links := make([]string, 0, 4)
if page.HasNext() { 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() { 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() { 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() { 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 { if len(links) > 0 {
ctx.Header().Set("Link", strings.Join(links, ",")) c.Header().Set("Link", strings.Join(links, ","))
} }
} }
func APIContexter() macaron.Handler { func APIContexter() macaron.Handler {
return func(c *Context) { return func(ctx *Context) {
ctx := &APIContext{ c := &APIContext{
Context: c, Context: ctx,
} }
c.Map(ctx) ctx.Map(c)
} }
} }

54
pkg/context/auth.go

@ -22,73 +22,73 @@ type ToggleOptions struct {
} }
func Toggle(options *ToggleOptions) macaron.Handler { func Toggle(options *ToggleOptions) macaron.Handler {
return func(ctx *Context) { return func(c *Context) {
// Cannot view any page before installation. // Cannot view any page before installation.
if !setting.InstallLock { if !setting.InstallLock {
ctx.Redirect(setting.AppSubURL + "/install") c.Redirect(setting.AppSubURL + "/install")
return return
} }
// Check prohibit login users. // Check prohibit login users.
if ctx.IsLogged && ctx.User.ProhibitLogin { if c.IsLogged && c.User.ProhibitLogin {
ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") c.Data["Title"] = c.Tr("auth.prohibit_login")
ctx.HTML(200, "user/auth/prohibit_login") c.HTML(200, "user/auth/prohibit_login")
return return
} }
// Check non-logged users landing page. // Check non-logged users landing page.
if !ctx.IsLogged && ctx.Req.RequestURI == "/" && setting.LandingPageURL != setting.LANDING_PAGE_HOME { if !c.IsLogged && c.Req.RequestURI == "/" && setting.LandingPageURL != setting.LANDING_PAGE_HOME {
ctx.Redirect(setting.AppSubURL + string(setting.LandingPageURL)) c.Redirect(setting.AppSubURL + string(setting.LandingPageURL))
return return
} }
// Redirect to dashboard if user tries to visit any non-login page. // Redirect to dashboard if user tries to visit any non-login page.
if options.SignOutRequired && ctx.IsLogged && ctx.Req.RequestURI != "/" { if options.SignOutRequired && c.IsLogged && c.Req.RequestURI != "/" {
ctx.Redirect(setting.AppSubURL + "/") c.Redirect(setting.AppSubURL + "/")
return return
} }
if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" && !auth.IsAPIPath(ctx.Req.URL.Path) { if !options.SignOutRequired && !options.DisableCSRF && c.Req.Method == "POST" && !auth.IsAPIPath(c.Req.URL.Path) {
csrf.Validate(ctx.Context, ctx.csrf) csrf.Validate(c.Context, c.csrf)
if ctx.Written() { if c.Written() {
return return
} }
} }
if options.SignInRequired { if options.SignInRequired {
if !ctx.IsLogged { if !c.IsLogged {
// Restrict API calls with error message. // Restrict API calls with error message.
if auth.IsAPIPath(ctx.Req.URL.Path) { if auth.IsAPIPath(c.Req.URL.Path) {
ctx.JSON(403, map[string]string{ c.JSON(403, map[string]string{
"message": "Only signed in user is allowed to call APIs.", "message": "Only signed in user is allowed to call APIs.",
}) })
return return
} }
ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+ctx.Req.RequestURI), 0, setting.AppSubURL) c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+c.Req.RequestURI), 0, setting.AppSubURL)
ctx.Redirect(setting.AppSubURL + "/user/login") c.Redirect(setting.AppSubURL + "/user/login")
return return
} else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { } else if !c.User.IsActive && setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account") c.Data["Title"] = c.Tr("auth.active_your_account")
ctx.HTML(200, "user/auth/activate") c.HTML(200, "user/auth/activate")
return return
} }
} }
// Redirect to log in page if auto-signin info is provided and has not signed in. // 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) && if !options.SignOutRequired && !c.IsLogged && !auth.IsAPIPath(c.Req.URL.Path) &&
len(ctx.GetCookie(setting.CookieUserName)) > 0 { len(c.GetCookie(setting.CookieUserName)) > 0 {
ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+ctx.Req.RequestURI), 0, setting.AppSubURL) c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+c.Req.RequestURI), 0, setting.AppSubURL)
ctx.Redirect(setting.AppSubURL + "/user/login") c.Redirect(setting.AppSubURL + "/user/login")
return return
} }
if options.AdminRequired { if options.AdminRequired {
if !ctx.User.IsAdmin { if !c.User.IsAdmin {
ctx.Error(403) c.Error(403)
return return
} }
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
} }
} }
} }

78
pkg/context/context.go

@ -85,39 +85,39 @@ func (c *Context) UserID() int64 {
} }
// HasError returns true if error occurs in form validation. // HasError returns true if error occurs in form validation.
func (ctx *Context) HasApiError() bool { func (c *Context) HasApiError() bool {
hasErr, ok := ctx.Data["HasError"] hasErr, ok := c.Data["HasError"]
if !ok { if !ok {
return false return false
} }
return hasErr.(bool) return hasErr.(bool)
} }
func (ctx *Context) GetErrMsg() string { func (c *Context) GetErrMsg() string {
return ctx.Data["ErrorMsg"].(string) return c.Data["ErrorMsg"].(string)
} }
// HasError returns true if error occurs in form validation. // HasError returns true if error occurs in form validation.
func (ctx *Context) HasError() bool { func (c *Context) HasError() bool {
hasErr, ok := ctx.Data["HasError"] hasErr, ok := c.Data["HasError"]
if !ok { if !ok {
return false return false
} }
ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string) c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string)
ctx.Data["Flash"] = ctx.Flash c.Data["Flash"] = c.Flash
return hasErr.(bool) return hasErr.(bool)
} }
// HasValue returns true if value of given name exists. // HasValue returns true if value of given name exists.
func (ctx *Context) HasValue(name string) bool { func (c *Context) HasValue(name string) bool {
_, ok := ctx.Data[name] _, ok := c.Data[name]
return ok return ok
} }
// HTML responses template with given status. // 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) log.Trace("Template: %s", name)
ctx.Context.HTML(status, name) c.Context.HTML(status, name)
} }
// Success responses template with status http.StatusOK. // 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. // 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 { if f != nil {
form.Assign(f, ctx.Data) form.Assign(f, c.Data)
} }
ctx.Flash.ErrorMsg = msg c.Flash.ErrorMsg = msg
ctx.Data["Flash"] = ctx.Flash c.Data["Flash"] = c.Flash
ctx.HTML(http.StatusOK, tpl) c.HTML(http.StatusOK, tpl)
} }
// Handle handles and logs error by given status. // 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 { switch status {
case http.StatusNotFound: case http.StatusNotFound:
ctx.Data["Title"] = "Page Not Found" c.Data["Title"] = "Page Not Found"
case http.StatusInternalServerError: case http.StatusInternalServerError:
ctx.Data["Title"] = "Internal Server Error" c.Data["Title"] = "Internal Server Error"
log.Error(2, "%s: %v", title, err) log.Error(2, "%s: %v", title, err)
if !setting.ProdMode || (ctx.IsLogged && ctx.User.IsAdmin) { if !setting.ProdMode || (c.IsLogged && c.User.IsAdmin) {
ctx.Data["ErrorMsg"] = err 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. // NotFound renders the 404 page.
func (ctx *Context) NotFound() { func (c *Context) NotFound() {
ctx.Handle(http.StatusNotFound, "", nil) c.Handle(http.StatusNotFound, "", nil)
} }
// ServerError renders the 500 page. // ServerError renders the 500 page.
@ -182,11 +182,11 @@ func (c *Context) NotFoundOrServerError(title string, errck func(error) bool, er
c.ServerError(title, err) c.ServerError(title, err)
} }
func (ctx *Context) HandleText(status int, title string) { func (c *Context) HandleText(status int, title string) {
ctx.PlainText(status, []byte(title)) 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() modtime := time.Now()
for _, p := range params { for _, p := range params {
switch v := p.(type) { switch v := p.(type) {
@ -194,14 +194,14 @@ func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interfa
modtime = v modtime = v
} }
} }
ctx.Resp.Header().Set("Content-Description", "File Transfer") c.Resp.Header().Set("Content-Description", "File Transfer")
ctx.Resp.Header().Set("Content-Type", "application/octet-stream") c.Resp.Header().Set("Content-Type", "application/octet-stream")
ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name) c.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary") c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
ctx.Resp.Header().Set("Expires", "0") c.Resp.Header().Set("Expires", "0")
ctx.Resp.Header().Set("Cache-Control", "must-revalidate") c.Resp.Header().Set("Cache-Control", "must-revalidate")
ctx.Resp.Header().Set("Pragma", "public") c.Resp.Header().Set("Pragma", "public")
http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r) http.ServeContent(c.Resp, c.Req.Request, name, modtime, r)
} }
// Contexter initializes a classic context for a request. // 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 // This is particular a workaround for "go get" command which does not respect
// .netrc file. // .netrc file.
if c.Query("go-get") == "1" { if c.Query("go-get") == "1" {
ownerName := ctx.Params(":username") ownerName := c.Params(":username")
repoName := ctx.Params(":reponame") repoName := c.Params(":reponame")
branchName := "master" branchName := "master"
owner, err := models.GetUserByName(ownerName) owner, err := models.GetUserByName(ownerName)
@ -244,7 +244,7 @@ func Contexter() macaron.Handler {
} }
prefix := setting.AppURL + path.Join(ownerName, repoName, "src", branchName) prefix := setting.AppURL + path.Join(ownerName, repoName, "src", branchName)
ctx.PlainText(http.StatusOK, []byte(com.Expand(` c.PlainText(http.StatusOK, []byte(com.Expand(`
<html> <html>
<head> <head>
<meta name="go-import" content="{GoGetImport} git {CloneLink}"> <meta name="go-import" content="{GoGetImport} git {CloneLink}">

94
pkg/context/org.go

@ -25,7 +25,7 @@ type Organization struct {
Team *models.Team Team *models.Team
} }
func HandleOrgAssignment(ctx *Context, args ...bool) { func HandleOrgAssignment(c *Context, args ...bool) {
var ( var (
requireMember bool requireMember bool
requireOwner bool requireOwner bool
@ -45,106 +45,106 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
requireTeamAdmin = args[3] requireTeamAdmin = args[3]
} }
orgName := ctx.Params(":org") orgName := c.Params(":org")
var err error var err error
ctx.Org.Organization, err = models.GetUserByName(orgName) c.Org.Organization, err = models.GetUserByName(orgName)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return return
} }
org := ctx.Org.Organization org := c.Org.Organization
ctx.Data["Org"] = org c.Data["Org"] = org
// Force redirection when username is actually a user. // Force redirection when username is actually a user.
if !org.IsOrganization() { if !org.IsOrganization() {
ctx.Redirect("/" + org.Name) c.Redirect("/" + org.Name)
return return
} }
// Admin has super access. // Admin has super access.
if ctx.IsLogged && ctx.User.IsAdmin { if c.IsLogged && c.User.IsAdmin {
ctx.Org.IsOwner = true c.Org.IsOwner = true
ctx.Org.IsMember = true c.Org.IsMember = true
ctx.Org.IsTeamMember = true c.Org.IsTeamMember = true
ctx.Org.IsTeamAdmin = true c.Org.IsTeamAdmin = true
} else if ctx.IsLogged { } else if c.IsLogged {
ctx.Org.IsOwner = org.IsOwnedBy(ctx.User.ID) c.Org.IsOwner = org.IsOwnedBy(c.User.ID)
if ctx.Org.IsOwner { if c.Org.IsOwner {
ctx.Org.IsMember = true c.Org.IsMember = true
ctx.Org.IsTeamMember = true c.Org.IsTeamMember = true
ctx.Org.IsTeamAdmin = true c.Org.IsTeamAdmin = true
} else { } else {
if org.IsOrgMember(ctx.User.ID) { if org.IsOrgMember(c.User.ID) {
ctx.Org.IsMember = true c.Org.IsMember = true
} }
} }
} else { } else {
// Fake data. // Fake data.
ctx.Data["SignedUser"] = &models.User{} c.Data["SignedUser"] = &models.User{}
} }
if (requireMember && !ctx.Org.IsMember) || if (requireMember && !c.Org.IsMember) ||
(requireOwner && !ctx.Org.IsOwner) { (requireOwner && !c.Org.IsOwner) {
ctx.Handle(404, "OrgAssignment", err) c.Handle(404, "OrgAssignment", err)
return return
} }
ctx.Data["IsOrganizationOwner"] = ctx.Org.IsOwner c.Data["IsOrganizationOwner"] = c.Org.IsOwner
ctx.Data["IsOrganizationMember"] = ctx.Org.IsMember c.Data["IsOrganizationMember"] = c.Org.IsMember
ctx.Org.OrgLink = setting.AppSubURL + "/org/" + org.Name c.Org.OrgLink = setting.AppSubURL + "/org/" + org.Name
ctx.Data["OrgLink"] = ctx.Org.OrgLink c.Data["OrgLink"] = c.Org.OrgLink
// Team. // Team.
if ctx.Org.IsMember { if c.Org.IsMember {
if ctx.Org.IsOwner { if c.Org.IsOwner {
if err := org.GetTeams(); err != nil { if err := org.GetTeams(); err != nil {
ctx.Handle(500, "GetTeams", err) c.Handle(500, "GetTeams", err)
return return
} }
} else { } else {
org.Teams, err = org.GetUserTeams(ctx.User.ID) org.Teams, err = org.GetUserTeams(c.User.ID)
if err != nil { if err != nil {
ctx.Handle(500, "GetUserTeams", err) c.Handle(500, "GetUserTeams", err)
return return
} }
} }
} }
teamName := ctx.Params(":team") teamName := c.Params(":team")
if len(teamName) > 0 { if len(teamName) > 0 {
teamExists := false teamExists := false
for _, team := range org.Teams { for _, team := range org.Teams {
if team.LowerName == strings.ToLower(teamName) { if team.LowerName == strings.ToLower(teamName) {
teamExists = true teamExists = true
ctx.Org.Team = team c.Org.Team = team
ctx.Org.IsTeamMember = true c.Org.IsTeamMember = true
ctx.Data["Team"] = ctx.Org.Team c.Data["Team"] = c.Org.Team
break break
} }
} }
if !teamExists { if !teamExists {
ctx.Handle(404, "OrgAssignment", err) c.Handle(404, "OrgAssignment", err)
return return
} }
ctx.Data["IsTeamMember"] = ctx.Org.IsTeamMember c.Data["IsTeamMember"] = c.Org.IsTeamMember
if requireTeamMember && !ctx.Org.IsTeamMember { if requireTeamMember && !c.Org.IsTeamMember {
ctx.Handle(404, "OrgAssignment", err) c.Handle(404, "OrgAssignment", err)
return return
} }
ctx.Org.IsTeamAdmin = ctx.Org.Team.IsOwnerTeam() || ctx.Org.Team.Authorize >= models.ACCESS_MODE_ADMIN c.Org.IsTeamAdmin = c.Org.Team.IsOwnerTeam() || c.Org.Team.Authorize >= models.ACCESS_MODE_ADMIN
ctx.Data["IsTeamAdmin"] = ctx.Org.IsTeamAdmin c.Data["IsTeamAdmin"] = c.Org.IsTeamAdmin
if requireTeamAdmin && !ctx.Org.IsTeamAdmin { if requireTeamAdmin && !c.Org.IsTeamAdmin {
ctx.Handle(404, "OrgAssignment", err) c.Handle(404, "OrgAssignment", err)
return return
} }
} }
} }
func OrgAssignment(args ...bool) macaron.Handler { func OrgAssignment(args ...bool) macaron.Handler {
return func(ctx *Context) { return func(c *Context) {
HandleOrgAssignment(ctx, args...) HandleOrgAssignment(c, args...)
} }
} }

270
pkg/context/repo.go

@ -108,7 +108,7 @@ func (r *Repository) PullRequestURL(baseBranch, headBranch string) string {
// [0]: issues, [1]: wiki // [0]: issues, [1]: wiki
func RepoAssignment(pages ...bool) macaron.Handler { func RepoAssignment(pages ...bool) macaron.Handler {
return func(ctx *Context) { return func(c *Context) {
var ( var (
owner *models.User owner *models.User
err error err error
@ -123,53 +123,53 @@ func RepoAssignment(pages ...bool) macaron.Handler {
isWikiPage = pages[1] isWikiPage = pages[1]
} }
ownerName := ctx.Params(":username") ownerName := c.Params(":username")
repoName := strings.TrimSuffix(ctx.Params(":reponame"), ".git") repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
refName := ctx.Params(":branchname") refName := c.Params(":branchname")
if len(refName) == 0 { if len(refName) == 0 {
refName = ctx.Params(":path") refName = c.Params(":path")
} }
// Check if the user is the same as the repository owner // Check if the user is the same as the repository owner
if ctx.IsLogged && ctx.User.LowerName == strings.ToLower(ownerName) { if c.IsLogged && c.User.LowerName == strings.ToLower(ownerName) {
owner = ctx.User owner = c.User
} else { } else {
owner, err = models.GetUserByName(ownerName) owner, err = models.GetUserByName(ownerName)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return return
} }
} }
ctx.Repo.Owner = owner c.Repo.Owner = owner
ctx.Data["Username"] = ctx.Repo.Owner.Name c.Data["Username"] = c.Repo.Owner.Name
repo, err := models.GetRepositoryByName(owner.ID, repoName) repo, err := models.GetRepositoryByName(owner.ID, repoName)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err) c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
return return
} }
ctx.Repo.Repository = repo c.Repo.Repository = repo
ctx.Data["RepoName"] = ctx.Repo.Repository.Name c.Data["RepoName"] = c.Repo.Repository.Name
ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare c.Data["IsBareRepo"] = c.Repo.Repository.IsBare
ctx.Repo.RepoLink = repo.Link() c.Repo.RepoLink = repo.Link()
ctx.Data["RepoLink"] = ctx.Repo.RepoLink c.Data["RepoLink"] = c.Repo.RepoLink
ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name c.Data["RepoRelPath"] = c.Repo.Owner.Name + "/" + c.Repo.Repository.Name
// Admin has super access. // Admin has super access.
if ctx.IsLogged && ctx.User.IsAdmin { if c.IsLogged && c.User.IsAdmin {
ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER c.Repo.AccessMode = models.ACCESS_MODE_OWNER
} else { } else {
mode, err := models.AccessLevel(ctx.UserID(), repo) mode, err := models.AccessLevel(c.UserID(), repo)
if err != nil { if err != nil {
ctx.ServerError("AccessLevel", err) c.ServerError("AccessLevel", err)
return return
} }
ctx.Repo.AccessMode = mode c.Repo.AccessMode = mode
} }
// Check access // 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 // Redirect to any accessible page if not yet on it
if repo.IsPartialPublic() && if repo.IsPartialPublic() &&
(!(isIssuesPage || isWikiPage) || (!(isIssuesPage || isWikiPage) ||
@ -177,11 +177,11 @@ func RepoAssignment(pages ...bool) macaron.Handler {
(isWikiPage && !repo.CanGuestViewWiki())) { (isWikiPage && !repo.CanGuestViewWiki())) {
switch { switch {
case repo.CanGuestViewIssues(): case repo.CanGuestViewIssues():
ctx.Redirect(repo.Link() + "/issues") c.Redirect(repo.Link() + "/issues")
case repo.CanGuestViewWiki(): case repo.CanGuestViewWiki():
ctx.Redirect(repo.Link() + "/wiki") c.Redirect(repo.Link() + "/wiki")
default: default:
ctx.NotFound() c.NotFound()
} }
return return
} }
@ -190,92 +190,92 @@ func RepoAssignment(pages ...bool) macaron.Handler {
if !repo.IsPartialPublic() || if !repo.IsPartialPublic() ||
(isIssuesPage && !repo.CanGuestViewIssues()) || (isIssuesPage && !repo.CanGuestViewIssues()) ||
(isWikiPage && !repo.CanGuestViewWiki()) { (isWikiPage && !repo.CanGuestViewWiki()) {
ctx.NotFound() c.NotFound()
return return
} }
ctx.Repo.Repository.EnableIssues = repo.CanGuestViewIssues() c.Repo.Repository.EnableIssues = repo.CanGuestViewIssues()
ctx.Repo.Repository.EnableWiki = repo.CanGuestViewWiki() c.Repo.Repository.EnableWiki = repo.CanGuestViewWiki()
} }
if repo.IsMirror { if repo.IsMirror {
ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID) c.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
if err != nil { if err != nil {
ctx.Handle(500, "GetMirror", err) c.ServerError("GetMirror", err)
return return
} }
ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune c.Data["MirrorEnablePrune"] = c.Repo.Mirror.EnablePrune
ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval c.Data["MirrorInterval"] = c.Repo.Mirror.Interval
ctx.Data["Mirror"] = ctx.Repo.Mirror c.Data["Mirror"] = c.Repo.Mirror
} }
gitRepo, err := git.OpenRepository(models.RepoPath(ownerName, repoName)) gitRepo, err := git.OpenRepository(models.RepoPath(ownerName, repoName))
if err != nil { 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 return
} }
ctx.Repo.GitRepo = gitRepo c.Repo.GitRepo = gitRepo
tags, err := ctx.Repo.GitRepo.GetTags() tags, err := c.Repo.GitRepo.GetTags()
if err != nil { 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 return
} }
ctx.Data["Tags"] = tags c.Data["Tags"] = tags
ctx.Repo.Repository.NumTags = len(tags) c.Repo.Repository.NumTags = len(tags)
ctx.Data["Title"] = owner.Name + "/" + repo.Name c.Data["Title"] = owner.Name + "/" + repo.Name
ctx.Data["Repository"] = repo c.Data["Repository"] = repo
ctx.Data["Owner"] = ctx.Repo.Repository.Owner c.Data["Owner"] = c.Repo.Repository.Owner
ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner() c.Data["IsRepositoryOwner"] = c.Repo.IsOwner()
ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin() c.Data["IsRepositoryAdmin"] = c.Repo.IsAdmin()
ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter() c.Data["IsRepositoryWriter"] = c.Repo.IsWriter()
ctx.Data["DisableSSH"] = setting.SSH.Disabled c.Data["DisableSSH"] = setting.SSH.Disabled
ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit c.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
ctx.Data["CloneLink"] = repo.CloneLink() c.Data["CloneLink"] = repo.CloneLink()
ctx.Data["WikiCloneLink"] = repo.WikiCloneLink() c.Data["WikiCloneLink"] = repo.WikiCloneLink()
if ctx.IsLogged { if c.IsLogged {
ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID) c.Data["IsWatchingRepo"] = models.IsWatching(c.User.ID, repo.ID)
ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID) c.Data["IsStaringRepo"] = models.IsStaring(c.User.ID, repo.ID)
} }
// repo is bare and display enable // repo is bare and display enable
if ctx.Repo.Repository.IsBare { if c.Repo.Repository.IsBare {
return return
} }
ctx.Data["TagName"] = ctx.Repo.TagName c.Data["TagName"] = c.Repo.TagName
brs, err := ctx.Repo.GitRepo.GetBranches() brs, err := c.Repo.GitRepo.GetBranches()
if err != nil { if err != nil {
ctx.Handle(500, "GetBranches", err) c.ServerError("GetBranches", err)
return return
} }
ctx.Data["Branches"] = brs c.Data["Branches"] = brs
ctx.Data["BrancheCount"] = len(brs) c.Data["BrancheCount"] = len(brs)
// If not branch selected, try default one. // If not branch selected, try default one.
// If default branch doesn't exists, fall back to some other branch. // If default branch doesn't exists, fall back to some other branch.
if len(ctx.Repo.BranchName) == 0 { if len(c.Repo.BranchName) == 0 {
if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) { if len(c.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(c.Repo.Repository.DefaultBranch) {
ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch c.Repo.BranchName = c.Repo.Repository.DefaultBranch
} else if len(brs) > 0 { } else if len(brs) > 0 {
ctx.Repo.BranchName = brs[0] c.Repo.BranchName = brs[0]
} }
} }
ctx.Data["BranchName"] = ctx.Repo.BranchName c.Data["BranchName"] = c.Repo.BranchName
ctx.Data["CommitID"] = ctx.Repo.CommitID 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 `/`. // RepoRef handles repository reference name including those contain `/`.
func RepoRef() macaron.Handler { func RepoRef() macaron.Handler {
return func(ctx *Context) { return func(c *Context) {
// Empty repository does not have reference information. // Empty repository does not have reference information.
if ctx.Repo.Repository.IsBare { if c.Repo.Repository.IsBare {
return return
} }
@ -285,44 +285,44 @@ func RepoRef() macaron.Handler {
) )
// For API calls. // For API calls.
if ctx.Repo.GitRepo == nil { if c.Repo.GitRepo == nil {
repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) repoPath := models.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name)
ctx.Repo.GitRepo, err = git.OpenRepository(repoPath) c.Repo.GitRepo, err = git.OpenRepository(repoPath)
if err != nil { if err != nil {
ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err) c.Handle(500, "RepoRef Invalid repo "+repoPath, err)
return return
} }
} }
// Get default branch. // Get default branch.
if len(ctx.Params("*")) == 0 { if len(c.Params("*")) == 0 {
refName = ctx.Repo.Repository.DefaultBranch refName = c.Repo.Repository.DefaultBranch
if !ctx.Repo.GitRepo.IsBranchExist(refName) { if !c.Repo.GitRepo.IsBranchExist(refName) {
brs, err := ctx.Repo.GitRepo.GetBranches() brs, err := c.Repo.GitRepo.GetBranches()
if err != nil { if err != nil {
ctx.Handle(500, "GetBranches", err) c.Handle(500, "GetBranches", err)
return return
} }
refName = brs[0] refName = brs[0]
} }
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName) c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(refName)
if err != nil { if err != nil {
ctx.Handle(500, "GetBranchCommit", err) c.Handle(500, "GetBranchCommit", err)
return return
} }
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() c.Repo.CommitID = c.Repo.Commit.ID.String()
ctx.Repo.IsViewBranch = true c.Repo.IsViewBranch = true
} else { } else {
hasMatched := false hasMatched := false
parts := strings.Split(ctx.Params("*"), "/") parts := strings.Split(c.Params("*"), "/")
for i, part := range parts { for i, part := range parts {
refName = strings.TrimPrefix(refName+"/"+part, "/") refName = strings.TrimPrefix(refName+"/"+part, "/")
if ctx.Repo.GitRepo.IsBranchExist(refName) || if c.Repo.GitRepo.IsBranchExist(refName) ||
ctx.Repo.GitRepo.IsTagExist(refName) { c.Repo.GitRepo.IsTagExist(refName) {
if i < len(parts)-1 { if i < len(parts)-1 {
ctx.Repo.TreePath = strings.Join(parts[i+1:], "/") c.Repo.TreePath = strings.Join(parts[i+1:], "/")
} }
hasMatched = true hasMatched = true
break break
@ -330,97 +330,97 @@ func RepoRef() macaron.Handler {
} }
if !hasMatched && len(parts[0]) == 40 { if !hasMatched && len(parts[0]) == 40 {
refName = parts[0] refName = parts[0]
ctx.Repo.TreePath = strings.Join(parts[1:], "/") c.Repo.TreePath = strings.Join(parts[1:], "/")
} }
if ctx.Repo.GitRepo.IsBranchExist(refName) { if c.Repo.GitRepo.IsBranchExist(refName) {
ctx.Repo.IsViewBranch = true 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 { if err != nil {
ctx.Handle(500, "GetBranchCommit", err) c.Handle(500, "GetBranchCommit", err)
return return
} }
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() c.Repo.CommitID = c.Repo.Commit.ID.String()
} else if ctx.Repo.GitRepo.IsTagExist(refName) { } else if c.Repo.GitRepo.IsTagExist(refName) {
ctx.Repo.IsViewTag = true c.Repo.IsViewTag = true
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName) c.Repo.Commit, err = c.Repo.GitRepo.GetTagCommit(refName)
if err != nil { if err != nil {
ctx.Handle(500, "GetTagCommit", err) c.Handle(500, "GetTagCommit", err)
return return
} }
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() c.Repo.CommitID = c.Repo.Commit.ID.String()
} else if len(refName) == 40 { } else if len(refName) == 40 {
ctx.Repo.IsViewCommit = true c.Repo.IsViewCommit = true
ctx.Repo.CommitID = refName 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 { if err != nil {
ctx.NotFound() c.NotFound()
return return
} }
} else { } 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 return
} }
} }
ctx.Repo.BranchName = refName c.Repo.BranchName = refName
ctx.Data["BranchName"] = ctx.Repo.BranchName c.Data["BranchName"] = c.Repo.BranchName
ctx.Data["CommitID"] = ctx.Repo.CommitID c.Data["CommitID"] = c.Repo.CommitID
ctx.Data["TreePath"] = ctx.Repo.TreePath c.Data["TreePath"] = c.Repo.TreePath
ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch c.Data["IsViewBranch"] = c.Repo.IsViewBranch
ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag c.Data["IsViewTag"] = c.Repo.IsViewTag
ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit c.Data["IsViewCommit"] = c.Repo.IsViewCommit
// People who have push access or have fored repository can propose a new pull request. // 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 // Pull request is allowed if this is a fork repository
// and base repository accepts pull requests. // and base repository accepts pull requests.
if ctx.Repo.Repository.BaseRepo != nil { if c.Repo.Repository.BaseRepo != nil {
if ctx.Repo.Repository.BaseRepo.AllowsPulls() { if c.Repo.Repository.BaseRepo.AllowsPulls() {
ctx.Repo.PullRequest.Allowed = true c.Repo.PullRequest.Allowed = true
// In-repository pull requests has higher priority than cross-repository if user is viewing // 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. // base repository and 1) has write access to it 2) has forked it.
if ctx.Repo.IsWriter() { if c.Repo.IsWriter() {
ctx.Data["BaseRepo"] = ctx.Repo.Repository.BaseRepo c.Data["BaseRepo"] = c.Repo.Repository.BaseRepo
ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository.BaseRepo c.Repo.PullRequest.BaseRepo = c.Repo.Repository.BaseRepo
ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName c.Repo.PullRequest.HeadInfo = c.Repo.Owner.Name + ":" + c.Repo.BranchName
} else { } else {
ctx.Data["BaseRepo"] = ctx.Repo.Repository c.Data["BaseRepo"] = c.Repo.Repository
ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository c.Repo.PullRequest.BaseRepo = c.Repo.Repository
ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
} }
} }
} else { } else {
// Or, this is repository accepts pull requests between branches. // Or, this is repository accepts pull requests between branches.
if ctx.Repo.Repository.AllowsPulls() { if c.Repo.Repository.AllowsPulls() {
ctx.Data["BaseRepo"] = ctx.Repo.Repository c.Data["BaseRepo"] = c.Repo.Repository
ctx.Repo.PullRequest.BaseRepo = ctx.Repo.Repository c.Repo.PullRequest.BaseRepo = c.Repo.Repository
ctx.Repo.PullRequest.Allowed = true c.Repo.PullRequest.Allowed = true
ctx.Repo.PullRequest.SameRepo = true c.Repo.PullRequest.SameRepo = true
ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName c.Repo.PullRequest.HeadInfo = c.Repo.BranchName
} }
} }
} }
ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest c.Data["PullRequestCtx"] = c.Repo.PullRequest
} }
} }
func RequireRepoAdmin() macaron.Handler { func RequireRepoAdmin() macaron.Handler {
return func(ctx *Context) { return func(c *Context) {
if !ctx.IsLogged || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) { if !c.IsLogged || (!c.Repo.IsAdmin() && !c.User.IsAdmin) {
ctx.NotFound() c.NotFound()
return return
} }
} }
} }
func RequireRepoWriter() macaron.Handler { func RequireRepoWriter() macaron.Handler {
return func(ctx *Context) { return func(c *Context) {
if !ctx.IsLogged || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) { if !c.IsLogged || (!c.Repo.IsWriter() && !c.User.IsAdmin) {
ctx.NotFound() c.NotFound()
return return
} }
} }
@ -428,9 +428,9 @@ func RequireRepoWriter() macaron.Handler {
// GitHookService checks if repository Git hooks service has been enabled. // GitHookService checks if repository Git hooks service has been enabled.
func GitHookService() macaron.Handler { func GitHookService() macaron.Handler {
return func(ctx *Context) { return func(c *Context) {
if !ctx.User.CanEditGitHook() { if !c.User.CanEditGitHook() {
ctx.NotFound() c.NotFound()
return return
} }
} }

126
routers/admin/admin.go

@ -125,111 +125,111 @@ const (
REINIT_MISSING_REPOSITORY REINIT_MISSING_REPOSITORY
) )
func Dashboard(ctx *context.Context) { func Dashboard(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.dashboard") c.Data["Title"] = c.Tr("admin.dashboard")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminDashboard"] = true c.Data["PageIsAdminDashboard"] = true
// Run operation. // Run operation.
op, _ := com.StrTo(ctx.Query("op")).Int() op, _ := com.StrTo(c.Query("op")).Int()
if op > 0 { if op > 0 {
var err error var err error
var success string var success string
switch AdminOperation(op) { switch AdminOperation(op) {
case CLEAN_INACTIVATE_USER: 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() err = models.DeleteInactivateUsers()
case CLEAN_REPO_ARCHIVES: 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() err = models.DeleteRepositoryArchives()
case CLEAN_MISSING_REPOS: 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() err = models.DeleteMissingRepositories()
case GIT_GC_REPOS: 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() err = models.GitGcRepos()
case SYNC_SSH_AUTHORIZED_KEY: 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() err = models.RewriteAllPublicKeys()
case SYNC_REPOSITORY_HOOKS: 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() err = models.SyncRepositoryHooks()
case REINIT_MISSING_REPOSITORY: 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() err = models.ReinitMissingRepositories()
} }
if err != nil { if err != nil {
ctx.Flash.Error(err.Error()) c.Flash.Error(err.Error())
} else { } else {
ctx.Flash.Success(success) c.Flash.Success(success)
} }
ctx.Redirect(setting.AppSubURL + "/admin") c.Redirect(setting.AppSubURL + "/admin")
return return
} }
ctx.Data["Stats"] = models.GetStatistic() c.Data["Stats"] = models.GetStatistic()
// FIXME: update periodically // FIXME: update periodically
updateSystemStatus() updateSystemStatus()
ctx.Data["SysStatus"] = sysStatus c.Data["SysStatus"] = sysStatus
ctx.HTML(200, DASHBOARD) c.HTML(200, DASHBOARD)
} }
func SendTestMail(ctx *context.Context) { func SendTestMail(c *context.Context) {
email := ctx.Query("email") email := c.Query("email")
// Send a test email to the user's email address and redirect back to Config // Send a test email to the user's email address and redirect back to Config
if err := mailer.SendTestMail(email); err != nil { 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 { } 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) { func Config(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.config") c.Data["Title"] = c.Tr("admin.config")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminConfig"] = true c.Data["PageIsAdminConfig"] = true
ctx.Data["AppURL"] = setting.AppURL c.Data["AppURL"] = setting.AppURL
ctx.Data["Domain"] = setting.Domain c.Data["Domain"] = setting.Domain
ctx.Data["OfflineMode"] = setting.OfflineMode c.Data["OfflineMode"] = setting.OfflineMode
ctx.Data["DisableRouterLog"] = setting.DisableRouterLog c.Data["DisableRouterLog"] = setting.DisableRouterLog
ctx.Data["RunUser"] = setting.RunUser c.Data["RunUser"] = setting.RunUser
ctx.Data["RunMode"] = strings.Title(macaron.Env) c.Data["RunMode"] = strings.Title(macaron.Env)
ctx.Data["StaticRootPath"] = setting.StaticRootPath c.Data["StaticRootPath"] = setting.StaticRootPath
ctx.Data["LogRootPath"] = setting.LogRootPath c.Data["LogRootPath"] = setting.LogRootPath
ctx.Data["ReverseProxyAuthUser"] = setting.ReverseProxyAuthUser c.Data["ReverseProxyAuthUser"] = setting.ReverseProxyAuthUser
ctx.Data["SSH"] = setting.SSH c.Data["SSH"] = setting.SSH
ctx.Data["RepoRootPath"] = setting.RepoRootPath c.Data["RepoRootPath"] = setting.RepoRootPath
ctx.Data["ScriptType"] = setting.ScriptType c.Data["ScriptType"] = setting.ScriptType
ctx.Data["Repository"] = setting.Repository c.Data["Repository"] = setting.Repository
ctx.Data["Service"] = setting.Service c.Data["Service"] = setting.Service
ctx.Data["DbCfg"] = models.DbCfg c.Data["DbCfg"] = models.DbCfg
ctx.Data["Webhook"] = setting.Webhook c.Data["Webhook"] = setting.Webhook
ctx.Data["MailerEnabled"] = false c.Data["MailerEnabled"] = false
if setting.MailService != nil { if setting.MailService != nil {
ctx.Data["MailerEnabled"] = true c.Data["MailerEnabled"] = true
ctx.Data["Mailer"] = setting.MailService c.Data["Mailer"] = setting.MailService
} }
ctx.Data["CacheAdapter"] = setting.CacheAdapter c.Data["CacheAdapter"] = setting.CacheAdapter
ctx.Data["CacheInterval"] = setting.CacheInterval c.Data["CacheInterval"] = setting.CacheInterval
ctx.Data["CacheConn"] = setting.CacheConn c.Data["CacheConn"] = setting.CacheConn
ctx.Data["SessionConfig"] = setting.SessionConfig c.Data["SessionConfig"] = setting.SessionConfig
ctx.Data["DisableGravatar"] = setting.DisableGravatar c.Data["DisableGravatar"] = setting.DisableGravatar
ctx.Data["EnableFederatedAvatar"] = setting.EnableFederatedAvatar c.Data["EnableFederatedAvatar"] = setting.EnableFederatedAvatar
ctx.Data["GitVersion"] = setting.Git.Version c.Data["GitVersion"] = setting.Git.Version
ctx.Data["Git"] = setting.Git c.Data["Git"] = setting.Git
type logger struct { type logger struct {
Mode, Config string Mode, Config string
@ -243,16 +243,16 @@ func Config(ctx *context.Context) {
result, _ := json.MarshalIndent(setting.LogConfigs[i], "", " ") result, _ := json.MarshalIndent(setting.LogConfigs[i], "", " ")
loggers[i].Config = string(result) 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) { func Monitor(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.monitor") c.Data["Title"] = c.Tr("admin.monitor")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminMonitor"] = true c.Data["PageIsAdminMonitor"] = true
ctx.Data["Processes"] = process.Processes c.Data["Processes"] = process.Processes
ctx.Data["Entries"] = cron.ListTasks() c.Data["Entries"] = cron.ListTasks()
ctx.HTML(200, MONITOR) c.HTML(200, MONITOR)
} }

156
routers/admin/auths.go

@ -24,20 +24,20 @@ const (
AUTH_EDIT = "admin/auth/edit" AUTH_EDIT = "admin/auth/edit"
) )
func Authentications(ctx *context.Context) { func Authentications(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.authentication") c.Data["Title"] = c.Tr("admin.authentication")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true c.Data["PageIsAdminAuthentications"] = true
var err error var err error
ctx.Data["Sources"], err = models.LoginSources() c.Data["Sources"], err = models.LoginSources()
if err != nil { if err != nil {
ctx.Handle(500, "LoginSources", err) c.Handle(500, "LoginSources", err)
return return
} }
ctx.Data["Total"] = models.CountLoginSources() c.Data["Total"] = models.CountLoginSources()
ctx.HTML(200, AUTHS) c.HTML(200, AUTHS)
} }
type dropdownItem struct { type dropdownItem struct {
@ -59,20 +59,20 @@ var (
} }
) )
func NewAuthSource(ctx *context.Context) { func NewAuthSource(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.auths.new") c.Data["Title"] = c.Tr("admin.auths.new")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true c.Data["PageIsAdminAuthentications"] = true
ctx.Data["type"] = models.LOGIN_LDAP c.Data["type"] = models.LOGIN_LDAP
ctx.Data["CurrentTypeName"] = models.LoginNames[models.LOGIN_LDAP] c.Data["CurrentTypeName"] = models.LoginNames[models.LOGIN_LDAP]
ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_UNENCRYPTED] c.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_UNENCRYPTED]
ctx.Data["smtp_auth"] = "PLAIN" c.Data["smtp_auth"] = "PLAIN"
ctx.Data["is_active"] = true c.Data["is_active"] = true
ctx.Data["AuthSources"] = authSources c.Data["AuthSources"] = authSources
ctx.Data["SecurityProtocols"] = securityProtocols c.Data["SecurityProtocols"] = securityProtocols
ctx.Data["SMTPAuths"] = models.SMTPAuths c.Data["SMTPAuths"] = models.SMTPAuths
ctx.HTML(200, AUTH_NEW) c.HTML(200, AUTH_NEW)
} }
func parseLDAPConfig(f form.Authentication) *models.LDAPConfig { 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) { func NewAuthSourcePost(c *context.Context, f form.Authentication) {
ctx.Data["Title"] = ctx.Tr("admin.auths.new") c.Data["Title"] = c.Tr("admin.auths.new")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true c.Data["PageIsAdminAuthentications"] = true
ctx.Data["CurrentTypeName"] = models.LoginNames[models.LoginType(f.Type)] c.Data["CurrentTypeName"] = models.LoginNames[models.LoginType(f.Type)]
ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocol(f.SecurityProtocol)] c.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocol(f.SecurityProtocol)]
ctx.Data["AuthSources"] = authSources c.Data["AuthSources"] = authSources
ctx.Data["SecurityProtocols"] = securityProtocols c.Data["SecurityProtocols"] = securityProtocols
ctx.Data["SMTPAuths"] = models.SMTPAuths c.Data["SMTPAuths"] = models.SMTPAuths
hasTLS := false hasTLS := false
var config core.Conversion var config core.Conversion
@ -140,13 +140,13 @@ func NewAuthSourcePost(ctx *context.Context, f form.Authentication) {
ServiceName: f.PAMServiceName, ServiceName: f.PAMServiceName,
} }
default: default:
ctx.Error(400) c.Error(400)
return return
} }
ctx.Data["HasTLS"] = hasTLS c.Data["HasTLS"] = hasTLS
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, AUTH_NEW) c.HTML(200, AUTH_NEW)
return return
} }
@ -157,56 +157,56 @@ func NewAuthSourcePost(ctx *context.Context, f form.Authentication) {
Cfg: config, Cfg: config,
}); err != nil { }); err != nil {
if models.IsErrLoginSourceAlreadyExist(err) { if models.IsErrLoginSourceAlreadyExist(err) {
ctx.Data["Err_Name"] = true c.Data["Err_Name"] = true
ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(models.ErrLoginSourceAlreadyExist).Name), AUTH_NEW, f) c.RenderWithErr(c.Tr("admin.auths.login_source_exist", err.(models.ErrLoginSourceAlreadyExist).Name), AUTH_NEW, f)
} else { } else {
ctx.Handle(500, "CreateSource", err) c.Handle(500, "CreateSource", err)
} }
return 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)) c.Flash.Success(c.Tr("admin.auths.new_success", f.Name))
ctx.Redirect(setting.AppSubURL + "/admin/auths") c.Redirect(setting.AppSubURL + "/admin/auths")
} }
func EditAuthSource(ctx *context.Context) { func EditAuthSource(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.auths.edit") c.Data["Title"] = c.Tr("admin.auths.edit")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true c.Data["PageIsAdminAuthentications"] = true
ctx.Data["SecurityProtocols"] = securityProtocols c.Data["SecurityProtocols"] = securityProtocols
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 { if err != nil {
ctx.Handle(500, "GetLoginSourceByID", err) c.Handle(500, "GetLoginSourceByID", err)
return return
} }
ctx.Data["Source"] = source c.Data["Source"] = source
ctx.Data["HasTLS"] = source.HasTLS() c.Data["HasTLS"] = source.HasTLS()
ctx.HTML(200, AUTH_EDIT) c.HTML(200, AUTH_EDIT)
} }
func EditAuthSourcePost(ctx *context.Context, f form.Authentication) { func EditAuthSourcePost(c *context.Context, f form.Authentication) {
ctx.Data["Title"] = ctx.Tr("admin.auths.edit") c.Data["Title"] = c.Tr("admin.auths.edit")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = 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 { if err != nil {
ctx.Handle(500, "GetLoginSourceByID", err) c.Handle(500, "GetLoginSourceByID", err)
return return
} }
ctx.Data["Source"] = source c.Data["Source"] = source
ctx.Data["HasTLS"] = source.HasTLS() c.Data["HasTLS"] = source.HasTLS()
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, AUTH_EDIT) c.HTML(200, AUTH_EDIT)
return return
} }
@ -221,7 +221,7 @@ func EditAuthSourcePost(ctx *context.Context, f form.Authentication) {
ServiceName: f.PAMServiceName, ServiceName: f.PAMServiceName,
} }
default: default:
ctx.Error(400) c.Error(400)
return return
} }
@ -229,37 +229,37 @@ func EditAuthSourcePost(ctx *context.Context, f form.Authentication) {
source.IsActived = f.IsActive source.IsActived = f.IsActive
source.Cfg = config source.Cfg = config
if err := models.UpdateSource(source); err != nil { if err := models.UpdateSource(source); err != nil {
ctx.Handle(500, "UpdateSource", err) c.Handle(500, "UpdateSource", err)
return 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")) c.Flash.Success(c.Tr("admin.auths.update_success"))
ctx.Redirect(setting.AppSubURL + "/admin/auths/" + com.ToStr(f.ID)) c.Redirect(setting.AppSubURL + "/admin/auths/" + com.ToStr(f.ID))
} }
func DeleteAuthSource(ctx *context.Context) { func DeleteAuthSource(c *context.Context) {
source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid")) source, err := models.GetLoginSourceByID(c.ParamsInt64(":authid"))
if err != nil { if err != nil {
ctx.Handle(500, "GetLoginSourceByID", err) c.Handle(500, "GetLoginSourceByID", err)
return return
} }
if err = models.DeleteSource(source); err != nil { if err = models.DeleteSource(source); err != nil {
if models.IsErrLoginSourceInUse(err) { 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 { } else {
ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err)) c.Flash.Error(fmt.Sprintf("DeleteSource: %v", err))
} }
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/auths/" + ctx.Params(":authid"), "redirect": setting.AppSubURL + "/admin/auths/" + c.Params(":authid"),
}) })
return 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")) c.Flash.Success(c.Tr("admin.auths.deletion_success"))
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/auths", "redirect": setting.AppSubURL + "/admin/auths",
}) })
} }

42
routers/admin/notice.go

@ -18,31 +18,31 @@ const (
NOTICES = "admin/notice" NOTICES = "admin/notice"
) )
func Notices(ctx *context.Context) { func Notices(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.notices") c.Data["Title"] = c.Tr("admin.notices")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminNotices"] = true c.Data["PageIsAdminNotices"] = true
total := models.CountNotices() total := models.CountNotices()
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page <= 1 { if page <= 1 {
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) notices, err := models.Notices(page, setting.UI.Admin.NoticePagingNum)
if err != nil { if err != nil {
ctx.Handle(500, "Notices", err) c.Handle(500, "Notices", err)
return return
} }
ctx.Data["Notices"] = notices c.Data["Notices"] = notices
ctx.Data["Total"] = total c.Data["Total"] = total
ctx.HTML(200, NOTICES) c.HTML(200, NOTICES)
} }
func DeleteNotices(ctx *context.Context) { func DeleteNotices(c *context.Context) {
strs := ctx.QueryStrings("ids[]") strs := c.QueryStrings("ids[]")
ids := make([]int64, 0, len(strs)) ids := make([]int64, 0, len(strs))
for i := range strs { for i := range strs {
id := com.StrTo(strs[i]).MustInt64() id := com.StrTo(strs[i]).MustInt64()
@ -52,21 +52,21 @@ func DeleteNotices(ctx *context.Context) {
} }
if err := models.DeleteNoticesByIDs(ids); err != nil { if err := models.DeleteNoticesByIDs(ids); err != nil {
ctx.Flash.Error("DeleteNoticesByIDs: " + err.Error()) c.Flash.Error("DeleteNoticesByIDs: " + err.Error())
ctx.Status(500) c.Status(500)
} else { } else {
ctx.Flash.Success(ctx.Tr("admin.notices.delete_success")) c.Flash.Success(c.Tr("admin.notices.delete_success"))
ctx.Status(200) c.Status(200)
} }
} }
func EmptyNotices(ctx *context.Context) { func EmptyNotices(c *context.Context) {
if err := models.DeleteNotices(0, 0); err != nil { if err := models.DeleteNotices(0, 0); err != nil {
ctx.Handle(500, "DeleteNotices", err) c.Handle(500, "DeleteNotices", err)
return return
} }
log.Trace("System notices deleted by admin (%s): [start: %d]", ctx.User.Name, 0) log.Trace("System notices deleted by admin (%s): [start: %d]", c.User.Name, 0)
ctx.Flash.Success(ctx.Tr("admin.notices.delete_success")) c.Flash.Success(c.Tr("admin.notices.delete_success"))
ctx.Redirect(setting.AppSubURL + "/admin/notices") c.Redirect(setting.AppSubURL + "/admin/notices")
} }

10
routers/admin/orgs.go

@ -15,12 +15,12 @@ const (
ORGS = "admin/org/list" ORGS = "admin/org/list"
) )
func Organizations(ctx *context.Context) { func Organizations(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.organizations") c.Data["Title"] = c.Tr("admin.organizations")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminOrganizations"] = true c.Data["PageIsAdminOrganizations"] = true
routers.RenderUserSearch(ctx, &routers.UserSearchOptions{ routers.RenderUserSearch(c, &routers.UserSearchOptions{
Type: models.USER_TYPE_ORGANIZATION, Type: models.USER_TYPE_ORGANIZATION,
Counter: models.CountOrganizations, Counter: models.CountOrganizations,
Ranger: models.Organizations, Ranger: models.Organizations,

42
routers/admin/repos.go

@ -17,12 +17,12 @@ const (
REPOS = "admin/repo/list" REPOS = "admin/repo/list"
) )
func Repos(ctx *context.Context) { func Repos(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.repositories") c.Data["Title"] = c.Tr("admin.repositories")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminRepositories"] = true c.Data["PageIsAdminRepositories"] = true
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page <= 0 { if page <= 0 {
page = 1 page = 1
} }
@ -33,11 +33,11 @@ func Repos(ctx *context.Context) {
err error err error
) )
keyword := ctx.Query("q") keyword := c.Query("q")
if len(keyword) == 0 { if len(keyword) == 0 {
repos, err = models.Repositories(page, setting.UI.Admin.RepoPagingNum) repos, err = models.Repositories(page, setting.UI.Admin.RepoPagingNum)
if err != nil { if err != nil {
ctx.Handle(500, "Repositories", err) c.Handle(500, "Repositories", err)
return return
} }
count = models.CountRepositories(true) count = models.CountRepositories(true)
@ -50,38 +50,38 @@ func Repos(ctx *context.Context) {
PageSize: setting.UI.Admin.RepoPagingNum, PageSize: setting.UI.Admin.RepoPagingNum,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "SearchRepositoryByName", err) c.Handle(500, "SearchRepositoryByName", err)
return return
} }
} }
ctx.Data["Keyword"] = keyword c.Data["Keyword"] = keyword
ctx.Data["Total"] = count c.Data["Total"] = count
ctx.Data["Page"] = paginater.New(int(count), setting.UI.Admin.RepoPagingNum, page, 5) c.Data["Page"] = paginater.New(int(count), setting.UI.Admin.RepoPagingNum, page, 5)
if err = models.RepositoryList(repos).LoadAttributes(); err != nil { if err = models.RepositoryList(repos).LoadAttributes(); err != nil {
ctx.Handle(500, "LoadAttributes", err) c.Handle(500, "LoadAttributes", err)
return return
} }
ctx.Data["Repos"] = repos c.Data["Repos"] = repos
ctx.HTML(200, REPOS) c.HTML(200, REPOS)
} }
func DeleteRepo(ctx *context.Context) { func DeleteRepo(c *context.Context) {
repo, err := models.GetRepositoryByID(ctx.QueryInt64("id")) repo, err := models.GetRepositoryByID(c.QueryInt64("id"))
if err != nil { if err != nil {
ctx.Handle(500, "GetRepositoryByID", err) c.Handle(500, "GetRepositoryByID", err)
return return
} }
if err := models.DeleteRepository(repo.MustOwner().ID, repo.ID); err != nil { if err := models.DeleteRepository(repo.MustOwner().ID, repo.ID); err != nil {
ctx.Handle(500, "DeleteRepository", err) c.Handle(500, "DeleteRepository", err)
return return
} }
log.Trace("Repository deleted: %s/%s", repo.MustOwner().Name, repo.Name) log.Trace("Repository deleted: %s/%s", repo.MustOwner().Name, repo.Name)
ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success")) c.Flash.Success(c.Tr("repo.settings.deletion_success"))
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/repos?page=" + ctx.Query("page"), "redirect": setting.AppSubURL + "/admin/repos?page=" + c.Query("page"),
}) })
} }

164
routers/admin/users.go

@ -24,12 +24,12 @@ const (
USER_EDIT = "admin/user/edit" USER_EDIT = "admin/user/edit"
) )
func Users(ctx *context.Context) { func Users(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.users") c.Data["Title"] = c.Tr("admin.users")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true c.Data["PageIsAdminUsers"] = true
routers.RenderUserSearch(ctx, &routers.UserSearchOptions{ routers.RenderUserSearch(c, &routers.UserSearchOptions{
Type: models.USER_TYPE_INDIVIDUAL, Type: models.USER_TYPE_INDIVIDUAL,
Counter: models.CountUsers, Counter: models.CountUsers,
Ranger: models.Users, Ranger: models.Users,
@ -39,40 +39,40 @@ func Users(ctx *context.Context) {
}) })
} }
func NewUser(ctx *context.Context) { func NewUser(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.users.new_account") c.Data["Title"] = c.Tr("admin.users.new_account")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true c.Data["PageIsAdminUsers"] = true
ctx.Data["login_type"] = "0-0" c.Data["login_type"] = "0-0"
sources, err := models.LoginSources() sources, err := models.LoginSources()
if err != nil { if err != nil {
ctx.Handle(500, "LoginSources", err) c.Handle(500, "LoginSources", err)
return return
} }
ctx.Data["Sources"] = sources c.Data["Sources"] = sources
ctx.Data["CanSendEmail"] = setting.MailService != nil c.Data["CanSendEmail"] = setting.MailService != nil
ctx.HTML(200, USER_NEW) c.HTML(200, USER_NEW)
} }
func NewUserPost(ctx *context.Context, f form.AdminCrateUser) { func NewUserPost(c *context.Context, f form.AdminCrateUser) {
ctx.Data["Title"] = ctx.Tr("admin.users.new_account") c.Data["Title"] = c.Tr("admin.users.new_account")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true c.Data["PageIsAdminUsers"] = true
sources, err := models.LoginSources() sources, err := models.LoginSources()
if err != nil { if err != nil {
ctx.Handle(500, "LoginSources", err) c.Handle(500, "LoginSources", err)
return return
} }
ctx.Data["Sources"] = sources c.Data["Sources"] = sources
ctx.Data["CanSendEmail"] = setting.MailService != nil c.Data["CanSendEmail"] = setting.MailService != nil
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, USER_NEW) c.HTML(200, USER_NEW)
return return
} }
@ -96,88 +96,88 @@ func NewUserPost(ctx *context.Context, f form.AdminCrateUser) {
if err := models.CreateUser(u); err != nil { if err := models.CreateUser(u); err != nil {
switch { switch {
case models.IsErrUserAlreadyExist(err): case models.IsErrUserAlreadyExist(err):
ctx.Data["Err_UserName"] = true c.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), USER_NEW, &f) c.RenderWithErr(c.Tr("form.username_been_taken"), USER_NEW, &f)
case models.IsErrEmailAlreadyUsed(err): case models.IsErrEmailAlreadyUsed(err):
ctx.Data["Err_Email"] = true c.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_NEW, &f) c.RenderWithErr(c.Tr("form.email_been_used"), USER_NEW, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.Data["Err_UserName"] = true c.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), USER_NEW, &f) c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), USER_NEW, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_UserName"] = true c.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), USER_NEW, &f) c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), USER_NEW, &f)
default: default:
ctx.Handle(500, "CreateUser", err) c.Handle(500, "CreateUser", err)
} }
return 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. // Send email notification.
if f.SendNotify && setting.MailService != nil { 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)) c.Flash.Success(c.Tr("admin.users.new_success", u.Name))
ctx.Redirect(setting.AppSubURL + "/admin/users/" + com.ToStr(u.ID)) c.Redirect(setting.AppSubURL + "/admin/users/" + com.ToStr(u.ID))
} }
func prepareUserInfo(ctx *context.Context) *models.User { func prepareUserInfo(c *context.Context) *models.User {
u, err := models.GetUserByID(ctx.ParamsInt64(":userid")) u, err := models.GetUserByID(c.ParamsInt64(":userid"))
if err != nil { if err != nil {
ctx.Handle(500, "GetUserByID", err) c.Handle(500, "GetUserByID", err)
return nil return nil
} }
ctx.Data["User"] = u c.Data["User"] = u
if u.LoginSource > 0 { if u.LoginSource > 0 {
ctx.Data["LoginSource"], err = models.GetLoginSourceByID(u.LoginSource) c.Data["LoginSource"], err = models.GetLoginSourceByID(u.LoginSource)
if err != nil { if err != nil {
ctx.Handle(500, "GetLoginSourceByID", err) c.Handle(500, "GetLoginSourceByID", err)
return nil return nil
} }
} else { } else {
ctx.Data["LoginSource"] = &models.LoginSource{} c.Data["LoginSource"] = &models.LoginSource{}
} }
sources, err := models.LoginSources() sources, err := models.LoginSources()
if err != nil { if err != nil {
ctx.Handle(500, "LoginSources", err) c.Handle(500, "LoginSources", err)
return nil return nil
} }
ctx.Data["Sources"] = sources c.Data["Sources"] = sources
return u return u
} }
func EditUser(ctx *context.Context) { func EditUser(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("admin.users.edit_account") c.Data["Title"] = c.Tr("admin.users.edit_account")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true c.Data["PageIsAdminUsers"] = true
ctx.Data["EnableLocalPathMigration"] = setting.Repository.EnableLocalPathMigration c.Data["EnableLocalPathMigration"] = setting.Repository.EnableLocalPathMigration
prepareUserInfo(ctx) prepareUserInfo(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.HTML(200, USER_EDIT) c.HTML(200, USER_EDIT)
} }
func EditUserPost(ctx *context.Context, f form.AdminEditUser) { func EditUserPost(c *context.Context, f form.AdminEditUser) {
ctx.Data["Title"] = ctx.Tr("admin.users.edit_account") c.Data["Title"] = c.Tr("admin.users.edit_account")
ctx.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminUsers"] = true c.Data["PageIsAdminUsers"] = true
ctx.Data["EnableLocalPathMigration"] = setting.Repository.EnableLocalPathMigration c.Data["EnableLocalPathMigration"] = setting.Repository.EnableLocalPathMigration
u := prepareUserInfo(ctx) u := prepareUserInfo(c)
if ctx.Written() { if c.Written() {
return return
} }
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, USER_EDIT) c.HTML(200, USER_EDIT)
return return
} }
@ -196,7 +196,7 @@ func EditUserPost(ctx *context.Context, f form.AdminEditUser) {
u.Passwd = f.Password u.Passwd = f.Password
var err error var err error
if u.Salt, err = models.GetUserSalt(); err != nil { if u.Salt, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
return return
} }
u.EncodePasswd() u.EncodePasswd()
@ -216,47 +216,47 @@ func EditUserPost(ctx *context.Context, f form.AdminEditUser) {
if err := models.UpdateUser(u); err != nil { if err := models.UpdateUser(u); err != nil {
if models.IsErrEmailAlreadyUsed(err) { if models.IsErrEmailAlreadyUsed(err) {
ctx.Data["Err_Email"] = true c.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_EDIT, &f) c.RenderWithErr(c.Tr("form.email_been_used"), USER_EDIT, &f)
} else { } else {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
} }
return 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")) c.Flash.Success(c.Tr("admin.users.update_profile_success"))
ctx.Redirect(setting.AppSubURL + "/admin/users/" + ctx.Params(":userid")) c.Redirect(setting.AppSubURL + "/admin/users/" + c.Params(":userid"))
} }
func DeleteUser(ctx *context.Context) { func DeleteUser(c *context.Context) {
u, err := models.GetUserByID(ctx.ParamsInt64(":userid")) u, err := models.GetUserByID(c.ParamsInt64(":userid"))
if err != nil { if err != nil {
ctx.Handle(500, "GetUserByID", err) c.Handle(500, "GetUserByID", err)
return return
} }
if err = models.DeleteUser(u); err != nil { if err = models.DeleteUser(u); err != nil {
switch { switch {
case models.IsErrUserOwnRepos(err): case models.IsErrUserOwnRepos(err):
ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo")) c.Flash.Error(c.Tr("admin.users.still_own_repo"))
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"), "redirect": setting.AppSubURL + "/admin/users/" + c.Params(":userid"),
}) })
case models.IsErrUserHasOrgs(err): case models.IsErrUserHasOrgs(err):
ctx.Flash.Error(ctx.Tr("admin.users.still_has_org")) c.Flash.Error(c.Tr("admin.users.still_has_org"))
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"), "redirect": setting.AppSubURL + "/admin/users/" + c.Params(":userid"),
}) })
default: default:
ctx.Handle(500, "DeleteUser", err) c.Handle(500, "DeleteUser", err)
} }
return 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")) c.Flash.Success(c.Tr("admin.users.deletion_success"))
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": setting.AppSubURL + "/admin/users", "redirect": setting.AppSubURL + "/admin/users",
}) })
} }

12
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 // https://github.com/gogits/go-gogs-client/wiki/Administration-Organizations#create-a-new-organization
func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) { func CreateOrg(c *context.APIContext, form api.CreateOrgOption) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
@ -33,12 +33,12 @@ func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) {
if models.IsErrUserAlreadyExist(err) || if models.IsErrUserAlreadyExist(err) ||
models.IsErrNameReserved(err) || models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) { models.IsErrNamePatternNotAllowed(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "CreateOrganization", err) c.Error(500, "CreateOrganization", err)
} }
return return
} }
ctx.JSON(201, convert.ToOrganization(org)) c.JSON(201, convert.ToOrganization(org))
} }

32
routers/api/v1/admin/org_repo.go

@ -10,41 +10,41 @@ import (
"github.com/gogits/gogs/pkg/context" "github.com/gogits/gogs/pkg/context"
) )
func GetRepositoryByParams(ctx *context.APIContext) *models.Repository { func GetRepositoryByParams(c *context.APIContext) *models.Repository {
repo, err := models.GetRepositoryByName(ctx.Org.Team.OrgID, ctx.Params(":reponame")) repo, err := models.GetRepositoryByName(c.Org.Team.OrgID, c.Params(":reponame"))
if err != nil { if err != nil {
if errors.IsRepoNotExist(err) { if errors.IsRepoNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetRepositoryByName", err) c.Error(500, "GetRepositoryByName", err)
} }
return nil return nil
} }
return repo return repo
} }
func AddTeamRepository(ctx *context.APIContext) { func AddTeamRepository(c *context.APIContext) {
repo := GetRepositoryByParams(ctx) repo := GetRepositoryByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
if err := ctx.Org.Team.AddRepository(repo); err != nil { if err := c.Org.Team.AddRepository(repo); err != nil {
ctx.Error(500, "AddRepository", err) c.Error(500, "AddRepository", err)
return return
} }
ctx.Status(204) c.Status(204)
} }
func RemoveTeamRepository(ctx *context.APIContext) { func RemoveTeamRepository(c *context.APIContext) {
repo := GetRepositoryByParams(ctx) repo := GetRepositoryByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
if err := ctx.Org.Team.RemoveRepository(repo.ID); err != nil { if err := c.Org.Team.RemoveRepository(repo.ID); err != nil {
ctx.Error(500, "RemoveRepository", err) c.Error(500, "RemoveRepository", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

34
routers/api/v1/admin/org_team.go

@ -13,48 +13,48 @@ import (
"github.com/gogits/gogs/routers/api/v1/user" "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{ team := &models.Team{
OrgID: ctx.Org.Organization.ID, OrgID: c.Org.Organization.ID,
Name: form.Name, Name: form.Name,
Description: form.Description, Description: form.Description,
Authorize: models.ParseAccessMode(form.Permission), Authorize: models.ParseAccessMode(form.Permission),
} }
if err := models.NewTeam(team); err != nil { if err := models.NewTeam(team); err != nil {
if models.IsErrTeamAlreadyExist(err) { if models.IsErrTeamAlreadyExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "NewTeam", err) c.Error(500, "NewTeam", err)
} }
return return
} }
ctx.JSON(201, convert.ToTeam(team)) c.JSON(201, convert.ToTeam(team))
} }
func AddTeamMember(ctx *context.APIContext) { func AddTeamMember(c *context.APIContext) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
if err := ctx.Org.Team.AddMember(u.ID); err != nil { if err := c.Org.Team.AddMember(u.ID); err != nil {
ctx.Error(500, "AddMember", err) c.Error(500, "AddMember", err)
return return
} }
ctx.Status(204) c.Status(204)
} }
func RemoveTeamMember(ctx *context.APIContext) { func RemoveTeamMember(c *context.APIContext) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
if err := ctx.Org.Team.RemoveMember(u.ID); err != nil { if err := c.Org.Team.RemoveMember(u.ID); err != nil {
ctx.Error(500, "RemoveMember", err) c.Error(500, "RemoveMember", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

8
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 // https://github.com/gogits/go-gogs-client/wiki/Administration-Repositories#create-a-new-repository
func CreateRepo(ctx *context.APIContext, form api.CreateRepoOption) { func CreateRepo(c *context.APIContext, form api.CreateRepoOption) {
owner := user.GetUserByParams(ctx) owner := user.GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
repo.CreateUserRepo(ctx, owner, form) repo.CreateUserRepo(c, owner, form)
} }

64
routers/api/v1/admin/user.go

@ -16,7 +16,7 @@ import (
"github.com/gogits/gogs/routers/api/v1/user" "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 { if sourceID == 0 {
return return
} }
@ -24,9 +24,9 @@ func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, l
source, err := models.GetLoginSourceByID(sourceID) source, err := models.GetLoginSourceByID(sourceID)
if err != nil { if err != nil {
if models.IsErrLoginSourceNotExist(err) { if models.IsErrLoginSourceNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetLoginSourceByID", err) c.Error(500, "GetLoginSourceByID", err)
} }
return 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 // 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{ u := &models.User{
Name: form.Username, Name: form.Username,
FullName: form.FullName, FullName: form.FullName,
@ -47,8 +47,8 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) {
LoginType: models.LOGIN_PLAIN, LoginType: models.LOGIN_PLAIN,
} }
parseLoginSource(ctx, u, form.SourceID, form.LoginName) parseLoginSource(c, u, form.SourceID, form.LoginName)
if ctx.Written() { if c.Written() {
return return
} }
@ -57,31 +57,31 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) {
models.IsErrEmailAlreadyUsed(err) || models.IsErrEmailAlreadyUsed(err) ||
models.IsErrNameReserved(err) || models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) { models.IsErrNamePatternNotAllowed(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "CreateUser", err) c.Error(500, "CreateUser", err)
} }
return 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. // Send email notification.
if form.SendNotify && setting.MailService != nil { 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 // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#edit-an-existing-user
func EditUser(ctx *context.APIContext, form api.EditUserOption) { func EditUser(c *context.APIContext, form api.EditUserOption) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
parseLoginSource(ctx, u, form.SourceID, form.LoginName) parseLoginSource(c, u, form.SourceID, form.LoginName)
if ctx.Written() { if c.Written() {
return return
} }
@ -89,7 +89,7 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) {
u.Passwd = form.Password u.Passwd = form.Password
var err error var err error
if u.Salt, err = models.GetUserSalt(); err != nil { if u.Salt, err = models.GetUserSalt(); err != nil {
ctx.Error(500, "UpdateUser", err) c.Error(500, "UpdateUser", err)
return return
} }
u.EncodePasswd() u.EncodePasswd()
@ -118,43 +118,43 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) {
if err := models.UpdateUser(u); err != nil { if err := models.UpdateUser(u); err != nil {
if models.IsErrEmailAlreadyUsed(err) { if models.IsErrEmailAlreadyUsed(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "UpdateUser", err) c.Error(500, "UpdateUser", err)
} }
return 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 // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#delete-a-user
func DeleteUser(ctx *context.APIContext) { func DeleteUser(c *context.APIContext) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
if err := models.DeleteUser(u); err != nil { if err := models.DeleteUser(u); err != nil {
if models.IsErrUserOwnRepos(err) || if models.IsErrUserOwnRepos(err) ||
models.IsErrUserHasOrgs(err) { models.IsErrUserHasOrgs(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "DeleteUser", err) c.Error(500, "DeleteUser", err)
} }
return 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 // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-public-key-for-user
func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) { func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
user.CreateUserPublicKey(ctx, form, u.ID) user.CreateUserPublicKey(c, form, u.ID)
} }

88
routers/api/v1/api.go

@ -24,9 +24,9 @@ import (
) )
func repoAssignment() macaron.Handler { func repoAssignment() macaron.Handler {
return func(ctx *context.APIContext) { return func(c *context.APIContext) {
userName := ctx.Params(":username") userName := c.Params(":username")
repoName := ctx.Params(":reponame") repoName := c.Params(":reponame")
var ( var (
owner *models.User owner *models.User
@ -34,87 +34,87 @@ func repoAssignment() macaron.Handler {
) )
// Check if the user is the same as the repository owner. // Check if the user is the same as the repository owner.
if ctx.IsLogged && ctx.User.LowerName == strings.ToLower(userName) { if c.IsLogged && c.User.LowerName == strings.ToLower(userName) {
owner = ctx.User owner = c.User
} else { } else {
owner, err = models.GetUserByName(userName) owner, err = models.GetUserByName(userName)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return return
} }
} }
ctx.Repo.Owner = owner c.Repo.Owner = owner
// Get repository. // Get repository.
repo, err := models.GetRepositoryByName(owner.ID, repoName) repo, err := models.GetRepositoryByName(owner.ID, repoName)
if err != nil { if err != nil {
if errors.IsRepoNotExist(err) { if errors.IsRepoNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetRepositoryByName", err) c.Error(500, "GetRepositoryByName", err)
} }
return return
} else if err = repo.GetOwner(); err != nil { } else if err = repo.GetOwner(); err != nil {
ctx.Error(500, "GetOwner", err) c.Error(500, "GetOwner", err)
return return
} }
if ctx.IsLogged && ctx.User.IsAdmin { if c.IsLogged && c.User.IsAdmin {
ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER c.Repo.AccessMode = models.ACCESS_MODE_OWNER
} else { } else {
mode, err := models.AccessLevel(ctx.User.ID, repo) mode, err := models.AccessLevel(c.User.ID, repo)
if err != nil { if err != nil {
ctx.Error(500, "AccessLevel", err) c.Error(500, "AccessLevel", err)
return return
} }
ctx.Repo.AccessMode = mode c.Repo.AccessMode = mode
} }
if !ctx.Repo.HasAccess() { if !c.Repo.HasAccess() {
ctx.Status(404) c.Status(404)
return return
} }
ctx.Repo.Repository = repo c.Repo.Repository = repo
} }
} }
// Contexter middleware already checks token for user sign in process. // Contexter middleware already checks token for user sign in process.
func reqToken() macaron.Handler { func reqToken() macaron.Handler {
return func(ctx *context.Context) { return func(c *context.Context) {
if !ctx.IsLogged { if !c.IsLogged {
ctx.Error(401) c.Error(401)
return return
} }
} }
} }
func reqBasicAuth() macaron.Handler { func reqBasicAuth() macaron.Handler {
return func(ctx *context.Context) { return func(c *context.Context) {
if !ctx.IsBasicAuth { if !c.IsBasicAuth {
ctx.Error(401) c.Error(401)
return return
} }
} }
} }
func reqAdmin() macaron.Handler { func reqAdmin() macaron.Handler {
return func(ctx *context.Context) { return func(c *context.Context) {
if !ctx.IsLogged || !ctx.User.IsAdmin { if !c.IsLogged || !c.User.IsAdmin {
ctx.Error(403) c.Error(403)
return return
} }
} }
} }
func reqRepoWriter() macaron.Handler { func reqRepoWriter() macaron.Handler {
return func(ctx *context.Context) { return func(c *context.Context) {
if !ctx.Repo.IsWriter() { if !c.Repo.IsWriter() {
ctx.Error(403) c.Error(403)
return return
} }
} }
@ -131,29 +131,29 @@ func orgAssignment(args ...bool) macaron.Handler {
if len(args) > 1 { if len(args) > 1 {
assignTeam = args[1] assignTeam = args[1]
} }
return func(ctx *context.APIContext) { return func(c *context.APIContext) {
ctx.Org = new(context.APIOrganization) c.Org = new(context.APIOrganization)
var err error var err error
if assignOrg { if assignOrg {
ctx.Org.Organization, err = models.GetUserByName(ctx.Params(":orgname")) c.Org.Organization, err = models.GetUserByName(c.Params(":orgname"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return return
} }
} }
if assignTeam { if assignTeam {
ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid")) c.Org.Team, err = models.GetTeamByID(c.ParamsInt64(":teamid"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetTeamById", err) c.Error(500, "GetTeamById", err)
} }
return return
} }
@ -161,9 +161,9 @@ func orgAssignment(args ...bool) macaron.Handler {
} }
} }
func mustEnableIssues(ctx *context.APIContext) { func mustEnableIssues(c *context.APIContext) {
if !ctx.Repo.Repository.EnableIssues || ctx.Repo.Repository.EnableExternalTracker { if !c.Repo.Repository.EnableIssues || c.Repo.Repository.EnableExternalTracker {
ctx.Status(404) c.Status(404)
return return
} }
} }
@ -323,8 +323,8 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Combo("/teams").Get(org.ListTeams) m.Combo("/teams").Get(org.ListTeams)
}, orgAssignment(true)) }, orgAssignment(true))
m.Any("/*", func(ctx *context.Context) { m.Any("/*", func(c *context.Context) {
ctx.Error(404) c.Error(404)
}) })
m.Group("/admin", func() { m.Group("/admin", func() {

20
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 // https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document
func Markdown(ctx *context.APIContext, form api.MarkdownOption) { func Markdown(c *context.APIContext, form api.MarkdownOption) {
if ctx.HasApiError() { if c.HasApiError() {
ctx.Error(422, "", ctx.GetErrMsg()) c.Error(422, "", c.GetErrMsg())
return return
} }
if len(form.Text) == 0 { if len(form.Text) == 0 {
ctx.Write([]byte("")) c.Write([]byte(""))
return return
} }
switch form.Mode { switch form.Mode {
case "gfm": case "gfm":
ctx.Write(markup.Markdown([]byte(form.Text), form.Context, nil)) c.Write(markup.Markdown([]byte(form.Text), form.Context, nil))
default: 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 // https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-a-markdown-document-in-raw-mode
func MarkdownRaw(ctx *context.APIContext) { func MarkdownRaw(c *context.APIContext) {
body, err := ctx.Req.Body().Bytes() body, err := c.Req.Body().Bytes()
if err != nil { if err != nil {
ctx.Error(422, "", err) c.Error(422, "", err)
return return
} }
ctx.Write(markup.RawMarkdown(body, "")) c.Write(markup.RawMarkdown(body, ""))
} }

34
routers/api/v1/org/org.go

@ -13,9 +13,9 @@ import (
"github.com/gogits/gogs/routers/api/v1/user" "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 { if err := u.GetOrganizations(all); err != nil {
ctx.Error(500, "GetOrganizations", err) c.Error(500, "GetOrganizations", err)
return return
} }
@ -23,33 +23,33 @@ func listUserOrgs(ctx *context.APIContext, u *models.User, all bool) {
for i := range u.Orgs { for i := range u.Orgs {
apiOrgs[i] = convert.ToOrganization(u.Orgs[i]) 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 // https://github.com/gogits/go-gogs-client/wiki/Organizations#list-your-organizations
func ListMyOrgs(ctx *context.APIContext) { func ListMyOrgs(c *context.APIContext) {
listUserOrgs(ctx, ctx.User, true) listUserOrgs(c, c.User, true)
} }
// https://github.com/gogits/go-gogs-client/wiki/Organizations#list-user-organizations // https://github.com/gogits/go-gogs-client/wiki/Organizations#list-user-organizations
func ListUserOrgs(ctx *context.APIContext) { func ListUserOrgs(c *context.APIContext) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
listUserOrgs(ctx, u, false) listUserOrgs(c, u, false)
} }
// https://github.com/gogits/go-gogs-client/wiki/Organizations#get-an-organization // https://github.com/gogits/go-gogs-client/wiki/Organizations#get-an-organization
func Get(ctx *context.APIContext) { func Get(c *context.APIContext) {
ctx.JSON(200, convert.ToOrganization(ctx.Org.Organization)) c.JSON(200, convert.ToOrganization(c.Org.Organization))
} }
// https://github.com/gogits/go-gogs-client/wiki/Organizations#edit-an-organization // https://github.com/gogits/go-gogs-client/wiki/Organizations#edit-an-organization
func Edit(ctx *context.APIContext, form api.EditOrgOption) { func Edit(c *context.APIContext, form api.EditOrgOption) {
org := ctx.Org.Organization org := c.Org.Organization
if !org.IsOwnedBy(ctx.User.ID) { if !org.IsOwnedBy(c.User.ID) {
ctx.Status(403) c.Status(403)
return return
} }
@ -58,9 +58,9 @@ func Edit(ctx *context.APIContext, form api.EditOrgOption) {
org.Website = form.Website org.Website = form.Website
org.Location = form.Location org.Location = form.Location
if err := models.UpdateUser(org); err != nil { if err := models.UpdateUser(org); err != nil {
ctx.Error(500, "UpdateUser", err) c.Error(500, "UpdateUser", err)
return return
} }
ctx.JSON(200, convert.ToOrganization(org)) c.JSON(200, convert.ToOrganization(org))
} }

8
routers/api/v1/org/team.go

@ -11,10 +11,10 @@ import (
"github.com/gogits/gogs/routers/api/v1/convert" "github.com/gogits/gogs/routers/api/v1/convert"
) )
func ListTeams(ctx *context.APIContext) { func ListTeams(c *context.APIContext) {
org := ctx.Org.Organization org := c.Org.Organization
if err := org.GetTeams(); err != nil { if err := org.GetTeams(); err != nil {
ctx.Error(500, "GetTeams", err) c.Error(500, "GetTeams", err)
return return
} }
@ -22,5 +22,5 @@ func ListTeams(ctx *context.APIContext) {
for i := range org.Teams { for i := range org.Teams {
apiTeams[i] = convert.ToTeam(org.Teams[i]) apiTeams[i] = convert.ToTeam(org.Teams[i])
} }
ctx.JSON(200, apiTeams) c.JSON(200, apiTeams)
} }

28
routers/api/v1/repo/branch.go

@ -13,43 +13,43 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Repositories#get-branch // https://github.com/gogits/go-gogs-client/wiki/Repositories#get-branch
func GetBranch(ctx *context.APIContext) { func GetBranch(c *context.APIContext) {
branch, err := ctx.Repo.Repository.GetBranch(ctx.Params("*")) branch, err := c.Repo.Repository.GetBranch(c.Params("*"))
if err != nil { if err != nil {
if models.IsErrBranchNotExist(err) { if models.IsErrBranchNotExist(err) {
ctx.Error(404, "GetBranch", err) c.Error(404, "GetBranch", err)
} else { } else {
ctx.Error(500, "GetBranch", err) c.Error(500, "GetBranch", err)
} }
return return
} }
c, err := branch.GetCommit() commit, err := branch.GetCommit()
if err != nil { if err != nil {
ctx.Error(500, "GetCommit", err) c.Error(500, "GetCommit", err)
return 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 // https://github.com/gogits/go-gogs-client/wiki/Repositories#list-branches
func ListBranches(ctx *context.APIContext) { func ListBranches(c *context.APIContext) {
branches, err := ctx.Repo.Repository.GetBranches() branches, err := c.Repo.Repository.GetBranches()
if err != nil { if err != nil {
ctx.Error(500, "GetBranches", err) c.Error(500, "GetBranches", err)
return return
} }
apiBranches := make([]*api.Branch, len(branches)) apiBranches := make([]*api.Branch, len(branches))
for i := range branches { for i := range branches {
c, err := branches[i].GetCommit() commit, err := branches[i].GetCommit()
if err != nil { if err != nil {
ctx.Error(500, "GetCommit", err) c.Error(500, "GetCommit", err)
return return
} }
apiBranches[i] = convert.ToBranch(branches[i], c) apiBranches[i] = convert.ToBranch(branches[i], commit)
} }
ctx.JSON(200, &apiBranches) c.JSON(200, &apiBranches)
} }

56
routers/api/v1/repo/collaborators.go

@ -12,13 +12,13 @@ import (
"github.com/gogits/gogs/pkg/context" "github.com/gogits/gogs/pkg/context"
) )
func ListCollaborators(ctx *context.APIContext) { func ListCollaborators(c *context.APIContext) {
collaborators, err := ctx.Repo.Repository.GetCollaborators() collaborators, err := c.Repo.Repository.GetCollaborators()
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetCollaborators", err) c.Error(500, "GetCollaborators", err)
} }
return return
} }
@ -27,68 +27,68 @@ func ListCollaborators(ctx *context.APIContext) {
for i := range collaborators { for i := range collaborators {
apiCollaborators[i] = collaborators[i].APIFormat() apiCollaborators[i] = collaborators[i].APIFormat()
} }
ctx.JSON(200, &apiCollaborators) c.JSON(200, &apiCollaborators)
} }
func AddCollaborator(ctx *context.APIContext, form api.AddCollaboratorOption) { func AddCollaborator(c *context.APIContext, form api.AddCollaboratorOption) {
collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) collaborator, err := models.GetUserByName(c.Params(":collaborator"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return return
} }
if err := ctx.Repo.Repository.AddCollaborator(collaborator); err != nil { if err := c.Repo.Repository.AddCollaborator(collaborator); err != nil {
ctx.Error(500, "AddCollaborator", err) c.Error(500, "AddCollaborator", err)
return return
} }
if form.Permission != nil { if form.Permission != nil {
if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(collaborator.ID, models.ParseAccessMode(*form.Permission)); err != nil { if err := c.Repo.Repository.ChangeCollaborationAccessMode(collaborator.ID, models.ParseAccessMode(*form.Permission)); err != nil {
ctx.Error(500, "ChangeCollaborationAccessMode", err) c.Error(500, "ChangeCollaborationAccessMode", err)
return return
} }
} }
ctx.Status(204) c.Status(204)
} }
func IsCollaborator(ctx *context.APIContext) { func IsCollaborator(c *context.APIContext) {
collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) collaborator, err := models.GetUserByName(c.Params(":collaborator"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return return
} }
if !ctx.Repo.Repository.IsCollaborator(collaborator.ID) { if !c.Repo.Repository.IsCollaborator(collaborator.ID) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Status(204) c.Status(204)
} }
} }
func DeleteCollaborator(ctx *context.APIContext) { func DeleteCollaborator(c *context.APIContext) {
collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) collaborator, err := models.GetUserByName(c.Params(":collaborator"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return return
} }
if err := ctx.Repo.Repository.DeleteCollaboration(collaborator.ID); err != nil { if err := c.Repo.Repository.DeleteCollaboration(collaborator.ID); err != nil {
ctx.Error(500, "DeleteCollaboration", err) c.Error(500, "DeleteCollaboration", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

44
routers/api/v1/repo/file.go

@ -13,60 +13,60 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-raw-content // https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-raw-content
func GetRawFile(ctx *context.APIContext) { func GetRawFile(c *context.APIContext) {
if !ctx.Repo.HasAccess() { if !c.Repo.HasAccess() {
ctx.Status(404) c.Status(404)
return return
} }
if ctx.Repo.Repository.IsBare { if c.Repo.Repository.IsBare {
ctx.Status(404) c.Status(404)
return return
} }
blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath) blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath)
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetBlobByPath", err) c.Error(500, "GetBlobByPath", err)
} }
return return
} }
if err = repo.ServeBlob(ctx.Context, blob); err != nil { if err = repo.ServeBlob(c.Context, blob); err != nil {
ctx.Error(500, "ServeBlob", err) c.Error(500, "ServeBlob", err)
} }
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-archive // https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-archive
func GetArchive(ctx *context.APIContext) { func GetArchive(c *context.APIContext) {
repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) repoPath := models.RepoPath(c.Params(":username"), c.Params(":reponame"))
gitRepo, err := git.OpenRepository(repoPath) gitRepo, err := git.OpenRepository(repoPath)
if err != nil { if err != nil {
ctx.Error(500, "OpenRepository", err) c.Error(500, "OpenRepository", err)
return return
} }
ctx.Repo.GitRepo = gitRepo c.Repo.GitRepo = gitRepo
repo.Download(ctx.Context) repo.Download(c.Context)
} }
func GetEditorconfig(ctx *context.APIContext) { func GetEditorconfig(c *context.APIContext) {
ec, err := ctx.Repo.GetEditorconfig() ec, err := c.Repo.GetEditorconfig()
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.Error(404, "GetEditorconfig", err) c.Error(404, "GetEditorconfig", err)
} else { } else {
ctx.Error(500, "GetEditorconfig", err) c.Error(500, "GetEditorconfig", err)
} }
return return
} }
fileName := ctx.Params("filename") fileName := c.Params("filename")
def := ec.GetDefinitionForFilename(fileName) def := ec.GetDefinitionForFilename(fileName)
if def == nil { if def == nil {
ctx.Error(404, "GetDefinitionForFilename", err) c.Error(404, "GetDefinitionForFilename", err)
return return
} }
ctx.JSON(200, def) c.JSON(200, def)
} }

56
routers/api/v1/repo/hook.go

@ -18,34 +18,34 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Repositories#list-hooks // https://github.com/gogits/go-gogs-client/wiki/Repositories#list-hooks
func ListHooks(ctx *context.APIContext) { func ListHooks(c *context.APIContext) {
hooks, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID) hooks, err := models.GetWebhooksByRepoID(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Error(500, "GetWebhooksByRepoID", err) c.Error(500, "GetWebhooksByRepoID", err)
return return
} }
apiHooks := make([]*api.Hook, len(hooks)) apiHooks := make([]*api.Hook, len(hooks))
for i := range 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 // 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) { if !models.IsValidHookTaskType(form.Type) {
ctx.Error(422, "", "Invalid hook type") c.Error(422, "", "Invalid hook type")
return return
} }
for _, name := range []string{"url", "content_type"} { for _, name := range []string{"url", "content_type"} {
if _, ok := form.Config[name]; !ok { if _, ok := form.Config[name]; !ok {
ctx.Error(422, "", "Missing config option: "+name) c.Error(422, "", "Missing config option: "+name)
return return
} }
} }
if !models.IsValidHookContentType(form.Config["content_type"]) { if !models.IsValidHookContentType(form.Config["content_type"]) {
ctx.Error(422, "", "Invalid content type") c.Error(422, "", "Invalid content type")
return return
} }
@ -53,7 +53,7 @@ func CreateHook(ctx *context.APIContext, form api.CreateHookOption) {
form.Events = []string{"push"} form.Events = []string{"push"}
} }
w := &models.Webhook{ w := &models.Webhook{
RepoID: ctx.Repo.Repository.ID, RepoID: c.Repo.Repository.ID,
URL: form.Config["url"], URL: form.Config["url"],
ContentType: models.ToHookContentType(form.Config["content_type"]), ContentType: models.ToHookContentType(form.Config["content_type"]),
Secret: form.Config["secret"], Secret: form.Config["secret"],
@ -76,7 +76,7 @@ func CreateHook(ctx *context.APIContext, form api.CreateHookOption) {
if w.HookTaskType == models.SLACK { if w.HookTaskType == models.SLACK {
channel, ok := form.Config["channel"] channel, ok := form.Config["channel"]
if !ok { if !ok {
ctx.Error(422, "", "Missing config option: channel") c.Error(422, "", "Missing config option: channel")
return return
} }
meta, err := json.Marshal(&models.SlackMeta{ meta, err := json.Marshal(&models.SlackMeta{
@ -86,31 +86,31 @@ func CreateHook(ctx *context.APIContext, form api.CreateHookOption) {
Color: form.Config["color"], Color: form.Config["color"],
}) })
if err != nil { if err != nil {
ctx.Error(500, "slack: JSON marshal failed", err) c.Error(500, "slack: JSON marshal failed", err)
return return
} }
w.Meta = string(meta) w.Meta = string(meta)
} }
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Error(500, "UpdateEvent", err) c.Error(500, "UpdateEvent", err)
return return
} else if err := models.CreateWebhook(w); err != nil { } else if err := models.CreateWebhook(w); err != nil {
ctx.Error(500, "CreateWebhook", err) c.Error(500, "CreateWebhook", err)
return 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 // https://github.com/gogits/go-gogs-client/wiki/Repositories#edit-a-hook
func EditHook(ctx *context.APIContext, form api.EditHookOption) { func EditHook(c *context.APIContext, form api.EditHookOption) {
w, err := models.GetWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) w, err := models.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
if err != nil { if err != nil {
if errors.IsWebhookNotExist(err) { if errors.IsWebhookNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetWebhookOfRepoByID", err) c.Error(500, "GetWebhookOfRepoByID", err)
} }
return return
} }
@ -121,7 +121,7 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) {
} }
if ct, ok := form.Config["content_type"]; ok { if ct, ok := form.Config["content_type"]; ok {
if !models.IsValidHookContentType(ct) { if !models.IsValidHookContentType(ct) {
ctx.Error(422, "", "Invalid content type") c.Error(422, "", "Invalid content type")
return return
} }
w.ContentType = models.ToHookContentType(ct) w.ContentType = models.ToHookContentType(ct)
@ -136,7 +136,7 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) {
Color: form.Config["color"], Color: form.Config["color"],
}) })
if err != nil { if err != nil {
ctx.Error(500, "slack: JSON marshal failed", err) c.Error(500, "slack: JSON marshal failed", err)
return return
} }
w.Meta = string(meta) 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.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PULL_REQUEST))
w.Release = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_RELEASE)) w.Release = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_RELEASE))
if err = w.UpdateEvent(); err != nil { if err = w.UpdateEvent(); err != nil {
ctx.Error(500, "UpdateEvent", err) c.Error(500, "UpdateEvent", err)
return return
} }
@ -169,18 +169,18 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) {
} }
if err := models.UpdateWebhook(w); err != nil { if err := models.UpdateWebhook(w); err != nil {
ctx.Error(500, "UpdateWebhook", err) c.Error(500, "UpdateWebhook", err)
return return
} }
ctx.JSON(200, convert.ToHook(ctx.Repo.RepoLink, w)) c.JSON(200, convert.ToHook(c.Repo.RepoLink, w))
} }
func DeleteHook(ctx *context.APIContext) { func DeleteHook(c *context.APIContext) {
if err := models.DeleteWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { if err := models.DeleteWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil {
ctx.Error(500, "DeleteWebhookByRepoID", err) c.Error(500, "DeleteWebhookByRepoID", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

100
routers/api/v1/repo/issue.go

@ -16,16 +16,16 @@ import (
"github.com/gogits/gogs/pkg/setting" "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) issues, err := models.Issues(opts)
if err != nil { if err != nil {
ctx.Error(500, "Issues", err) c.Error(500, "Issues", err)
return return
} }
count, err := models.IssuesCount(opts) count, err := models.IssuesCount(opts)
if err != nil { if err != nil {
ctx.Error(500, "IssuesCount", err) c.Error(500, "IssuesCount", err)
return return
} }
@ -33,64 +33,64 @@ func listIssues(ctx *context.APIContext, opts *models.IssuesOptions) {
apiIssues := make([]*api.Issue, len(issues)) apiIssues := make([]*api.Issue, len(issues))
for i := range issues { for i := range issues {
if err = issues[i].LoadAttributes(); err != nil { if err = issues[i].LoadAttributes(); err != nil {
ctx.Error(500, "LoadAttributes", err) c.Error(500, "LoadAttributes", err)
return return
} }
apiIssues[i] = issues[i].APIFormat() apiIssues[i] = issues[i].APIFormat()
} }
ctx.SetLinkHeader(int(count), setting.UI.IssuePagingNum) c.SetLinkHeader(int(count), setting.UI.IssuePagingNum)
ctx.JSON(200, &apiIssues) c.JSON(200, &apiIssues)
} }
func ListUserIssues(ctx *context.APIContext) { func ListUserIssues(c *context.APIContext) {
opts := models.IssuesOptions{ opts := models.IssuesOptions{
AssigneeID: ctx.User.ID, AssigneeID: c.User.ID,
Page: ctx.QueryInt("page"), Page: c.QueryInt("page"),
} }
listIssues(ctx, &opts) listIssues(c, &opts)
} }
func ListIssues(ctx *context.APIContext) { func ListIssues(c *context.APIContext) {
opts := models.IssuesOptions{ opts := models.IssuesOptions{
RepoID: ctx.Repo.Repository.ID, RepoID: c.Repo.Repository.ID,
Page: ctx.QueryInt("page"), Page: c.QueryInt("page"),
} }
listIssues(ctx, &opts) listIssues(c, &opts)
} }
func GetIssue(ctx *context.APIContext) { func GetIssue(c *context.APIContext) {
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 err != nil {
if errors.IsIssueNotExist(err) { if errors.IsIssueNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetIssueByIndex", err) c.Error(500, "GetIssueByIndex", err)
} }
return 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{ issue := &models.Issue{
RepoID: ctx.Repo.Repository.ID, RepoID: c.Repo.Repository.ID,
Title: form.Title, Title: form.Title,
PosterID: ctx.User.ID, PosterID: c.User.ID,
Poster: ctx.User, Poster: c.User,
Content: form.Body, Content: form.Body,
} }
if ctx.Repo.IsWriter() { if c.Repo.IsWriter() {
if len(form.Assignee) > 0 { if len(form.Assignee) > 0 {
assignee, err := models.GetUserByName(form.Assignee) assignee, err := models.GetUserByName(form.Assignee)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { 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 { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return return
} }
@ -101,14 +101,14 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) {
form.Labels = nil form.Labels = nil
} }
if err := models.NewIssue(ctx.Repo.Repository, issue, form.Labels, nil); err != nil { if err := models.NewIssue(c.Repo.Repository, issue, form.Labels, nil); err != nil {
ctx.Error(500, "NewIssue", err) c.Error(500, "NewIssue", err)
return return
} }
if form.Closed { if form.Closed {
if err := issue.ChangeStatus(ctx.User, ctx.Repo.Repository, true); err != nil { if err := issue.ChangeStatus(c.User, c.Repo.Repository, true); err != nil {
ctx.Error(500, "ChangeStatus", err) c.Error(500, "ChangeStatus", err)
return return
} }
} }
@ -117,25 +117,25 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) {
var err error var err error
issue, err = models.GetIssueByID(issue.ID) issue, err = models.GetIssueByID(issue.ID)
if err != nil { if err != nil {
ctx.Error(500, "GetIssueByID", err) c.Error(500, "GetIssueByID", err)
return return
} }
ctx.JSON(201, issue.APIFormat()) c.JSON(201, issue.APIFormat())
} }
func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { func EditIssue(c *context.APIContext, form api.EditIssueOption) {
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 err != nil {
if errors.IsIssueNotExist(err) { if errors.IsIssueNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetIssueByIndex", err) c.Error(500, "GetIssueByIndex", err)
} }
return return
} }
if !issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter() { if !issue.IsPoster(c.User.ID) && !c.Repo.IsWriter() {
ctx.Status(403) c.Status(403)
return return
} }
@ -146,7 +146,7 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) {
issue.Content = *form.Body 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)) { (issue.Assignee == nil || issue.Assignee.LowerName != strings.ToLower(*form.Assignee)) {
if len(*form.Assignee) == 0 { if len(*form.Assignee) == 0 {
issue.AssigneeID = 0 issue.AssigneeID = 0
@ -154,9 +154,9 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) {
assignee, err := models.GetUserByName(*form.Assignee) assignee, err := models.GetUserByName(*form.Assignee)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { 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 { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return return
} }
@ -164,27 +164,27 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) {
} }
if err = models.UpdateIssueUserByAssignee(issue); err != nil { if err = models.UpdateIssueUserByAssignee(issue); err != nil {
ctx.Error(500, "UpdateIssueUserByAssignee", err) c.Error(500, "UpdateIssueUserByAssignee", err)
return return
} }
} }
if ctx.Repo.IsWriter() && form.Milestone != nil && if c.Repo.IsWriter() && form.Milestone != nil &&
issue.MilestoneID != *form.Milestone { issue.MilestoneID != *form.Milestone {
oldMilestoneID := issue.MilestoneID oldMilestoneID := issue.MilestoneID
issue.MilestoneID = *form.Milestone issue.MilestoneID = *form.Milestone
if err = models.ChangeMilestoneAssign(ctx.User, issue, oldMilestoneID); err != nil { if err = models.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil {
ctx.Error(500, "ChangeMilestoneAssign", err) c.Error(500, "ChangeMilestoneAssign", err)
return return
} }
} }
if err = models.UpdateIssue(issue); err != nil { if err = models.UpdateIssue(issue); err != nil {
ctx.Error(500, "UpdateIssue", err) c.Error(500, "UpdateIssue", err)
return return
} }
if form.State != nil { if form.State != nil {
if err = issue.ChangeStatus(ctx.User, ctx.Repo.Repository, api.STATE_CLOSED == api.StateType(*form.State)); err != nil { if err = issue.ChangeStatus(c.User, c.Repo.Repository, api.STATE_CLOSED == api.StateType(*form.State)); err != nil {
ctx.Error(500, "ChangeStatus", err) c.Error(500, "ChangeStatus", err)
return return
} }
} }
@ -192,8 +192,8 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) {
// Refetch from database to assign some automatic values // Refetch from database to assign some automatic values
issue, err = models.GetIssueByID(issue.ID) issue, err = models.GetIssueByID(issue.ID)
if err != nil { if err != nil {
ctx.Error(500, "GetIssueByID", err) c.Error(500, "GetIssueByID", err)
return return
} }
ctx.JSON(201, issue.APIFormat()) c.JSON(201, issue.APIFormat())
} }

78
routers/api/v1/repo/issue_comment.go

@ -12,22 +12,22 @@ import (
"github.com/gogits/gogs/pkg/context" "github.com/gogits/gogs/pkg/context"
) )
func ListIssueComments(ctx *context.APIContext) { func ListIssueComments(c *context.APIContext) {
var since time.Time var since time.Time
if len(ctx.Query("since")) > 0 { if len(c.Query("since")) > 0 {
since, _ = time.Parse(time.RFC3339, ctx.Query("since")) since, _ = time.Parse(time.RFC3339, c.Query("since"))
} }
// comments,err:=models.GetCommentsByIssueIDSince(, 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 { if err != nil {
ctx.Error(500, "GetRawIssueByIndex", err) c.Error(500, "GetRawIssueByIndex", err)
return return
} }
comments, err := models.GetCommentsByIssueIDSince(issue.ID, since.Unix()) comments, err := models.GetCommentsByIssueIDSince(issue.ID, since.Unix())
if err != nil { if err != nil {
ctx.Error(500, "GetCommentsByIssueIDSince", err) c.Error(500, "GetCommentsByIssueIDSince", err)
return return
} }
@ -35,18 +35,18 @@ func ListIssueComments(ctx *context.APIContext) {
for i := range comments { for i := range comments {
apiComments[i] = comments[i].APIFormat() 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 var since time.Time
if len(ctx.Query("since")) > 0 { if len(c.Query("since")) > 0 {
since, _ = time.Parse(time.RFC3339, ctx.Query("since")) 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 { if err != nil {
ctx.Error(500, "GetCommentsByRepoIDSince", err) c.Error(500, "GetCommentsByRepoIDSince", err)
return return
} }
@ -54,75 +54,75 @@ func ListRepoIssueComments(ctx *context.APIContext) {
for i := range comments { for i := range comments {
apiComments[i] = comments[i].APIFormat() apiComments[i] = comments[i].APIFormat()
} }
ctx.JSON(200, &apiComments) c.JSON(200, &apiComments)
} }
func CreateIssueComment(ctx *context.APIContext, form api.CreateIssueCommentOption) { func CreateIssueComment(c *context.APIContext, form api.CreateIssueCommentOption) {
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 err != nil {
ctx.Error(500, "GetIssueByIndex", err) c.Error(500, "GetIssueByIndex", err)
return 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 { if err != nil {
ctx.Error(500, "CreateIssueComment", err) c.Error(500, "CreateIssueComment", err)
return return
} }
ctx.JSON(201, comment.APIFormat()) c.JSON(201, comment.APIFormat())
} }
func EditIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) { func EditIssueComment(c *context.APIContext, form api.EditIssueCommentOption) {
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) comment, err := models.GetCommentByID(c.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrCommentNotExist(err) { if models.IsErrCommentNotExist(err) {
ctx.Error(404, "GetCommentByID", err) c.Error(404, "GetCommentByID", err)
} else { } else {
ctx.Error(500, "GetCommentByID", err) c.Error(500, "GetCommentByID", err)
} }
return return
} }
if ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin() { if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() {
ctx.Status(403) c.Status(403)
return return
} else if comment.Type != models.COMMENT_TYPE_COMMENT { } else if comment.Type != models.COMMENT_TYPE_COMMENT {
ctx.Status(204) c.Status(204)
return return
} }
oldContent := comment.Content oldContent := comment.Content
comment.Content = form.Body comment.Content = form.Body
if err := models.UpdateComment(ctx.User, comment, oldContent); err != nil { if err := models.UpdateComment(c.User, comment, oldContent); err != nil {
ctx.Error(500, "UpdateComment", err) c.Error(500, "UpdateComment", err)
return return
} }
ctx.JSON(200, comment.APIFormat()) c.JSON(200, comment.APIFormat())
} }
func DeleteIssueComment(ctx *context.APIContext) { func DeleteIssueComment(c *context.APIContext) {
comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) comment, err := models.GetCommentByID(c.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrCommentNotExist(err) { if models.IsErrCommentNotExist(err) {
ctx.Error(404, "GetCommentByID", err) c.Error(404, "GetCommentByID", err)
} else { } else {
ctx.Error(500, "GetCommentByID", err) c.Error(500, "GetCommentByID", err)
} }
return return
} }
if ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin() { if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() {
ctx.Status(403) c.Status(403)
return return
} else if comment.Type != models.COMMENT_TYPE_COMMENT { } else if comment.Type != models.COMMENT_TYPE_COMMENT {
ctx.Status(204) c.Status(204)
return return
} }
if err = models.DeleteCommentByID(ctx.User, comment.ID); err != nil { if err = models.DeleteCommentByID(c.User, comment.ID); err != nil {
ctx.Error(500, "DeleteCommentByID", err) c.Error(500, "DeleteCommentByID", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

96
routers/api/v1/repo/issue_label.go

@ -12,13 +12,13 @@ import (
"github.com/gogits/gogs/pkg/context" "github.com/gogits/gogs/pkg/context"
) )
func ListIssueLabels(ctx *context.APIContext) { func ListIssueLabels(c *context.APIContext) {
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 err != nil {
if errors.IsIssueNotExist(err) { if errors.IsIssueNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetIssueByIndex", err) c.Error(500, "GetIssueByIndex", err)
} }
return return
} }
@ -27,39 +27,39 @@ func ListIssueLabels(ctx *context.APIContext) {
for i := range issue.Labels { for i := range issue.Labels {
apiLabels[i] = issue.Labels[i].APIFormat() apiLabels[i] = issue.Labels[i].APIFormat()
} }
ctx.JSON(200, &apiLabels) c.JSON(200, &apiLabels)
} }
func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { func AddIssueLabels(c *context.APIContext, form api.IssueLabelsOption) {
if !ctx.Repo.IsWriter() { if !c.Repo.IsWriter() {
ctx.Status(403) c.Status(403)
return 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 err != nil {
if errors.IsIssueNotExist(err) { if errors.IsIssueNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetIssueByIndex", err) c.Error(500, "GetIssueByIndex", err)
} }
return return
} }
labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) labels, err := models.GetLabelsInRepoByIDs(c.Repo.Repository.ID, form.Labels)
if err != nil { if err != nil {
ctx.Error(500, "GetLabelsInRepoByIDs", err) c.Error(500, "GetLabelsInRepoByIDs", err)
return return
} }
if err = issue.AddLabels(ctx.User, labels); err != nil { if err = issue.AddLabels(c.User, labels); err != nil {
ctx.Error(500, "AddLabels", err) c.Error(500, "AddLabels", err)
return return
} }
labels, err = models.GetLabelsByIssueID(issue.ID) labels, err = models.GetLabelsByIssueID(issue.ID)
if err != nil { if err != nil {
ctx.Error(500, "GetLabelsByIssueID", err) c.Error(500, "GetLabelsByIssueID", err)
return return
} }
@ -67,73 +67,73 @@ func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) {
for i := range labels { for i := range labels {
apiLabels[i] = issue.Labels[i].APIFormat() apiLabels[i] = issue.Labels[i].APIFormat()
} }
ctx.JSON(200, &apiLabels) c.JSON(200, &apiLabels)
} }
func DeleteIssueLabel(ctx *context.APIContext) { func DeleteIssueLabel(c *context.APIContext) {
if !ctx.Repo.IsWriter() { if !c.Repo.IsWriter() {
ctx.Status(403) c.Status(403)
return 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 err != nil {
if errors.IsIssueNotExist(err) { if errors.IsIssueNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetIssueByIndex", err) c.Error(500, "GetIssueByIndex", err)
} }
return 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 err != nil {
if models.IsErrLabelNotExist(err) { if models.IsErrLabelNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetLabelInRepoByID", err) c.Error(500, "GetLabelInRepoByID", err)
} }
return return
} }
if err := models.DeleteIssueLabel(issue, label); err != nil { if err := models.DeleteIssueLabel(issue, label); err != nil {
ctx.Error(500, "DeleteIssueLabel", err) c.Error(500, "DeleteIssueLabel", err)
return return
} }
ctx.Status(204) c.Status(204)
} }
func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { func ReplaceIssueLabels(c *context.APIContext, form api.IssueLabelsOption) {
if !ctx.Repo.IsWriter() { if !c.Repo.IsWriter() {
ctx.Status(403) c.Status(403)
return 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 err != nil {
if errors.IsIssueNotExist(err) { if errors.IsIssueNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetIssueByIndex", err) c.Error(500, "GetIssueByIndex", err)
} }
return return
} }
labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) labels, err := models.GetLabelsInRepoByIDs(c.Repo.Repository.ID, form.Labels)
if err != nil { if err != nil {
ctx.Error(500, "GetLabelsInRepoByIDs", err) c.Error(500, "GetLabelsInRepoByIDs", err)
return return
} }
if err := issue.ReplaceLabels(labels); err != nil { if err := issue.ReplaceLabels(labels); err != nil {
ctx.Error(500, "ReplaceLabels", err) c.Error(500, "ReplaceLabels", err)
return return
} }
labels, err = models.GetLabelsByIssueID(issue.ID) labels, err = models.GetLabelsByIssueID(issue.ID)
if err != nil { if err != nil {
ctx.Error(500, "GetLabelsByIssueID", err) c.Error(500, "GetLabelsByIssueID", err)
return return
} }
@ -141,29 +141,29 @@ func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) {
for i := range labels { for i := range labels {
apiLabels[i] = issue.Labels[i].APIFormat() apiLabels[i] = issue.Labels[i].APIFormat()
} }
ctx.JSON(200, &apiLabels) c.JSON(200, &apiLabels)
} }
func ClearIssueLabels(ctx *context.APIContext) { func ClearIssueLabels(c *context.APIContext) {
if !ctx.Repo.IsWriter() { if !c.Repo.IsWriter() {
ctx.Status(403) c.Status(403)
return 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 err != nil {
if errors.IsIssueNotExist(err) { if errors.IsIssueNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetIssueByIndex", err) c.Error(500, "GetIssueByIndex", err)
} }
return return
} }
if err := issue.ClearLabels(ctx.User); err != nil { if err := issue.ClearLabels(c.User); err != nil {
ctx.Error(500, "ClearLabels", err) c.Error(500, "ClearLabels", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

62
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 // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#list-deploy-keys
func ListDeployKeys(ctx *context.APIContext) { func ListDeployKeys(c *context.APIContext) {
keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) keys, err := models.ListDeployKeys(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Error(500, "ListDeployKeys", err) c.Error(500, "ListDeployKeys", err)
return 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)) apiKeys := make([]*api.DeployKey, len(keys))
for i := range keys { for i := range keys {
if err = keys[i].GetContent(); err != nil { if err = keys[i].GetContent(); err != nil {
ctx.Error(500, "GetContent", err) c.Error(500, "GetContent", err)
return return
} }
apiKeys[i] = convert.ToDeployKey(apiLink, keys[i]) 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 // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#get-a-deploy-key
func GetDeployKey(ctx *context.APIContext) { func GetDeployKey(c *context.APIContext) {
key, err := models.GetDeployKeyByID(ctx.ParamsInt64(":id")) key, err := models.GetDeployKeyByID(c.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrDeployKeyNotExist(err) { if models.IsErrDeployKeyNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetDeployKeyByID", err) c.Error(500, "GetDeployKeyByID", err)
} }
return return
} }
if err = key.GetContent(); err != nil { if err = key.GetContent(); err != nil {
ctx.Error(500, "GetContent", err) c.Error(500, "GetContent", err)
return return
} }
apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name) apiLink := composeDeployKeysAPILink(c.Repo.Owner.Name + "/" + c.Repo.Repository.Name)
ctx.JSON(200, convert.ToDeployKey(apiLink, key)) 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) { if models.IsErrKeyUnableVerify(err) {
ctx.Error(422, "", "Unable to verify key content") c.Error(422, "", "Unable to verify key content")
} else { } 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 { switch {
case models.IsErrKeyAlreadyExist(err): 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): case models.IsErrKeyNameAlreadyUsed(err):
ctx.Error(422, "", "Key title has been used") c.Error(422, "", "Key title has been used")
default: 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 // 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) content, err := models.CheckPublicKeyString(form.Key)
if err != nil { if err != nil {
HandleCheckKeyStringError(ctx, err) HandleCheckKeyStringError(c, err)
return 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 { if err != nil {
HandleAddKeyError(ctx, err) HandleAddKeyError(c, err)
return return
} }
key.Content = content key.Content = content
apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name) apiLink := composeDeployKeysAPILink(c.Repo.Owner.Name + "/" + c.Repo.Repository.Name)
ctx.JSON(201, convert.ToDeployKey(apiLink, key)) c.JSON(201, convert.ToDeployKey(apiLink, key))
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key
func DeleteDeploykey(ctx *context.APIContext) { func DeleteDeploykey(c *context.APIContext) {
if err := models.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if err := models.DeleteDeployKey(c.User, c.ParamsInt64(":id")); err != nil {
if models.IsErrKeyAccessDenied(err) { 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 { } else {
ctx.Error(500, "DeleteDeployKey", err) c.Error(500, "DeleteDeployKey", err)
} }
return return
} }
ctx.Status(204) c.Status(204)
} }

58
routers/api/v1/repo/label.go

@ -11,10 +11,10 @@ import (
"github.com/gogits/gogs/pkg/context" "github.com/gogits/gogs/pkg/context"
) )
func ListLabels(ctx *context.APIContext) { func ListLabels(c *context.APIContext) {
labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID) labels, err := models.GetLabelsByRepoID(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Error(500, "GetLabelsByRepoID", err) c.Error(500, "GetLabelsByRepoID", err)
return return
} }
@ -22,53 +22,53 @@ func ListLabels(ctx *context.APIContext) {
for i := range labels { for i := range labels {
apiLabels[i] = labels[i].APIFormat() apiLabels[i] = labels[i].APIFormat()
} }
ctx.JSON(200, &apiLabels) c.JSON(200, &apiLabels)
} }
func GetLabel(ctx *context.APIContext) { func GetLabel(c *context.APIContext) {
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 err != nil {
if models.IsErrLabelNotExist(err) { if models.IsErrLabelNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetLabelByRepoID", err) c.Error(500, "GetLabelByRepoID", err)
} }
return return
} }
ctx.JSON(200, label.APIFormat()) c.JSON(200, label.APIFormat())
} }
func CreateLabel(ctx *context.APIContext, form api.CreateLabelOption) { func CreateLabel(c *context.APIContext, form api.CreateLabelOption) {
if !ctx.Repo.IsWriter() { if !c.Repo.IsWriter() {
ctx.Status(403) c.Status(403)
return return
} }
label := &models.Label{ label := &models.Label{
Name: form.Name, Name: form.Name,
Color: form.Color, Color: form.Color,
RepoID: ctx.Repo.Repository.ID, RepoID: c.Repo.Repository.ID,
} }
if err := models.NewLabels(label); err != nil { if err := models.NewLabels(label); err != nil {
ctx.Error(500, "NewLabel", err) c.Error(500, "NewLabel", err)
return return
} }
ctx.JSON(201, label.APIFormat()) c.JSON(201, label.APIFormat())
} }
func EditLabel(ctx *context.APIContext, form api.EditLabelOption) { func EditLabel(c *context.APIContext, form api.EditLabelOption) {
if !ctx.Repo.IsWriter() { if !c.Repo.IsWriter() {
ctx.Status(403) c.Status(403)
return 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 err != nil {
if models.IsErrLabelNotExist(err) { if models.IsErrLabelNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetLabelByRepoID", err) c.Error(500, "GetLabelByRepoID", err)
} }
return return
} }
@ -80,22 +80,22 @@ func EditLabel(ctx *context.APIContext, form api.EditLabelOption) {
label.Color = *form.Color label.Color = *form.Color
} }
if err := models.UpdateLabel(label); err != nil { if err := models.UpdateLabel(label); err != nil {
ctx.Handle(500, "UpdateLabel", err) c.Handle(500, "UpdateLabel", err)
return return
} }
ctx.JSON(200, label.APIFormat()) c.JSON(200, label.APIFormat())
} }
func DeleteLabel(ctx *context.APIContext) { func DeleteLabel(c *context.APIContext) {
if !ctx.Repo.IsWriter() { if !c.Repo.IsWriter() {
ctx.Status(403) c.Status(403)
return return
} }
if err := models.DeleteLabel(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { if err := models.DeleteLabel(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil {
ctx.Error(500, "DeleteLabel", err) c.Error(500, "DeleteLabel", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

48
routers/api/v1/repo/milestone.go

@ -13,10 +13,10 @@ import (
"github.com/gogits/gogs/pkg/context" "github.com/gogits/gogs/pkg/context"
) )
func ListMilestones(ctx *context.APIContext) { func ListMilestones(c *context.APIContext) {
milestones, err := models.GetMilestonesByRepoID(ctx.Repo.Repository.ID) milestones, err := models.GetMilestonesByRepoID(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Error(500, "GetMilestonesByRepoID", err) c.Error(500, "GetMilestonesByRepoID", err)
return return
} }
@ -24,49 +24,49 @@ func ListMilestones(ctx *context.APIContext) {
for i := range milestones { for i := range milestones {
apiMilestones[i] = milestones[i].APIFormat() apiMilestones[i] = milestones[i].APIFormat()
} }
ctx.JSON(200, &apiMilestones) c.JSON(200, &apiMilestones)
} }
func GetMilestone(ctx *context.APIContext) { func GetMilestone(c *context.APIContext) {
milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) milestone, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrMilestoneNotExist(err) { if models.IsErrMilestoneNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetMilestoneByRepoID", err) c.Error(500, "GetMilestoneByRepoID", err)
} }
return 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 { if form.Deadline == nil {
defaultDeadline, _ := time.ParseInLocation("2006-01-02", "9999-12-31", time.Local) defaultDeadline, _ := time.ParseInLocation("2006-01-02", "9999-12-31", time.Local)
form.Deadline = &defaultDeadline form.Deadline = &defaultDeadline
} }
milestone := &models.Milestone{ milestone := &models.Milestone{
RepoID: ctx.Repo.Repository.ID, RepoID: c.Repo.Repository.ID,
Name: form.Title, Name: form.Title,
Content: form.Description, Content: form.Description,
Deadline: *form.Deadline, Deadline: *form.Deadline,
} }
if err := models.NewMilestone(milestone); err != nil { if err := models.NewMilestone(milestone); err != nil {
ctx.Error(500, "NewMilestone", err) c.Error(500, "NewMilestone", err)
return return
} }
ctx.JSON(201, milestone.APIFormat()) c.JSON(201, milestone.APIFormat())
} }
func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) { func EditMilestone(c *context.APIContext, form api.EditMilestoneOption) {
milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) milestone, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrMilestoneNotExist(err) { if models.IsErrMilestoneNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetMilestoneByRepoID", err) c.Error(500, "GetMilestoneByRepoID", err)
} }
return return
} }
@ -83,21 +83,21 @@ func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) {
if form.State != nil { if form.State != nil {
if err = milestone.ChangeStatus(api.STATE_CLOSED == api.StateType(*form.State)); err != 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 return
} }
} else if err = models.UpdateMilestone(milestone); err != nil { } else if err = models.UpdateMilestone(milestone); err != nil {
ctx.Handle(500, "UpdateMilestone", err) c.Handle(500, "UpdateMilestone", err)
return return
} }
ctx.JSON(200, milestone.APIFormat()) c.JSON(200, milestone.APIFormat())
} }
func DeleteMilestone(ctx *context.APIContext) { func DeleteMilestone(c *context.APIContext) {
if err := models.DeleteMilestoneOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { if err := models.DeleteMilestoneOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil {
ctx.Error(500, "DeleteMilestoneByRepoID", err) c.Error(500, "DeleteMilestoneByRepoID", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

192
routers/api/v1/repo/repo.go

@ -20,27 +20,27 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories // https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories
func Search(ctx *context.APIContext) { func Search(c *context.APIContext) {
opts := &models.SearchRepoOptions{ opts := &models.SearchRepoOptions{
Keyword: path.Base(ctx.Query("q")), Keyword: path.Base(c.Query("q")),
OwnerID: ctx.QueryInt64("uid"), OwnerID: c.QueryInt64("uid"),
PageSize: convert.ToCorrectPageSize(ctx.QueryInt("limit")), PageSize: convert.ToCorrectPageSize(c.QueryInt("limit")),
} }
// Check visibility. // Check visibility.
if ctx.IsLogged && opts.OwnerID > 0 { if c.IsLogged && opts.OwnerID > 0 {
if ctx.User.ID == opts.OwnerID { if c.User.ID == opts.OwnerID {
opts.Private = true opts.Private = true
} else { } else {
u, err := models.GetUserByID(opts.OwnerID) u, err := models.GetUserByID(opts.OwnerID)
if err != nil { if err != nil {
ctx.JSON(500, map[string]interface{}{ c.JSON(500, map[string]interface{}{
"ok": false, "ok": false,
"error": err.Error(), "error": err.Error(),
}) })
return return
} }
if u.IsOrganization() && u.IsOwnedBy(ctx.User.ID) { if u.IsOrganization() && u.IsOwnedBy(c.User.ID) {
opts.Private = true opts.Private = true
} }
// FIXME: how about collaborators? // FIXME: how about collaborators?
@ -49,7 +49,7 @@ func Search(ctx *context.APIContext) {
repos, count, err := models.SearchRepositoryByName(opts) repos, count, err := models.SearchRepositoryByName(opts)
if err != nil { if err != nil {
ctx.JSON(500, map[string]interface{}{ c.JSON(500, map[string]interface{}{
"ok": false, "ok": false,
"error": err.Error(), "error": err.Error(),
}) })
@ -59,7 +59,7 @@ func Search(ctx *context.APIContext) {
results := make([]*api.Repository, len(repos)) results := make([]*api.Repository, len(repos))
for i := range repos { for i := range repos {
if err = repos[i].GetOwner(); err != nil { if err = repos[i].GetOwner(); err != nil {
ctx.JSON(500, map[string]interface{}{ c.JSON(500, map[string]interface{}{
"ok": false, "ok": false,
"error": err.Error(), "error": err.Error(),
}) })
@ -71,17 +71,17 @@ func Search(ctx *context.APIContext) {
} }
} }
ctx.SetLinkHeader(int(count), setting.API.MaxResponseItems) c.SetLinkHeader(int(count), setting.API.MaxResponseItems)
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"ok": true, "ok": true,
"data": results, "data": results,
}) })
} }
func listUserRepositories(ctx *context.APIContext, username string) { func listUserRepositories(c *context.APIContext, username string) {
user, err := models.GetUserByName(username) user, err := models.GetUserByName(username)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return return
} }
@ -89,32 +89,32 @@ func listUserRepositories(ctx *context.APIContext, username string) {
// or an organization isn't a member of. // or an organization isn't a member of.
var ownRepos []*models.Repository var ownRepos []*models.Repository
if user.IsOrganization() { if user.IsOrganization() {
ownRepos, _, err = user.GetUserRepositories(ctx.User.ID, 1, user.NumRepos) ownRepos, _, err = user.GetUserRepositories(c.User.ID, 1, user.NumRepos)
} else { } else {
ownRepos, err = models.GetUserRepositories(&models.UserRepoOptions{ ownRepos, err = models.GetUserRepositories(&models.UserRepoOptions{
UserID: user.ID, UserID: user.ID,
Private: ctx.User.ID == user.ID, Private: c.User.ID == user.ID,
Page: 1, Page: 1,
PageSize: user.NumRepos, PageSize: user.NumRepos,
}) })
} }
if err != nil { if err != nil {
ctx.Error(500, "GetUserRepositories", err) c.Error(500, "GetUserRepositories", err)
return return
} }
if ctx.User.ID != user.ID { if c.User.ID != user.ID {
repos := make([]*api.Repository, len(ownRepos)) repos := make([]*api.Repository, len(ownRepos))
for i := range ownRepos { for i := range ownRepos {
repos[i] = ownRepos[i].APIFormat(&api.Permission{true, true, true}) repos[i] = ownRepos[i].APIFormat(&api.Permission{true, true, true})
} }
ctx.JSON(200, &repos) c.JSON(200, &repos)
return return
} }
accessibleRepos, err := user.GetRepositoryAccesses() accessibleRepos, err := user.GetRepositoryAccesses()
if err != nil { if err != nil {
ctx.Error(500, "GetRepositoryAccesses", err) c.Error(500, "GetRepositoryAccesses", err)
return return
} }
@ -134,23 +134,23 @@ func listUserRepositories(ctx *context.APIContext, username string) {
i++ i++
} }
ctx.JSON(200, &repos) c.JSON(200, &repos)
} }
func ListMyRepos(ctx *context.APIContext) { func ListMyRepos(c *context.APIContext) {
listUserRepositories(ctx, ctx.User.Name) listUserRepositories(c, c.User.Name)
} }
func ListUserRepositories(ctx *context.APIContext) { func ListUserRepositories(c *context.APIContext) {
listUserRepositories(ctx, ctx.Params(":username")) listUserRepositories(c, c.Params(":username"))
} }
func ListOrgRepositories(ctx *context.APIContext) { func ListOrgRepositories(c *context.APIContext) {
listUserRepositories(ctx, ctx.Params(":org")) listUserRepositories(c, c.Params(":org"))
} }
func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateRepoOption) { func CreateUserRepo(c *context.APIContext, owner *models.User, opt api.CreateRepoOption) {
repo, err := models.CreateRepository(ctx.User, owner, models.CreateRepoOptions{ repo, err := models.CreateRepository(c.User, owner, models.CreateRepoOptions{
Name: opt.Name, Name: opt.Name,
Description: opt.Description, Description: opt.Description,
Gitignores: opt.Gitignores, Gitignores: opt.Gitignores,
@ -163,104 +163,104 @@ func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateR
if models.IsErrRepoAlreadyExist(err) || if models.IsErrRepoAlreadyExist(err) ||
models.IsErrNameReserved(err) || models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) { models.IsErrNamePatternNotAllowed(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
if repo != nil { 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) log.Error(2, "DeleteRepository: %v", err)
} }
} }
ctx.Error(500, "CreateRepository", err) c.Error(500, "CreateRepository", err)
} }
return 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 // 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. // Shouldn't reach this condition, but just in case.
if ctx.User.IsOrganization() { if c.User.IsOrganization() {
ctx.Error(422, "", "not allowed creating repository for organization") c.Error(422, "", "not allowed creating repository for organization")
return return
} }
CreateUserRepo(ctx, ctx.User, opt) CreateUserRepo(c, c.User, opt)
} }
func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) { func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) {
org, err := models.GetOrgByName(ctx.Params(":org")) org, err := models.GetOrgByName(c.Params(":org"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetOrgByName", err) c.Error(500, "GetOrgByName", err)
} }
return return
} }
if !org.IsOwnedBy(ctx.User.ID) { if !org.IsOwnedBy(c.User.ID) {
ctx.Error(403, "", "Given user is not owner of organization.") c.Error(403, "", "Given user is not owner of organization.")
return return
} }
CreateUserRepo(ctx, org, opt) CreateUserRepo(c, org, opt)
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate // https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate
func Migrate(ctx *context.APIContext, f form.MigrateRepo) { func Migrate(c *context.APIContext, f form.MigrateRepo) {
ctxUser := ctx.User ctxUser := c.User
// Not equal means context user is an organization, // Not equal means context user is an organization,
// or is another user/organization if current user is admin. // or is another user/organization if current user is admin.
if f.Uid != ctxUser.ID { if f.Uid != ctxUser.ID {
org, err := models.GetUserByID(f.Uid) org, err := models.GetUserByID(f.Uid)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetUserByID", err) c.Error(500, "GetUserByID", err)
} }
return return
} else if !org.IsOrganization() { } else if !org.IsOrganization() {
ctx.Error(403, "", "Given user is not an organization") c.Error(403, "", "Given user is not an organization")
return return
} }
ctxUser = org ctxUser = org
} }
if ctx.HasError() { if c.HasError() {
ctx.Error(422, "", ctx.GetErrMsg()) c.Error(422, "", c.GetErrMsg())
return return
} }
if ctxUser.IsOrganization() && !ctx.User.IsAdmin { if ctxUser.IsOrganization() && !c.User.IsAdmin {
// Check ownership of organization. // Check ownership of organization.
if !ctxUser.IsOwnedBy(ctx.User.ID) { if !ctxUser.IsOwnedBy(c.User.ID) {
ctx.Error(403, "", "Given user is not owner of organization") c.Error(403, "", "Given user is not owner of organization")
return return
} }
} }
remoteAddr, err := f.ParseRemoteAddr(ctx.User) remoteAddr, err := f.ParseRemoteAddr(c.User)
if err != nil { if err != nil {
if models.IsErrInvalidCloneAddr(err) { if models.IsErrInvalidCloneAddr(err) {
addrErr := err.(models.ErrInvalidCloneAddr) addrErr := err.(models.ErrInvalidCloneAddr)
switch { switch {
case addrErr.IsURLError: case addrErr.IsURLError:
ctx.Error(422, "", err) c.Error(422, "", err)
case addrErr.IsPermissionDenied: 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: 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: default:
ctx.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error()) c.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error())
} }
} else { } else {
ctx.Error(500, "ParseRemoteAddr", err) c.Error(500, "ParseRemoteAddr", err)
} }
return return
} }
repo, err := models.MigrateRepository(ctx.User, ctxUser, models.MigrateRepoOptions{ repo, err := models.MigrateRepository(c.User, ctxUser, models.MigrateRepoOptions{
Name: f.RepoName, Name: f.RepoName,
Description: f.Description, Description: f.Description,
IsPrivate: f.Private || setting.Repository.ForcePrivate, IsPrivate: f.Private || setting.Repository.ForcePrivate,
@ -275,34 +275,34 @@ func Migrate(ctx *context.APIContext, f form.MigrateRepo) {
} }
if errors.IsReachLimitOfRepo(err) { if errors.IsReachLimitOfRepo(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "MigrateRepository", models.HandleMirrorCredentials(err.Error(), true)) c.Error(500, "MigrateRepository", models.HandleMirrorCredentials(err.Error(), true))
} }
return return
} }
log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName) 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) { func parseOwnerAndRepo(c *context.APIContext) (*models.User, *models.Repository) {
owner, err := models.GetUserByName(ctx.Params(":username")) owner, err := models.GetUserByName(c.Params(":username"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Error(422, "", err) c.Error(422, "", err)
} else { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return nil, nil 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 err != nil {
if errors.IsRepoNotExist(err) { if errors.IsRepoNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetRepositoryByName", err) c.Error(500, "GetRepositoryByName", err)
} }
return nil, nil 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 // https://github.com/gogits/go-gogs-client/wiki/Repositories#get
func Get(ctx *context.APIContext) { func Get(c *context.APIContext) {
_, repo := parseOwnerAndRepo(ctx) _, repo := parseOwnerAndRepo(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.JSON(200, repo.APIFormat(&api.Permission{ c.JSON(200, repo.APIFormat(&api.Permission{
Admin: ctx.Repo.IsAdmin(), Admin: c.Repo.IsAdmin(),
Push: ctx.Repo.IsWriter(), Push: c.Repo.IsWriter(),
Pull: true, Pull: true,
})) }))
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#delete // https://github.com/gogits/go-gogs-client/wiki/Repositories#delete
func Delete(ctx *context.APIContext) { func Delete(c *context.APIContext) {
owner, repo := parseOwnerAndRepo(ctx) owner, repo := parseOwnerAndRepo(c)
if ctx.Written() { if c.Written() {
return return
} }
if owner.IsOrganization() && !owner.IsOwnedBy(ctx.User.ID) { if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) {
ctx.Error(403, "", "Given user is not owner of organization.") c.Error(403, "", "Given user is not owner of organization.")
return return
} }
if err := models.DeleteRepository(owner.ID, repo.ID); err != nil { if err := models.DeleteRepository(owner.ID, repo.ID); err != nil {
ctx.Error(500, "DeleteRepository", err) c.Error(500, "DeleteRepository", err)
return return
} }
log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name) log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
ctx.Status(204) c.Status(204)
} }
func ListForks(ctx *context.APIContext) { func ListForks(c *context.APIContext) {
forks, err := ctx.Repo.Repository.GetForks() forks, err := c.Repo.Repository.GetForks()
if err != nil { if err != nil {
ctx.Error(500, "GetForks", err) c.Error(500, "GetForks", err)
return return
} }
apiForks := make([]*api.Repository, len(forks)) apiForks := make([]*api.Repository, len(forks))
for i := range forks { for i := range forks {
if err := forks[i].GetOwner(); err != nil { if err := forks[i].GetOwner(); err != nil {
ctx.Error(500, "GetOwner", err) c.Error(500, "GetOwner", err)
return return
} }
apiForks[i] = forks[i].APIFormat(&api.Permission{ apiForks[i] = forks[i].APIFormat(&api.Permission{
Admin: ctx.User.IsAdminOfRepo(forks[i]), Admin: c.User.IsAdminOfRepo(forks[i]),
Push: ctx.User.IsWriterOfRepo(forks[i]), Push: c.User.IsWriterOfRepo(forks[i]),
Pull: true, Pull: true,
}) })
} }
ctx.JSON(200, &apiForks) c.JSON(200, &apiForks)
} }
func MirrorSync(ctx *context.APIContext) { func MirrorSync(c *context.APIContext) {
_, repo := parseOwnerAndRepo(ctx) _, repo := parseOwnerAndRepo(c)
if ctx.Written() { if c.Written() {
return return
} else if !repo.IsMirror { } else if !repo.IsMirror {
ctx.Status(404) c.Status(404)
return return
} }
go models.MirrorQueue.Add(repo.ID) go models.MirrorQueue.Add(repo.ID)
ctx.Status(202) c.Status(202)
} }

16
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 // https://github.com/gogits/go-gogs-client/wiki/Users#list-access-tokens-for-a-user
func ListAccessTokens(ctx *context.APIContext) { func ListAccessTokens(c *context.APIContext) {
tokens, err := models.ListAccessTokens(ctx.User.ID) tokens, err := models.ListAccessTokens(c.User.ID)
if err != nil { if err != nil {
ctx.Error(500, "ListAccessTokens", err) c.Error(500, "ListAccessTokens", err)
return return
} }
@ -23,18 +23,18 @@ func ListAccessTokens(ctx *context.APIContext) {
for i := range tokens { for i := range tokens {
apiTokens[i] = &api.AccessToken{tokens[i].Name, tokens[i].Sha1} 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 // 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{ t := &models.AccessToken{
UID: ctx.User.ID, UID: c.User.ID,
Name: form.Name, Name: form.Name,
} }
if err := models.NewAccessToken(t); err != nil { if err := models.NewAccessToken(t); err != nil {
ctx.Error(500, "NewAccessToken", err) c.Error(500, "NewAccessToken", err)
return return
} }
ctx.JSON(201, &api.AccessToken{t.Name, t.Sha1}) c.JSON(201, &api.AccessToken{t.Name, t.Sha1})
} }

30
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 // https://github.com/gogits/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user
func ListEmails(ctx *context.APIContext) { func ListEmails(c *context.APIContext) {
emails, err := models.GetEmailAddresses(ctx.User.ID) emails, err := models.GetEmailAddresses(c.User.ID)
if err != nil { if err != nil {
ctx.Error(500, "GetEmailAddresses", err) c.Error(500, "GetEmailAddresses", err)
return return
} }
apiEmails := make([]*api.Email, len(emails)) apiEmails := make([]*api.Email, len(emails))
for i := range emails { for i := range emails {
apiEmails[i] = convert.ToEmail(emails[i]) 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 // 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 { if len(form.Emails) == 0 {
ctx.Status(422) c.Status(422)
return return
} }
emails := make([]*models.EmailAddress, len(form.Emails)) emails := make([]*models.EmailAddress, len(form.Emails))
for i := range form.Emails { for i := range form.Emails {
emails[i] = &models.EmailAddress{ emails[i] = &models.EmailAddress{
UID: ctx.User.ID, UID: c.User.ID,
Email: form.Emails[i], Email: form.Emails[i],
IsActivated: !setting.Service.RegisterEmailConfirm, IsActivated: !setting.Service.RegisterEmailConfirm,
} }
@ -45,9 +45,9 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) {
if err := models.AddEmailAddresses(emails); err != nil { if err := models.AddEmailAddresses(emails); err != nil {
if models.IsErrEmailAlreadyUsed(err) { 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 { } else {
ctx.Error(500, "AddEmailAddresses", err) c.Error(500, "AddEmailAddresses", err)
} }
return return
} }
@ -56,27 +56,27 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) {
for i := range emails { for i := range emails {
apiEmails[i] = convert.ToEmail(emails[i]) 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 // 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 { if len(form.Emails) == 0 {
ctx.Status(204) c.Status(204)
return return
} }
emails := make([]*models.EmailAddress, len(form.Emails)) emails := make([]*models.EmailAddress, len(form.Emails))
for i := range form.Emails { for i := range form.Emails {
emails[i] = &models.EmailAddress{ emails[i] = &models.EmailAddress{
UID: ctx.User.ID, UID: c.User.ID,
Email: form.Emails[i], Email: form.Emails[i],
} }
} }
if err := models.DeleteEmailAddresses(emails); err != nil { if err := models.DeleteEmailAddresses(emails); err != nil {
ctx.Error(500, "DeleteEmailAddresses", err) c.Error(500, "DeleteEmailAddresses", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

94
routers/api/v1/user/follower.go

@ -11,110 +11,110 @@ import (
"github.com/gogits/gogs/pkg/context" "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)) apiUsers := make([]*api.User, len(users))
for i := range users { for i := range users {
apiUsers[i] = users[i].APIFormat() apiUsers[i] = users[i].APIFormat()
} }
ctx.JSON(200, &apiUsers) c.JSON(200, &apiUsers)
} }
func listUserFollowers(ctx *context.APIContext, u *models.User) { func listUserFollowers(c *context.APIContext, u *models.User) {
users, err := u.GetFollowers(ctx.QueryInt("page")) users, err := u.GetFollowers(c.QueryInt("page"))
if err != nil { if err != nil {
ctx.Error(500, "GetUserFollowers", err) c.Error(500, "GetUserFollowers", err)
return return
} }
responseApiUsers(ctx, users) responseApiUsers(c, users)
} }
func ListMyFollowers(ctx *context.APIContext) { func ListMyFollowers(c *context.APIContext) {
listUserFollowers(ctx, ctx.User) listUserFollowers(c, c.User)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-followers-of-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-followers-of-a-user
func ListFollowers(ctx *context.APIContext) { func ListFollowers(c *context.APIContext) {
u := GetUserByParams(ctx) u := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
listUserFollowers(ctx, u) listUserFollowers(c, u)
} }
func listUserFollowing(ctx *context.APIContext, u *models.User) { func listUserFollowing(c *context.APIContext, u *models.User) {
users, err := u.GetFollowing(ctx.QueryInt("page")) users, err := u.GetFollowing(c.QueryInt("page"))
if err != nil { if err != nil {
ctx.Error(500, "GetFollowing", err) c.Error(500, "GetFollowing", err)
return return
} }
responseApiUsers(ctx, users) responseApiUsers(c, users)
} }
func ListMyFollowing(ctx *context.APIContext) { func ListMyFollowing(c *context.APIContext) {
listUserFollowing(ctx, ctx.User) listUserFollowing(c, c.User)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-users-followed-by-another-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-users-followed-by-another-user
func ListFollowing(ctx *context.APIContext) { func ListFollowing(c *context.APIContext) {
u := GetUserByParams(ctx) u := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return 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) { if u.IsFollowing(followID) {
ctx.Status(204) c.Status(204)
} else { } else {
ctx.Status(404) c.Status(404)
} }
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-you-are-following-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-you-are-following-a-user
func CheckMyFollowing(ctx *context.APIContext) { func CheckMyFollowing(c *context.APIContext) {
target := GetUserByParams(ctx) target := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return 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 // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-one-user-follows-another
func CheckFollowing(ctx *context.APIContext) { func CheckFollowing(c *context.APIContext) {
u := GetUserByParams(ctx) u := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
target := GetUserByParamsName(ctx, ":target") target := GetUserByParamsName(c, ":target")
if ctx.Written() { if c.Written() {
return return
} }
checkUserFollowing(ctx, u, target.ID) checkUserFollowing(c, u, target.ID)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#follow-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#follow-a-user
func Follow(ctx *context.APIContext) { func Follow(c *context.APIContext) {
target := GetUserByParams(ctx) target := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
if err := models.FollowUser(ctx.User.ID, target.ID); err != nil { if err := models.FollowUser(c.User.ID, target.ID); err != nil {
ctx.Error(500, "FollowUser", err) c.Error(500, "FollowUser", err)
return return
} }
ctx.Status(204) c.Status(204)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#unfollow-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#unfollow-a-user
func Unfollow(ctx *context.APIContext) { func Unfollow(c *context.APIContext) {
target := GetUserByParams(ctx) target := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
if err := models.UnfollowUser(ctx.User.ID, target.ID); err != nil { if err := models.UnfollowUser(c.User.ID, target.ID); err != nil {
ctx.Error(500, "UnfollowUser", err) c.Error(500, "UnfollowUser", err)
return return
} }
ctx.Status(204) c.Status(204)
} }

62
routers/api/v1/user/key.go

@ -15,13 +15,13 @@ import (
"github.com/gogits/gogs/routers/api/v1/repo" "github.com/gogits/gogs/routers/api/v1/repo"
) )
func GetUserByParamsName(ctx *context.APIContext, name string) *models.User { func GetUserByParamsName(c *context.APIContext, name string) *models.User {
user, err := models.GetUserByName(ctx.Params(name)) user, err := models.GetUserByName(c.Params(name))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return nil 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. // GetUserByParams returns user whose name is presented in URL paramenter.
func GetUserByParams(ctx *context.APIContext) *models.User { func GetUserByParams(c *context.APIContext) *models.User {
return GetUserByParamsName(ctx, ":username") return GetUserByParamsName(c, ":username")
} }
func composePublicKeysAPILink() string { func composePublicKeysAPILink() string {
return setting.AppURL + "api/v1/user/keys/" 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) keys, err := models.ListPublicKeys(uid)
if err != nil { if err != nil {
ctx.Error(500, "ListPublicKeys", err) c.Error(500, "ListPublicKeys", err)
return return
} }
@ -50,71 +50,71 @@ func listPublicKeys(ctx *context.APIContext, uid int64) {
apiKeys[i] = convert.ToPublicKey(apiLink, keys[i]) 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 // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-your-public-keys
func ListMyPublicKeys(ctx *context.APIContext) { func ListMyPublicKeys(c *context.APIContext) {
listPublicKeys(ctx, ctx.User.ID) listPublicKeys(c, c.User.ID)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user
func ListPublicKeys(ctx *context.APIContext) { func ListPublicKeys(c *context.APIContext) {
user := GetUserByParams(ctx) user := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return 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 // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#get-a-single-public-key
func GetPublicKey(ctx *context.APIContext) { func GetPublicKey(c *context.APIContext) {
key, err := models.GetPublicKeyByID(ctx.ParamsInt64(":id")) key, err := models.GetPublicKeyByID(c.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrKeyNotExist(err) { if models.IsErrKeyNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetPublicKeyByID", err) c.Error(500, "GetPublicKeyByID", err)
} }
return return
} }
apiLink := composePublicKeysAPILink() 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. // 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) content, err := models.CheckPublicKeyString(form.Key)
if err != nil { if err != nil {
repo.HandleCheckKeyStringError(ctx, err) repo.HandleCheckKeyStringError(c, err)
return return
} }
key, err := models.AddPublicKey(uid, form.Title, content) key, err := models.AddPublicKey(uid, form.Title, content)
if err != nil { if err != nil {
repo.HandleAddKeyError(ctx, err) repo.HandleAddKeyError(c, err)
return return
} }
apiLink := composePublicKeysAPILink() 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 // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#create-a-public-key
func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) { func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) {
CreateUserPublicKey(ctx, form, ctx.User.ID) CreateUserPublicKey(c, form, c.User.ID)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key
func DeletePublicKey(ctx *context.APIContext) { func DeletePublicKey(c *context.APIContext) {
if err := models.DeletePublicKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if err := models.DeletePublicKey(c.User, c.ParamsInt64(":id")); err != nil {
if models.IsErrKeyAccessDenied(err) { 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 { } else {
ctx.Error(500, "DeletePublicKey", err) c.Error(500, "DeletePublicKey", err)
} }
return return
} }
ctx.Status(204) c.Status(204)
} }

28
routers/api/v1/user/user.go

@ -14,11 +14,11 @@ import (
"github.com/gogits/gogs/pkg/context" "github.com/gogits/gogs/pkg/context"
) )
func Search(ctx *context.APIContext) { func Search(c *context.APIContext) {
opts := &models.SearchUserOptions{ opts := &models.SearchUserOptions{
Keyword: ctx.Query("q"), Keyword: c.Query("q"),
Type: models.USER_TYPE_INDIVIDUAL, Type: models.USER_TYPE_INDIVIDUAL,
PageSize: com.StrTo(ctx.Query("limit")).MustInt(), PageSize: com.StrTo(c.Query("limit")).MustInt(),
} }
if opts.PageSize == 0 { if opts.PageSize == 0 {
opts.PageSize = 10 opts.PageSize = 10
@ -26,7 +26,7 @@ func Search(ctx *context.APIContext) {
users, _, err := models.SearchUserByName(opts) users, _, err := models.SearchUserByName(opts)
if err != nil { if err != nil {
ctx.JSON(500, map[string]interface{}{ c.JSON(500, map[string]interface{}{
"ok": false, "ok": false,
"error": err.Error(), "error": err.Error(),
}) })
@ -41,35 +41,35 @@ func Search(ctx *context.APIContext) {
AvatarUrl: users[i].AvatarLink(), AvatarUrl: users[i].AvatarLink(),
FullName: users[i].FullName, FullName: users[i].FullName,
} }
if ctx.IsLogged { if c.IsLogged {
results[i].Email = users[i].Email results[i].Email = users[i].Email
} }
} }
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"ok": true, "ok": true,
"data": results, "data": results,
}) })
} }
func GetInfo(ctx *context.APIContext) { func GetInfo(c *context.APIContext) {
u, err := models.GetUserByName(ctx.Params(":username")) u, err := models.GetUserByName(c.Params(":username"))
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Status(404) c.Status(404)
} else { } else {
ctx.Error(500, "GetUserByName", err) c.Error(500, "GetUserByName", err)
} }
return return
} }
// Hide user e-mail when API caller isn't signed in. // Hide user e-mail when API caller isn't signed in.
if !ctx.IsLogged { if !c.IsLogged {
u.Email = "" u.Email = ""
} }
ctx.JSON(200, u.APIFormat()) c.JSON(200, u.APIFormat())
} }
func GetAuthenticatedUser(ctx *context.APIContext) { func GetAuthenticatedUser(c *context.APIContext) {
ctx.JSON(200, ctx.User.APIFormat()) c.JSON(200, c.User.APIFormat())
} }

20
routers/dev/template.go

@ -10,15 +10,15 @@ import (
"github.com/gogits/gogs/pkg/setting" "github.com/gogits/gogs/pkg/setting"
) )
func TemplatePreview(ctx *context.Context) { func TemplatePreview(c *context.Context) {
ctx.Data["User"] = models.User{Name: "Unknown"} c.Data["User"] = models.User{Name: "Unknown"}
ctx.Data["AppName"] = setting.AppName c.Data["AppName"] = setting.AppName
ctx.Data["AppVer"] = setting.AppVer c.Data["AppVer"] = setting.AppVer
ctx.Data["AppURL"] = setting.AppURL c.Data["AppURL"] = setting.AppURL
ctx.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374" c.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374"
ctx.Data["ActiveCodeLives"] = setting.Service.ActiveCodeLives / 60 c.Data["ActiveCodeLives"] = setting.Service.ActiveCodeLives / 60
ctx.Data["ResetPwdCodeLives"] = setting.Service.ResetPwdCodeLives / 60 c.Data["ResetPwdCodeLives"] = setting.Service.ResetPwdCodeLives / 60
ctx.Data["CurDbValue"] = "" c.Data["CurDbValue"] = ""
ctx.HTML(200, (ctx.Params("*"))) c.HTML(200, (c.Params("*")))
} }

94
routers/home.go

@ -20,61 +20,61 @@ const (
EXPLORE_ORGANIZATIONS = "explore/organizations" EXPLORE_ORGANIZATIONS = "explore/organizations"
) )
func Home(ctx *context.Context) { func Home(c *context.Context) {
if ctx.IsLogged { if c.IsLogged {
if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { if !c.User.IsActive && setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account") c.Data["Title"] = c.Tr("auth.active_your_account")
ctx.HTML(200, user.ACTIVATE) c.HTML(200, user.ACTIVATE)
} else { } else {
user.Dashboard(ctx) user.Dashboard(c)
} }
return return
} }
// Check auto-login. // Check auto-login.
uname := ctx.GetCookie(setting.CookieUserName) uname := c.GetCookie(setting.CookieUserName)
if len(uname) != 0 { if len(uname) != 0 {
ctx.Redirect(setting.AppSubURL + "/user/login") c.Redirect(setting.AppSubURL + "/user/login")
return return
} }
ctx.Data["PageIsHome"] = true c.Data["PageIsHome"] = true
ctx.HTML(200, HOME) c.HTML(200, HOME)
} }
func ExploreRepos(ctx *context.Context) { func ExploreRepos(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("explore") c.Data["Title"] = c.Tr("explore")
ctx.Data["PageIsExplore"] = true c.Data["PageIsExplore"] = true
ctx.Data["PageIsExploreRepositories"] = true c.Data["PageIsExploreRepositories"] = true
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page <= 0 { if page <= 0 {
page = 1 page = 1
} }
keyword := ctx.Query("q") keyword := c.Query("q")
repos, count, err := models.SearchRepositoryByName(&models.SearchRepoOptions{ repos, count, err := models.SearchRepositoryByName(&models.SearchRepoOptions{
Keyword: keyword, Keyword: keyword,
UserID: ctx.UserID(), UserID: c.UserID(),
OrderBy: "updated_unix DESC", OrderBy: "updated_unix DESC",
Page: page, Page: page,
PageSize: setting.UI.ExplorePagingNum, PageSize: setting.UI.ExplorePagingNum,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "SearchRepositoryByName", err) c.Handle(500, "SearchRepositoryByName", err)
return return
} }
ctx.Data["Keyword"] = keyword c.Data["Keyword"] = keyword
ctx.Data["Total"] = count c.Data["Total"] = count
ctx.Data["Page"] = paginater.New(int(count), setting.UI.ExplorePagingNum, page, 5) c.Data["Page"] = paginater.New(int(count), setting.UI.ExplorePagingNum, page, 5)
if err = models.RepositoryList(repos).LoadAttributes(); err != nil { if err = models.RepositoryList(repos).LoadAttributes(); err != nil {
ctx.Handle(500, "LoadAttributes", err) c.Handle(500, "LoadAttributes", err)
return return
} }
ctx.Data["Repos"] = repos c.Data["Repos"] = repos
ctx.HTML(200, EXPLORE_REPOS) c.HTML(200, EXPLORE_REPOS)
} }
type UserSearchOptions struct { type UserSearchOptions struct {
@ -86,8 +86,8 @@ type UserSearchOptions struct {
TplName string TplName string
} }
func RenderUserSearch(ctx *context.Context, opts *UserSearchOptions) { func RenderUserSearch(c *context.Context, opts *UserSearchOptions) {
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page <= 1 { if page <= 1 {
page = 1 page = 1
} }
@ -98,11 +98,11 @@ func RenderUserSearch(ctx *context.Context, opts *UserSearchOptions) {
err error err error
) )
keyword := ctx.Query("q") keyword := c.Query("q")
if len(keyword) == 0 { if len(keyword) == 0 {
users, err = opts.Ranger(page, opts.PageSize) users, err = opts.Ranger(page, opts.PageSize)
if err != nil { if err != nil {
ctx.Handle(500, "opts.Ranger", err) c.Handle(500, "opts.Ranger", err)
return return
} }
count = opts.Counter() count = opts.Counter()
@ -115,24 +115,24 @@ func RenderUserSearch(ctx *context.Context, opts *UserSearchOptions) {
PageSize: opts.PageSize, PageSize: opts.PageSize,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "SearchUserByName", err) c.Handle(500, "SearchUserByName", err)
return return
} }
} }
ctx.Data["Keyword"] = keyword c.Data["Keyword"] = keyword
ctx.Data["Total"] = count c.Data["Total"] = count
ctx.Data["Page"] = paginater.New(int(count), opts.PageSize, page, 5) c.Data["Page"] = paginater.New(int(count), opts.PageSize, page, 5)
ctx.Data["Users"] = users c.Data["Users"] = users
ctx.HTML(200, opts.TplName) c.HTML(200, opts.TplName)
} }
func ExploreUsers(ctx *context.Context) { func ExploreUsers(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("explore") c.Data["Title"] = c.Tr("explore")
ctx.Data["PageIsExplore"] = true c.Data["PageIsExplore"] = true
ctx.Data["PageIsExploreUsers"] = true c.Data["PageIsExploreUsers"] = true
RenderUserSearch(ctx, &UserSearchOptions{ RenderUserSearch(c, &UserSearchOptions{
Type: models.USER_TYPE_INDIVIDUAL, Type: models.USER_TYPE_INDIVIDUAL,
Counter: models.CountUsers, Counter: models.CountUsers,
Ranger: models.Users, Ranger: models.Users,
@ -142,12 +142,12 @@ func ExploreUsers(ctx *context.Context) {
}) })
} }
func ExploreOrganizations(ctx *context.Context) { func ExploreOrganizations(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("explore") c.Data["Title"] = c.Tr("explore")
ctx.Data["PageIsExplore"] = true c.Data["PageIsExplore"] = true
ctx.Data["PageIsExploreOrganizations"] = true c.Data["PageIsExploreOrganizations"] = true
RenderUserSearch(ctx, &UserSearchOptions{ RenderUserSearch(c, &UserSearchOptions{
Type: models.USER_TYPE_ORGANIZATION, Type: models.USER_TYPE_ORGANIZATION,
Counter: models.CountOrganizations, Counter: models.CountOrganizations,
Ranger: models.Organizations, Ranger: models.Organizations,
@ -157,7 +157,7 @@ func ExploreOrganizations(ctx *context.Context) {
}) })
} }
func NotFound(ctx *context.Context) { func NotFound(c *context.Context) {
ctx.Data["Title"] = "Page Not Found" c.Data["Title"] = "Page Not Found"
ctx.Handle(404, "home.NotFound", nil) c.NotFound()
} }

80
routers/org/members.go

@ -19,105 +19,105 @@ const (
MEMBER_INVITE = "org/member/invite" MEMBER_INVITE = "org/member/invite"
) )
func Members(ctx *context.Context) { func Members(c *context.Context) {
org := ctx.Org.Organization org := c.Org.Organization
ctx.Data["Title"] = org.FullName c.Data["Title"] = org.FullName
ctx.Data["PageIsOrgMembers"] = true c.Data["PageIsOrgMembers"] = true
if err := org.GetMembers(); err != nil { if err := org.GetMembers(); err != nil {
ctx.Handle(500, "GetMembers", err) c.Handle(500, "GetMembers", err)
return return
} }
ctx.Data["Members"] = org.Members c.Data["Members"] = org.Members
ctx.HTML(200, MEMBERS) c.HTML(200, MEMBERS)
} }
func MembersAction(ctx *context.Context) { func MembersAction(c *context.Context) {
uid := com.StrTo(ctx.Query("uid")).MustInt64() uid := com.StrTo(c.Query("uid")).MustInt64()
if uid == 0 { if uid == 0 {
ctx.Redirect(ctx.Org.OrgLink + "/members") c.Redirect(c.Org.OrgLink + "/members")
return return
} }
org := ctx.Org.Organization org := c.Org.Organization
var err error var err error
switch ctx.Params(":action") { switch c.Params(":action") {
case "private": case "private":
if ctx.User.ID != uid && !ctx.Org.IsOwner { if c.User.ID != uid && !c.Org.IsOwner {
ctx.Error(404) c.Error(404)
return return
} }
err = models.ChangeOrgUserStatus(org.ID, uid, false) err = models.ChangeOrgUserStatus(org.ID, uid, false)
case "public": case "public":
if ctx.User.ID != uid && !ctx.Org.IsOwner { if c.User.ID != uid && !c.Org.IsOwner {
ctx.Error(404) c.Error(404)
return return
} }
err = models.ChangeOrgUserStatus(org.ID, uid, true) err = models.ChangeOrgUserStatus(org.ID, uid, true)
case "remove": case "remove":
if !ctx.Org.IsOwner { if !c.Org.IsOwner {
ctx.Error(404) c.Error(404)
return return
} }
err = org.RemoveMember(uid) err = org.RemoveMember(uid)
if models.IsErrLastOrgOwner(err) { if models.IsErrLastOrgOwner(err) {
ctx.Flash.Error(ctx.Tr("form.last_org_owner")) c.Flash.Error(c.Tr("form.last_org_owner"))
ctx.Redirect(ctx.Org.OrgLink + "/members") c.Redirect(c.Org.OrgLink + "/members")
return return
} }
case "leave": case "leave":
err = org.RemoveMember(ctx.User.ID) err = org.RemoveMember(c.User.ID)
if models.IsErrLastOrgOwner(err) { if models.IsErrLastOrgOwner(err) {
ctx.Flash.Error(ctx.Tr("form.last_org_owner")) c.Flash.Error(c.Tr("form.last_org_owner"))
ctx.Redirect(ctx.Org.OrgLink + "/members") c.Redirect(c.Org.OrgLink + "/members")
return return
} }
} }
if err != nil { if err != nil {
log.Error(4, "Action(%s): %v", ctx.Params(":action"), err) log.Error(4, "Action(%s): %v", c.Params(":action"), err)
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"ok": false, "ok": false,
"err": err.Error(), "err": err.Error(),
}) })
return return
} }
if ctx.Params(":action") != "leave" { if c.Params(":action") != "leave" {
ctx.Redirect(ctx.Org.OrgLink + "/members") c.Redirect(c.Org.OrgLink + "/members")
} else { } else {
ctx.Redirect(setting.AppSubURL + "/") c.Redirect(setting.AppSubURL + "/")
} }
} }
func Invitation(ctx *context.Context) { func Invitation(c *context.Context) {
org := ctx.Org.Organization org := c.Org.Organization
ctx.Data["Title"] = org.FullName c.Data["Title"] = org.FullName
ctx.Data["PageIsOrgMembers"] = true c.Data["PageIsOrgMembers"] = true
if ctx.Req.Method == "POST" { if c.Req.Method == "POST" {
uname := ctx.Query("uname") uname := c.Query("uname")
u, err := models.GetUserByName(uname) u, err := models.GetUserByName(uname)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Flash.Error(ctx.Tr("form.user_not_exist")) c.Flash.Error(c.Tr("form.user_not_exist"))
ctx.Redirect(ctx.Org.OrgLink + "/invitations/new") c.Redirect(c.Org.OrgLink + "/invitations/new")
} else { } else {
ctx.Handle(500, " GetUserByName", err) c.Handle(500, " GetUserByName", err)
} }
return return
} }
if err = org.AddMember(u.ID); err != nil { if err = org.AddMember(u.ID); err != nil {
ctx.Handle(500, " AddMember", err) c.Handle(500, " AddMember", err)
return return
} }
log.Trace("New member added(%s): %s", org.Name, u.Name) log.Trace("New member added(%s): %s", org.Name, u.Name)
ctx.Redirect(ctx.Org.OrgLink + "/members") c.Redirect(c.Org.OrgLink + "/members")
return return
} }
ctx.HTML(200, MEMBER_INVITE) c.HTML(200, MEMBER_INVITE)
} }

28
routers/org/org.go

@ -17,16 +17,16 @@ const (
CREATE = "org/create" CREATE = "org/create"
) )
func Create(ctx *context.Context) { func Create(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("new_org") c.Data["Title"] = c.Tr("new_org")
ctx.HTML(200, CREATE) c.HTML(200, CREATE)
} }
func CreatePost(ctx *context.Context, f form.CreateOrg) { func CreatePost(c *context.Context, f form.CreateOrg) {
ctx.Data["Title"] = ctx.Tr("new_org") c.Data["Title"] = c.Tr("new_org")
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, CREATE) c.HTML(200, CREATE)
return return
} }
@ -36,21 +36,21 @@ func CreatePost(ctx *context.Context, f form.CreateOrg) {
Type: models.USER_TYPE_ORGANIZATION, Type: models.USER_TYPE_ORGANIZATION,
} }
if err := models.CreateOrganization(org, ctx.User); err != nil { if err := models.CreateOrganization(org, c.User); err != nil {
ctx.Data["Err_OrgName"] = true c.Data["Err_OrgName"] = true
switch { switch {
case models.IsErrUserAlreadyExist(err): 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): 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): 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: default:
ctx.Handle(500, "CreateOrganization", err) c.Handle(500, "CreateOrganization", err)
} }
return return
} }
log.Trace("Organization created: %s", org.Name) log.Trace("Organization created: %s", org.Name)
ctx.Redirect(setting.AppSubURL + "/org/" + f.OrgName + "/dashboard") c.Redirect(setting.AppSubURL + "/org/" + f.OrgName + "/dashboard")
} }

122
routers/org/setting.go

@ -23,54 +23,54 @@ const (
SETTINGS_WEBHOOKS = "org/settings/webhooks" SETTINGS_WEBHOOKS = "org/settings/webhooks"
) )
func Settings(ctx *context.Context) { func Settings(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings") c.Data["Title"] = c.Tr("org.settings")
ctx.Data["PageIsSettingsOptions"] = true c.Data["PageIsSettingsOptions"] = true
ctx.HTML(200, SETTINGS_OPTIONS) c.HTML(200, SETTINGS_OPTIONS)
} }
func SettingsPost(ctx *context.Context, f form.UpdateOrgSetting) { func SettingsPost(c *context.Context, f form.UpdateOrgSetting) {
ctx.Data["Title"] = ctx.Tr("org.settings") c.Data["Title"] = c.Tr("org.settings")
ctx.Data["PageIsSettingsOptions"] = true c.Data["PageIsSettingsOptions"] = true
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, SETTINGS_OPTIONS) c.HTML(200, SETTINGS_OPTIONS)
return return
} }
org := ctx.Org.Organization org := c.Org.Organization
// Check if organization name has been changed. // Check if organization name has been changed.
if org.LowerName != strings.ToLower(f.Name) { if org.LowerName != strings.ToLower(f.Name) {
isExist, err := models.IsUserExist(org.ID, f.Name) isExist, err := models.IsUserExist(org.ID, f.Name)
if err != nil { if err != nil {
ctx.Handle(500, "IsUserExist", err) c.Handle(500, "IsUserExist", err)
return return
} else if isExist { } else if isExist {
ctx.Data["OrgName"] = true c.Data["OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &f) c.RenderWithErr(c.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &f)
return return
} else if err = models.ChangeUserName(org, f.Name); err != nil { } else if err = models.ChangeUserName(org, f.Name); err != nil {
ctx.Data["OrgName"] = true c.Data["OrgName"] = true
switch { switch {
case models.IsErrNameReserved(err): 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): 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: default:
ctx.Handle(500, "ChangeUserName", err) c.Handle(500, "ChangeUserName", err)
} }
return return
} }
// reset ctx.org.OrgLink with new name // reset c.org.OrgLink with new name
ctx.Org.OrgLink = setting.AppSubURL + "/org/" + f.Name c.Org.OrgLink = setting.AppSubURL + "/org/" + f.Name
log.Trace("Organization name changed: %s -> %s", org.Name, f.Name) log.Trace("Organization name changed: %s -> %s", org.Name, f.Name)
} }
// In case it's just a case change. // In case it's just a case change.
org.Name = f.Name org.Name = f.Name
org.LowerName = strings.ToLower(f.Name) org.LowerName = strings.ToLower(f.Name)
if ctx.User.IsAdmin { if c.User.IsAdmin {
org.MaxRepoCreation = f.MaxRepoCreation org.MaxRepoCreation = f.MaxRepoCreation
} }
@ -79,90 +79,90 @@ func SettingsPost(ctx *context.Context, f form.UpdateOrgSetting) {
org.Website = f.Website org.Website = f.Website
org.Location = f.Location org.Location = f.Location
if err := models.UpdateUser(org); err != nil { if err := models.UpdateUser(org); err != nil {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
return return
} }
log.Trace("Organization setting updated: %s", org.Name) log.Trace("Organization setting updated: %s", org.Name)
ctx.Flash.Success(ctx.Tr("org.settings.update_setting_success")) c.Flash.Success(c.Tr("org.settings.update_setting_success"))
ctx.Redirect(ctx.Org.OrgLink + "/settings") 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 f.Source = form.AVATAR_LOCAL
if err := user.UpdateAvatarSetting(ctx, f, ctx.Org.Organization); err != nil { if err := user.UpdateAvatarSetting(c, f, c.Org.Organization); err != nil {
ctx.Flash.Error(err.Error()) c.Flash.Error(err.Error())
} else { } 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) { func SettingsDeleteAvatar(c *context.Context) {
if err := ctx.Org.Organization.DeleteAvatar(); err != nil { if err := c.Org.Organization.DeleteAvatar(); err != nil {
ctx.Flash.Error(err.Error()) c.Flash.Error(err.Error())
} }
ctx.Redirect(ctx.Org.OrgLink + "/settings") c.Redirect(c.Org.OrgLink + "/settings")
} }
func SettingsDelete(ctx *context.Context) { func SettingsDelete(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings") c.Data["Title"] = c.Tr("org.settings")
ctx.Data["PageIsSettingsDelete"] = true c.Data["PageIsSettingsDelete"] = true
org := ctx.Org.Organization org := c.Org.Organization
if ctx.Req.Method == "POST" { if c.Req.Method == "POST" {
if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil { if _, err := models.UserSignIn(c.User.Name, c.Query("password")); err != nil {
if errors.IsUserNotExist(err) { 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 { } else {
ctx.Handle(500, "UserSignIn", err) c.Handle(500, "UserSignIn", err)
} }
return return
} }
if err := models.DeleteOrganization(org); err != nil { if err := models.DeleteOrganization(org); err != nil {
if models.IsErrUserOwnRepos(err) { if models.IsErrUserOwnRepos(err) {
ctx.Flash.Error(ctx.Tr("form.org_still_own_repo")) c.Flash.Error(c.Tr("form.org_still_own_repo"))
ctx.Redirect(ctx.Org.OrgLink + "/settings/delete") c.Redirect(c.Org.OrgLink + "/settings/delete")
} else { } else {
ctx.Handle(500, "DeleteOrganization", err) c.Handle(500, "DeleteOrganization", err)
} }
} else { } else {
log.Trace("Organization deleted: %s", org.Name) log.Trace("Organization deleted: %s", org.Name)
ctx.Redirect(setting.AppSubURL + "/") c.Redirect(setting.AppSubURL + "/")
} }
return return
} }
ctx.HTML(200, SETTINGS_DELETE) c.HTML(200, SETTINGS_DELETE)
} }
func Webhooks(ctx *context.Context) { func Webhooks(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings") c.Data["Title"] = c.Tr("org.settings")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["BaseLink"] = ctx.Org.OrgLink c.Data["BaseLink"] = c.Org.OrgLink
ctx.Data["Description"] = ctx.Tr("org.settings.hooks_desc") c.Data["Description"] = c.Tr("org.settings.hooks_desc")
ctx.Data["Types"] = setting.Webhook.Types 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 { if err != nil {
ctx.Handle(500, "GetWebhooksByOrgId", err) c.Handle(500, "GetWebhooksByOrgId", err)
return return
} }
ctx.Data["Webhooks"] = ws c.Data["Webhooks"] = ws
ctx.HTML(200, SETTINGS_WEBHOOKS) c.HTML(200, SETTINGS_WEBHOOKS)
} }
func DeleteWebhook(ctx *context.Context) { func DeleteWebhook(c *context.Context) {
if err := models.DeleteWebhookOfOrgByID(ctx.Org.Organization.ID, ctx.QueryInt64("id")); err != nil { if err := models.DeleteWebhookOfOrgByID(c.Org.Organization.ID, c.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteWebhookByOrgID: " + err.Error()) c.Flash.Error("DeleteWebhookByOrgID: " + err.Error())
} else { } 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{}{ c.JSON(200, map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/settings/hooks", "redirect": c.Org.OrgLink + "/settings/hooks",
}) })
} }

202
routers/org/teams.go

@ -23,75 +23,75 @@ const (
TEAM_REPOSITORIES = "org/team/repositories" TEAM_REPOSITORIES = "org/team/repositories"
) )
func Teams(ctx *context.Context) { func Teams(c *context.Context) {
org := ctx.Org.Organization org := c.Org.Organization
ctx.Data["Title"] = org.FullName c.Data["Title"] = org.FullName
ctx.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
for _, t := range org.Teams { for _, t := range org.Teams {
if err := t.GetMembers(); err != nil { if err := t.GetMembers(); err != nil {
ctx.Handle(500, "GetMembers", err) c.Handle(500, "GetMembers", err)
return return
} }
} }
ctx.Data["Teams"] = org.Teams c.Data["Teams"] = org.Teams
ctx.HTML(200, TEAMS) c.HTML(200, TEAMS)
} }
func TeamsAction(ctx *context.Context) { func TeamsAction(c *context.Context) {
uid := com.StrTo(ctx.Query("uid")).MustInt64() uid := com.StrTo(c.Query("uid")).MustInt64()
if uid == 0 { if uid == 0 {
ctx.Redirect(ctx.Org.OrgLink + "/teams") c.Redirect(c.Org.OrgLink + "/teams")
return return
} }
page := ctx.Query("page") page := c.Query("page")
var err error var err error
switch ctx.Params(":action") { switch c.Params(":action") {
case "join": case "join":
if !ctx.Org.IsOwner { if !c.Org.IsOwner {
ctx.Error(404) c.Error(404)
return return
} }
err = ctx.Org.Team.AddMember(ctx.User.ID) err = c.Org.Team.AddMember(c.User.ID)
case "leave": case "leave":
err = ctx.Org.Team.RemoveMember(ctx.User.ID) err = c.Org.Team.RemoveMember(c.User.ID)
case "remove": case "remove":
if !ctx.Org.IsOwner { if !c.Org.IsOwner {
ctx.Error(404) c.Error(404)
return return
} }
err = ctx.Org.Team.RemoveMember(uid) err = c.Org.Team.RemoveMember(uid)
page = "team" page = "team"
case "add": case "add":
if !ctx.Org.IsOwner { if !c.Org.IsOwner {
ctx.Error(404) c.Error(404)
return return
} }
uname := ctx.Query("uname") uname := c.Query("uname")
var u *models.User var u *models.User
u, err = models.GetUserByName(uname) u, err = models.GetUserByName(uname)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Flash.Error(ctx.Tr("form.user_not_exist")) c.Flash.Error(c.Tr("form.user_not_exist"))
ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName) c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName)
} else { } else {
ctx.Handle(500, " GetUserByName", err) c.Handle(500, " GetUserByName", err)
} }
return return
} }
err = ctx.Org.Team.AddMember(u.ID) err = c.Org.Team.AddMember(u.ID)
page = "team" page = "team"
} }
if err != nil { if err != nil {
if models.IsErrLastOrgOwner(err) { if models.IsErrLastOrgOwner(err) {
ctx.Flash.Error(ctx.Tr("form.last_org_owner")) c.Flash.Error(c.Tr("form.last_org_owner"))
} else { } else {
log.Error(3, "Action(%s): %v", ctx.Params(":action"), err) log.Error(3, "Action(%s): %v", c.Params(":action"), err)
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"ok": false, "ok": false,
"err": err.Error(), "err": err.Error(),
}) })
@ -101,124 +101,124 @@ func TeamsAction(ctx *context.Context) {
switch page { switch page {
case "team": case "team":
ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName) c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName)
default: default:
ctx.Redirect(ctx.Org.OrgLink + "/teams") c.Redirect(c.Org.OrgLink + "/teams")
} }
} }
func TeamsRepoAction(ctx *context.Context) { func TeamsRepoAction(c *context.Context) {
if !ctx.Org.IsOwner { if !c.Org.IsOwner {
ctx.Error(404) c.Error(404)
return return
} }
var err error var err error
switch ctx.Params(":action") { switch c.Params(":action") {
case "add": case "add":
repoName := path.Base(ctx.Query("repo_name")) repoName := path.Base(c.Query("repo_name"))
var repo *models.Repository 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 err != nil {
if errors.IsRepoNotExist(err) { if errors.IsRepoNotExist(err) {
ctx.Flash.Error(ctx.Tr("org.teams.add_nonexistent_repo")) c.Flash.Error(c.Tr("org.teams.add_nonexistent_repo"))
ctx.Redirect(ctx.Org.OrgLink + "/teams/" + ctx.Org.Team.LowerName + "/repositories") c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName + "/repositories")
return return
} }
ctx.Handle(500, "GetRepositoryByName", err) c.Handle(500, "GetRepositoryByName", err)
return return
} }
err = ctx.Org.Team.AddRepository(repo) err = c.Org.Team.AddRepository(repo)
case "remove": 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 { if err != nil {
log.Error(3, "Action(%s): '%s' %v", ctx.Params(":action"), ctx.Org.Team.Name, err) log.Error(3, "Action(%s): '%s' %v", c.Params(":action"), c.Org.Team.Name, err)
ctx.Handle(500, "TeamsRepoAction", err) c.Handle(500, "TeamsRepoAction", err)
return 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) { func NewTeam(c *context.Context) {
ctx.Data["Title"] = ctx.Org.Organization.FullName c.Data["Title"] = c.Org.Organization.FullName
ctx.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
ctx.Data["PageIsOrgTeamsNew"] = true c.Data["PageIsOrgTeamsNew"] = true
ctx.Data["Team"] = &models.Team{} c.Data["Team"] = &models.Team{}
ctx.HTML(200, TEAM_NEW) c.HTML(200, TEAM_NEW)
} }
func NewTeamPost(ctx *context.Context, f form.CreateTeam) { func NewTeamPost(c *context.Context, f form.CreateTeam) {
ctx.Data["Title"] = ctx.Org.Organization.FullName c.Data["Title"] = c.Org.Organization.FullName
ctx.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
ctx.Data["PageIsOrgTeamsNew"] = true c.Data["PageIsOrgTeamsNew"] = true
t := &models.Team{ t := &models.Team{
OrgID: ctx.Org.Organization.ID, OrgID: c.Org.Organization.ID,
Name: f.TeamName, Name: f.TeamName,
Description: f.Description, Description: f.Description,
Authorize: models.ParseAccessMode(f.Permission), Authorize: models.ParseAccessMode(f.Permission),
} }
ctx.Data["Team"] = t c.Data["Team"] = t
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, TEAM_NEW) c.HTML(200, TEAM_NEW)
return return
} }
if err := models.NewTeam(t); err != nil { if err := models.NewTeam(t); err != nil {
ctx.Data["Err_TeamName"] = true c.Data["Err_TeamName"] = true
switch { switch {
case models.IsErrTeamAlreadyExist(err): 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): 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: default:
ctx.Handle(500, "NewTeam", err) c.Handle(500, "NewTeam", err)
} }
return return
} }
log.Trace("Team created: %s/%s", ctx.Org.Organization.Name, t.Name) log.Trace("Team created: %s/%s", c.Org.Organization.Name, t.Name)
ctx.Redirect(ctx.Org.OrgLink + "/teams/" + t.LowerName) c.Redirect(c.Org.OrgLink + "/teams/" + t.LowerName)
} }
func TeamMembers(ctx *context.Context) { func TeamMembers(c *context.Context) {
ctx.Data["Title"] = ctx.Org.Team.Name c.Data["Title"] = c.Org.Team.Name
ctx.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
if err := ctx.Org.Team.GetMembers(); err != nil { if err := c.Org.Team.GetMembers(); err != nil {
ctx.Handle(500, "GetMembers", err) c.Handle(500, "GetMembers", err)
return return
} }
ctx.HTML(200, TEAM_MEMBERS) c.HTML(200, TEAM_MEMBERS)
} }
func TeamRepositories(ctx *context.Context) { func TeamRepositories(c *context.Context) {
ctx.Data["Title"] = ctx.Org.Team.Name c.Data["Title"] = c.Org.Team.Name
ctx.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
if err := ctx.Org.Team.GetRepositories(); err != nil { if err := c.Org.Team.GetRepositories(); err != nil {
ctx.Handle(500, "GetRepositories", err) c.Handle(500, "GetRepositories", err)
return return
} }
ctx.HTML(200, TEAM_REPOSITORIES) c.HTML(200, TEAM_REPOSITORIES)
} }
func EditTeam(ctx *context.Context) { func EditTeam(c *context.Context) {
ctx.Data["Title"] = ctx.Org.Organization.FullName c.Data["Title"] = c.Org.Organization.FullName
ctx.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
ctx.Data["team_name"] = ctx.Org.Team.Name c.Data["team_name"] = c.Org.Team.Name
ctx.Data["desc"] = ctx.Org.Team.Description c.Data["desc"] = c.Org.Team.Description
ctx.HTML(200, TEAM_NEW) c.HTML(200, TEAM_NEW)
} }
func EditTeamPost(ctx *context.Context, f form.CreateTeam) { func EditTeamPost(c *context.Context, f form.CreateTeam) {
t := ctx.Org.Team t := c.Org.Team
ctx.Data["Title"] = ctx.Org.Organization.FullName c.Data["Title"] = c.Org.Organization.FullName
ctx.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
ctx.Data["Team"] = t c.Data["Team"] = t
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, TEAM_NEW) c.HTML(200, TEAM_NEW)
return return
} }
@ -234,7 +234,7 @@ func EditTeamPost(ctx *context.Context, f form.CreateTeam) {
case "admin": case "admin":
auth = models.ACCESS_MODE_ADMIN auth = models.ACCESS_MODE_ADMIN
default: default:
ctx.Error(401) c.Error(401)
return return
} }
@ -246,26 +246,26 @@ func EditTeamPost(ctx *context.Context, f form.CreateTeam) {
} }
t.Description = f.Description t.Description = f.Description
if err := models.UpdateTeam(t, isAuthChanged); err != nil { if err := models.UpdateTeam(t, isAuthChanged); err != nil {
ctx.Data["Err_TeamName"] = true c.Data["Err_TeamName"] = true
switch { switch {
case models.IsErrTeamAlreadyExist(err): 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: default:
ctx.Handle(500, "UpdateTeam", err) c.Handle(500, "UpdateTeam", err)
} }
return return
} }
ctx.Redirect(ctx.Org.OrgLink + "/teams/" + t.LowerName) c.Redirect(c.Org.OrgLink + "/teams/" + t.LowerName)
} }
func DeleteTeam(ctx *context.Context) { func DeleteTeam(c *context.Context) {
if err := models.DeleteTeam(ctx.Org.Team); err != nil { if err := models.DeleteTeam(c.Org.Team); err != nil {
ctx.Flash.Error("DeleteTeam: " + err.Error()) c.Flash.Error("DeleteTeam: " + err.Error())
} else { } 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{}{ c.JSON(200, map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/teams", "redirect": c.Org.OrgLink + "/teams",
}) })
} }

68
routers/repo/branch.go

@ -26,16 +26,16 @@ type Branch struct {
IsProtected bool IsProtected bool
} }
func loadBranches(ctx *context.Context) []*Branch { func loadBranches(c *context.Context) []*Branch {
rawBranches, err := ctx.Repo.Repository.GetBranches() rawBranches, err := c.Repo.Repository.GetBranches()
if err != nil { if err != nil {
ctx.Handle(500, "GetBranches", err) c.Handle(500, "GetBranches", err)
return nil return nil
} }
protectBranches, err := models.GetProtectBranchesByRepoID(ctx.Repo.Repository.ID) protectBranches, err := models.GetProtectBranchesByRepoID(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Handle(500, "GetProtectBranchesByRepoID", err) c.Handle(500, "GetProtectBranchesByRepoID", err)
return nil return nil
} }
@ -43,7 +43,7 @@ func loadBranches(ctx *context.Context) []*Branch {
for i := range rawBranches { for i := range rawBranches {
commit, err := rawBranches[i].GetCommit() commit, err := rawBranches[i].GetCommit()
if err != nil { if err != nil {
ctx.Handle(500, "GetCommit", err) c.Handle(500, "GetCommit", err)
return nil 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 return branches
} }
func Branches(ctx *context.Context) { func Branches(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.git_branches") c.Data["Title"] = c.Tr("repo.git_branches")
ctx.Data["PageIsBranchesOverview"] = true c.Data["PageIsBranchesOverview"] = true
branches := loadBranches(ctx) branches := loadBranches(c)
if ctx.Written() { if c.Written() {
return return
} }
@ -78,8 +78,8 @@ func Branches(ctx *context.Context) {
staleBranches := make([]*Branch, 0, 3) staleBranches := make([]*Branch, 0, 3)
for i := range branches { for i := range branches {
switch { switch {
case branches[i].Name == ctx.Repo.BranchName: case branches[i].Name == c.Repo.BranchName:
ctx.Data["DefaultBranch"] = branches[i] c.Data["DefaultBranch"] = branches[i]
case branches[i].Commit.Committer.When.Add(30 * 24 * time.Hour).After(now): // 30 days case branches[i].Commit.Committer.When.Add(30 * 24 * time.Hour).After(now): // 30 days
activeBranches = append(activeBranches, branches[i]) activeBranches = append(activeBranches, branches[i])
case branches[i].Commit.Committer.When.Add(3 * 30 * 24 * time.Hour).Before(now): // 90 days 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 c.Data["ActiveBranches"] = activeBranches
ctx.Data["StaleBranches"] = staleBranches c.Data["StaleBranches"] = staleBranches
ctx.HTML(200, BRANCHES_OVERVIEW) c.HTML(200, BRANCHES_OVERVIEW)
} }
func AllBranches(ctx *context.Context) { func AllBranches(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.git_branches") c.Data["Title"] = c.Tr("repo.git_branches")
ctx.Data["PageIsBranchesAll"] = true c.Data["PageIsBranchesAll"] = true
branches := loadBranches(ctx) branches := loadBranches(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["Branches"] = branches c.Data["Branches"] = branches
ctx.HTML(200, BRANCHES_ALL) c.HTML(200, BRANCHES_ALL)
} }
func DeleteBranchPost(ctx *context.Context) { func DeleteBranchPost(c *context.Context) {
branchName := ctx.Params("*") branchName := c.Params("*")
commitID := ctx.Query("commit") commitID := c.Query("commit")
defer func() { defer func() {
redirectTo := ctx.Query("redirect_to") redirectTo := c.Query("redirect_to")
if len(redirectTo) == 0 { 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 return
} }
if len(commitID) > 0 { if len(commitID) > 0 {
branchCommitID, err := ctx.Repo.GitRepo.GetBranchCommitID(branchName) branchCommitID, err := c.Repo.GitRepo.GetBranchCommitID(branchName)
if err != nil { if err != nil {
log.Error(2, "GetBranchCommitID: %v", err) log.Error(2, "GetBranchCommitID: %v", err)
return return
} }
if branchCommitID != commitID { 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 return
} }
} }
if err := ctx.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{ if err := c.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{
Force: true, Force: true,
}); err != nil { }); err != nil {
log.Error(2, "DeleteBranch '%s': %v", branchName, err) log.Error(2, "DeleteBranch '%s': %v", branchName, err)

194
routers/repo/commit.go

@ -21,15 +21,15 @@ const (
DIFF = "repo/diff/page" DIFF = "repo/diff/page"
) )
func RefCommits(ctx *context.Context) { func RefCommits(c *context.Context) {
ctx.Data["PageIsViewFiles"] = true c.Data["PageIsViewFiles"] = true
switch { switch {
case len(ctx.Repo.TreePath) == 0: case len(c.Repo.TreePath) == 0:
Commits(ctx) Commits(c)
case ctx.Repo.TreePath == "search": case c.Repo.TreePath == "search":
SearchCommits(ctx) SearchCommits(c)
default: default:
FileHistory(ctx) FileHistory(c)
} }
} }
@ -42,15 +42,15 @@ func RenderIssueLinks(oldCommits *list.List, repoLink string) *list.List {
return newCommits return newCommits
} }
func renderCommits(ctx *context.Context, filename string) { func renderCommits(c *context.Context, filename string) {
ctx.Data["Title"] = ctx.Tr("repo.commits.commit_history") + " · " + ctx.Repo.Repository.FullName() c.Data["Title"] = c.Tr("repo.commits.commit_history") + " · " + c.Repo.Repository.FullName()
ctx.Data["PageIsCommits"] = true c.Data["PageIsCommits"] = true
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page < 1 { if page < 1 {
page = 1 page = 1
} }
pageSize := ctx.QueryInt("pageSize") pageSize := c.QueryInt("pageSize")
if pageSize < 1 { if pageSize < 1 {
pageSize = git.DefaultCommitsPageSize pageSize = git.DefaultCommitsPageSize
} }
@ -59,80 +59,80 @@ func renderCommits(ctx *context.Context, filename string) {
var err error var err error
var commits *list.List var commits *list.List
if len(filename) == 0 { if len(filename) == 0 {
commits, err = ctx.Repo.Commit.CommitsByRangeSize(page, pageSize) commits, err = c.Repo.Commit.CommitsByRangeSize(page, pageSize)
} else { } 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 { if err != nil {
ctx.Handle(500, "CommitsByRangeSize/CommitsByFileAndRangeSize", err) c.Handle(500, "CommitsByRangeSize/CommitsByFileAndRangeSize", err)
return return
} }
commits = RenderIssueLinks(commits, ctx.Repo.RepoLink) commits = RenderIssueLinks(commits, c.Repo.RepoLink)
commits = models.ValidateCommitsWithEmails(commits) commits = models.ValidateCommitsWithEmails(commits)
ctx.Data["Commits"] = commits c.Data["Commits"] = commits
if page > 1 { if page > 1 {
ctx.Data["HasPrevious"] = true c.Data["HasPrevious"] = true
ctx.Data["PreviousPage"] = page - 1 c.Data["PreviousPage"] = page - 1
} }
if commits.Len() == pageSize { if commits.Len() == pageSize {
ctx.Data["HasNext"] = true c.Data["HasNext"] = true
ctx.Data["NextPage"] = page + 1 c.Data["NextPage"] = page + 1
} }
ctx.Data["PageSize"] = pageSize c.Data["PageSize"] = pageSize
ctx.Data["Username"] = ctx.Repo.Owner.Name c.Data["Username"] = c.Repo.Owner.Name
ctx.Data["Reponame"] = ctx.Repo.Repository.Name c.Data["Reponame"] = c.Repo.Repository.Name
ctx.HTML(200, COMMITS) c.HTML(200, COMMITS)
} }
func Commits(ctx *context.Context) { func Commits(c *context.Context) {
renderCommits(ctx, "") renderCommits(c, "")
} }
func SearchCommits(ctx *context.Context) { func SearchCommits(c *context.Context) {
ctx.Data["PageIsCommits"] = true c.Data["PageIsCommits"] = true
keyword := ctx.Query("q") keyword := c.Query("q")
if len(keyword) == 0 { if len(keyword) == 0 {
ctx.Redirect(ctx.Repo.RepoLink + "/commits/" + ctx.Repo.BranchName) c.Redirect(c.Repo.RepoLink + "/commits/" + c.Repo.BranchName)
return return
} }
commits, err := ctx.Repo.Commit.SearchCommits(keyword) commits, err := c.Repo.Commit.SearchCommits(keyword)
if err != nil { if err != nil {
ctx.Handle(500, "SearchCommits", err) c.Handle(500, "SearchCommits", err)
return return
} }
commits = RenderIssueLinks(commits, ctx.Repo.RepoLink) commits = RenderIssueLinks(commits, c.Repo.RepoLink)
commits = models.ValidateCommitsWithEmails(commits) commits = models.ValidateCommitsWithEmails(commits)
ctx.Data["Commits"] = commits c.Data["Commits"] = commits
ctx.Data["Keyword"] = keyword c.Data["Keyword"] = keyword
ctx.Data["Username"] = ctx.Repo.Owner.Name c.Data["Username"] = c.Repo.Owner.Name
ctx.Data["Reponame"] = ctx.Repo.Repository.Name c.Data["Reponame"] = c.Repo.Repository.Name
ctx.Data["Branch"] = ctx.Repo.BranchName c.Data["Branch"] = c.Repo.BranchName
ctx.HTML(200, COMMITS) c.HTML(200, COMMITS)
} }
func FileHistory(ctx *context.Context) { func FileHistory(c *context.Context) {
renderCommits(ctx, ctx.Repo.TreePath) renderCommits(c, c.Repo.TreePath)
} }
func Diff(ctx *context.Context) { func Diff(c *context.Context) {
ctx.Data["PageIsDiff"] = true c.Data["PageIsDiff"] = true
ctx.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
userName := ctx.Repo.Owner.Name userName := c.Repo.Owner.Name
repoName := ctx.Repo.Repository.Name repoName := c.Repo.Repository.Name
commitID := ctx.Params(":sha") commitID := c.Params(":sha")
commit, err := ctx.Repo.GitRepo.GetCommit(commitID) commit, err := c.Repo.GitRepo.GetCommit(commitID)
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.Handle(404, "Repo.GitRepo.GetCommit", err) c.Handle(404, "Repo.GitRepo.GetCommit", err)
} else { } else {
ctx.Handle(500, "Repo.GitRepo.GetCommit", err) c.Handle(500, "Repo.GitRepo.GetCommit", err)
} }
return return
} }
@ -141,7 +141,7 @@ func Diff(ctx *context.Context) {
commitID, setting.Git.MaxGitDiffLines, commitID, setting.Git.MaxGitDiffLines,
setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles) setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetDiffCommit", git.IsErrNotExist, err) c.NotFoundOrServerError("GetDiffCommit", git.IsErrNotExist, err)
return return
} }
@ -150,33 +150,33 @@ func Diff(ctx *context.Context) {
sha, err := commit.ParentID(i) sha, err := commit.ParentID(i)
parents[i] = sha.String() parents[i] = sha.String()
if err != nil { if err != nil {
ctx.Handle(404, "repo.Diff", err) c.Handle(404, "repo.Diff", err)
return return
} }
} }
setEditorconfigIfExists(ctx) setEditorconfigIfExists(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["CommitID"] = commitID c.Data["CommitID"] = commitID
ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split" c.Data["IsSplitStyle"] = c.Query("style") == "split"
ctx.Data["Username"] = userName c.Data["Username"] = userName
ctx.Data["Reponame"] = repoName c.Data["Reponame"] = repoName
ctx.Data["IsImageFile"] = commit.IsImageFile c.Data["IsImageFile"] = commit.IsImageFile
ctx.Data["Title"] = commit.Summary() + " · " + tool.ShortSHA1(commitID) c.Data["Title"] = commit.Summary() + " · " + tool.ShortSHA1(commitID)
ctx.Data["Commit"] = commit c.Data["Commit"] = commit
ctx.Data["Author"] = models.ValidateCommitWithEmail(commit) c.Data["Author"] = models.ValidateCommitWithEmail(commit)
ctx.Data["Diff"] = diff c.Data["Diff"] = diff
ctx.Data["Parents"] = parents c.Data["Parents"] = parents
ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", commitID) c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", commitID)
if commit.ParentCount() > 0 { 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) c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", commitID)
ctx.HTML(200, DIFF) c.HTML(200, DIFF)
} }
func RawDiff(c *context.Context) { func RawDiff(c *context.Context) {
@ -191,16 +191,16 @@ func RawDiff(c *context.Context) {
} }
} }
func CompareDiff(ctx *context.Context) { func CompareDiff(c *context.Context) {
ctx.Data["IsDiffCompare"] = true c.Data["IsDiffCompare"] = true
userName := ctx.Repo.Owner.Name userName := c.Repo.Owner.Name
repoName := ctx.Repo.Repository.Name repoName := c.Repo.Repository.Name
beforeCommitID := ctx.Params(":before") beforeCommitID := c.Params(":before")
afterCommitID := ctx.Params(":after") afterCommitID := c.Params(":after")
commit, err := ctx.Repo.GitRepo.GetCommit(afterCommitID) commit, err := c.Repo.GitRepo.GetCommit(afterCommitID)
if err != nil { if err != nil {
ctx.Handle(404, "GetCommit", err) c.Handle(404, "GetCommit", err)
return return
} }
@ -208,32 +208,32 @@ func CompareDiff(ctx *context.Context) {
afterCommitID, setting.Git.MaxGitDiffLines, afterCommitID, setting.Git.MaxGitDiffLines,
setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles) setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
if err != nil { if err != nil {
ctx.Handle(404, "GetDiffRange", err) c.Handle(404, "GetDiffRange", err)
return return
} }
commits, err := commit.CommitsBeforeUntil(beforeCommitID) commits, err := commit.CommitsBeforeUntil(beforeCommitID)
if err != nil { if err != nil {
ctx.Handle(500, "CommitsBeforeUntil", err) c.Handle(500, "CommitsBeforeUntil", err)
return return
} }
commits = models.ValidateCommitsWithEmails(commits) commits = models.ValidateCommitsWithEmails(commits)
ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split" c.Data["IsSplitStyle"] = c.Query("style") == "split"
ctx.Data["CommitRepoLink"] = ctx.Repo.RepoLink c.Data["CommitRepoLink"] = c.Repo.RepoLink
ctx.Data["Commits"] = commits c.Data["Commits"] = commits
ctx.Data["CommitsCount"] = commits.Len() c.Data["CommitsCount"] = commits.Len()
ctx.Data["BeforeCommitID"] = beforeCommitID c.Data["BeforeCommitID"] = beforeCommitID
ctx.Data["AfterCommitID"] = afterCommitID c.Data["AfterCommitID"] = afterCommitID
ctx.Data["Username"] = userName c.Data["Username"] = userName
ctx.Data["Reponame"] = repoName c.Data["Reponame"] = repoName
ctx.Data["IsImageFile"] = commit.IsImageFile c.Data["IsImageFile"] = commit.IsImageFile
ctx.Data["Title"] = "Comparing " + tool.ShortSHA1(beforeCommitID) + "..." + tool.ShortSHA1(afterCommitID) + " · " + userName + "/" + repoName c.Data["Title"] = "Comparing " + tool.ShortSHA1(beforeCommitID) + "..." + tool.ShortSHA1(afterCommitID) + " · " + userName + "/" + repoName
ctx.Data["Commit"] = commit c.Data["Commit"] = commit
ctx.Data["Diff"] = diff c.Data["Diff"] = diff
ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", afterCommitID) c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", afterCommitID)
ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", beforeCommitID) c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", beforeCommitID)
ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", afterCommitID) c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", afterCommitID)
ctx.HTML(200, DIFF) c.HTML(200, DIFF)
} }

30
routers/repo/download.go

@ -15,7 +15,7 @@ import (
"github.com/gogits/gogs/pkg/setting" "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) buf := make([]byte, 1024)
n, _ := reader.Read(buf) n, _ := reader.Read(buf)
if n >= 0 { if n >= 0 {
@ -24,37 +24,37 @@ func ServeData(ctx *context.Context, name string, reader io.Reader) error {
if !tool.IsTextFile(buf) { if !tool.IsTextFile(buf) {
if !tool.IsImageFile(buf) { if !tool.IsImageFile(buf) {
ctx.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"") c.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"")
ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary") c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
} }
} else if !setting.Repository.EnableRawFileRenderMode || !ctx.QueryBool("render") { } else if !setting.Repository.EnableRawFileRenderMode || !c.QueryBool("render") {
ctx.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8") c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
} }
ctx.Resp.Write(buf) c.Resp.Write(buf)
_, err := io.Copy(ctx.Resp, reader) _, err := io.Copy(c.Resp, reader)
return err return err
} }
func ServeBlob(ctx *context.Context, blob *git.Blob) error { func ServeBlob(c *context.Context, blob *git.Blob) error {
dataRc, err := blob.Data() dataRc, err := blob.Data()
if err != nil { if err != nil {
return err 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) { func SingleDownload(c *context.Context) {
blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath) blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath)
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.Handle(404, "GetBlobByPath", nil) c.Handle(404, "GetBlobByPath", nil)
} else { } else {
ctx.Handle(500, "GetBlobByPath", err) c.Handle(500, "GetBlobByPath", err)
} }
return return
} }
if err = ServeBlob(ctx, blob); err != nil { if err = ServeBlob(c, blob); err != nil {
ctx.Handle(500, "ServeBlob", err) c.Handle(500, "ServeBlob", err)
} }
} }

204
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) { func EditFilePost(c *context.Context, f form.EditRepoFile) {
editFilePost(ctx, f, false) editFilePost(c, f, false)
} }
func NewFilePost(ctx *context.Context, f form.EditRepoFile) { func NewFilePost(c *context.Context, f form.EditRepoFile) {
editFilePost(ctx, f, true) editFilePost(c, f, true)
} }
func DiffPreviewPost(ctx *context.Context, f form.EditPreviewDiff) { func DiffPreviewPost(c *context.Context, f form.EditPreviewDiff) {
treePath := ctx.Repo.TreePath treePath := c.Repo.TreePath
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treePath) entry, err := c.Repo.Commit.GetTreeEntryByPath(treePath)
if err != nil { if err != nil {
ctx.Error(500, "GetTreeEntryByPath: "+err.Error()) c.Error(500, "GetTreeEntryByPath: "+err.Error())
return return
} else if entry.IsDir() { } else if entry.IsDir() {
ctx.Error(422) c.Error(422)
return 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 { if err != nil {
ctx.Error(500, "GetDiffPreview: "+err.Error()) c.Error(500, "GetDiffPreview: "+err.Error())
return return
} }
if diff.NumFiles() == 0 { 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 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) { func DeleteFile(c *context.Context) {
ctx.Data["PageIsDelete"] = true c.Data["PageIsDelete"] = true
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
ctx.Data["TreePath"] = ctx.Repo.TreePath c.Data["TreePath"] = c.Repo.TreePath
ctx.Data["commit_summary"] = "" c.Data["commit_summary"] = ""
ctx.Data["commit_message"] = "" c.Data["commit_message"] = ""
ctx.Data["commit_choice"] = "direct" c.Data["commit_choice"] = "direct"
ctx.Data["new_branch_name"] = "" c.Data["new_branch_name"] = ""
ctx.HTML(200, DELETE_FILE) c.HTML(200, DELETE_FILE)
} }
func DeleteFilePost(ctx *context.Context, f form.DeleteRepoFile) { func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) {
ctx.Data["PageIsDelete"] = true c.Data["PageIsDelete"] = true
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
ctx.Data["TreePath"] = ctx.Repo.TreePath c.Data["TreePath"] = c.Repo.TreePath
oldBranchName := ctx.Repo.BranchName oldBranchName := c.Repo.BranchName
branchName := oldBranchName branchName := oldBranchName
if f.IsNewBrnach() { if f.IsNewBrnach() {
branchName = f.NewBranchName branchName = f.NewBranchName
} }
ctx.Data["commit_summary"] = f.CommitSummary c.Data["commit_summary"] = f.CommitSummary
ctx.Data["commit_message"] = f.CommitMessage c.Data["commit_message"] = f.CommitMessage
ctx.Data["commit_choice"] = f.CommitChoice c.Data["commit_choice"] = f.CommitChoice
ctx.Data["new_branch_name"] = branchName c.Data["new_branch_name"] = branchName
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, DELETE_FILE) c.HTML(200, DELETE_FILE)
return return
} }
if oldBranchName != branchName { if oldBranchName != branchName {
if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { if _, err := c.Repo.Repository.GetBranch(branchName); err == nil {
ctx.Data["Err_NewBranchName"] = true c.Data["Err_NewBranchName"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &f) c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &f)
return return
} }
} }
message := strings.TrimSpace(f.CommitSummary) message := strings.TrimSpace(f.CommitSummary)
if len(message) == 0 { 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) f.CommitMessage = strings.TrimSpace(f.CommitMessage)
@ -373,58 +373,58 @@ func DeleteFilePost(ctx *context.Context, f form.DeleteRepoFile) {
message += "\n\n" + f.CommitMessage message += "\n\n" + f.CommitMessage
} }
if err := ctx.Repo.Repository.DeleteRepoFile(ctx.User, models.DeleteRepoFileOptions{ if err := c.Repo.Repository.DeleteRepoFile(c.User, models.DeleteRepoFileOptions{
LastCommitID: ctx.Repo.CommitID, LastCommitID: c.Repo.CommitID,
OldBranch: oldBranchName, OldBranch: oldBranchName,
NewBranch: branchName, NewBranch: branchName,
TreePath: ctx.Repo.TreePath, TreePath: c.Repo.TreePath,
Message: message, Message: message,
}); err != nil { }); err != nil {
ctx.Handle(500, "DeleteRepoFile", err) c.Handle(500, "DeleteRepoFile", err)
return return
} }
if f.IsNewBrnach() && ctx.Repo.PullRequest.Allowed { if f.IsNewBrnach() && c.Repo.PullRequest.Allowed {
ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
} else { } else {
ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath)) c.Flash.Success(c.Tr("repo.editor.file_delete_success", c.Repo.TreePath))
ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName) c.Redirect(c.Repo.RepoLink + "/src/" + branchName)
} }
} }
func renderUploadSettings(ctx *context.Context) { func renderUploadSettings(c *context.Context) {
ctx.Data["RequireDropzone"] = true c.Data["RequireDropzone"] = true
ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",") c.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",")
ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize c.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize
ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles c.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles
} }
func UploadFile(ctx *context.Context) { func UploadFile(c *context.Context) {
ctx.Data["PageIsUpload"] = true c.Data["PageIsUpload"] = true
renderUploadSettings(ctx) renderUploadSettings(c)
treeNames, treePaths := getParentTreeFields(ctx.Repo.TreePath) treeNames, treePaths := getParentTreeFields(c.Repo.TreePath)
if len(treeNames) == 0 { if len(treeNames) == 0 {
// We must at least have one element for user to input. // We must at least have one element for user to input.
treeNames = []string{""} treeNames = []string{""}
} }
ctx.Data["TreeNames"] = treeNames c.Data["TreeNames"] = treeNames
ctx.Data["TreePaths"] = treePaths c.Data["TreePaths"] = treePaths
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
ctx.Data["commit_summary"] = "" c.Data["commit_summary"] = ""
ctx.Data["commit_message"] = "" c.Data["commit_message"] = ""
ctx.Data["commit_choice"] = "direct" c.Data["commit_choice"] = "direct"
ctx.Data["new_branch_name"] = "" c.Data["new_branch_name"] = ""
ctx.HTML(200, UPLOAD_FILE) c.HTML(200, UPLOAD_FILE)
} }
func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) { func UploadFilePost(c *context.Context, f form.UploadRepoFile) {
ctx.Data["PageIsUpload"] = true c.Data["PageIsUpload"] = true
renderUploadSettings(ctx) renderUploadSettings(c)
oldBranchName := ctx.Repo.BranchName oldBranchName := c.Repo.BranchName
branchName := oldBranchName branchName := oldBranchName
if f.IsNewBrnach() { if f.IsNewBrnach() {
@ -438,24 +438,24 @@ func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) {
treeNames = []string{""} treeNames = []string{""}
} }
ctx.Data["TreePath"] = f.TreePath c.Data["TreePath"] = f.TreePath
ctx.Data["TreeNames"] = treeNames c.Data["TreeNames"] = treeNames
ctx.Data["TreePaths"] = treePaths c.Data["TreePaths"] = treePaths
ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + branchName
ctx.Data["commit_summary"] = f.CommitSummary c.Data["commit_summary"] = f.CommitSummary
ctx.Data["commit_message"] = f.CommitMessage c.Data["commit_message"] = f.CommitMessage
ctx.Data["commit_choice"] = f.CommitChoice c.Data["commit_choice"] = f.CommitChoice
ctx.Data["new_branch_name"] = branchName c.Data["new_branch_name"] = branchName
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, UPLOAD_FILE) c.HTML(200, UPLOAD_FILE)
return return
} }
if oldBranchName != branchName { if oldBranchName != branchName {
if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { if _, err := c.Repo.Repository.GetBranch(branchName); err == nil {
ctx.Data["Err_NewBranchName"] = true c.Data["Err_NewBranchName"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &f) c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &f)
return return
} }
} }
@ -463,28 +463,28 @@ func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) {
var newTreePath string var newTreePath string
for _, part := range treeNames { for _, part := range treeNames {
newTreePath = path.Join(newTreePath, part) newTreePath = path.Join(newTreePath, part)
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(newTreePath) entry, err := c.Repo.Commit.GetTreeEntryByPath(newTreePath)
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
// Means there is no item with that name, so we're good // Means there is no item with that name, so we're good
break break
} }
ctx.Handle(500, "Repo.Commit.GetTreeEntryByPath", err) c.Handle(500, "Repo.Commit.GetTreeEntryByPath", err)
return return
} }
// User can only upload files to a directory. // User can only upload files to a directory.
if !entry.IsDir() { if !entry.IsDir() {
ctx.Data["Err_TreePath"] = true c.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &f) c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &f)
return return
} }
} }
message := strings.TrimSpace(f.CommitSummary) message := strings.TrimSpace(f.CommitSummary)
if len(message) == 0 { 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) f.CommitMessage = strings.TrimSpace(f.CommitMessage)
@ -492,30 +492,30 @@ func UploadFilePost(ctx *context.Context, f form.UploadRepoFile) {
message += "\n\n" + f.CommitMessage message += "\n\n" + f.CommitMessage
} }
if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, models.UploadRepoFileOptions{ if err := c.Repo.Repository.UploadRepoFiles(c.User, models.UploadRepoFileOptions{
LastCommitID: ctx.Repo.CommitID, LastCommitID: c.Repo.CommitID,
OldBranch: oldBranchName, OldBranch: oldBranchName,
NewBranch: branchName, NewBranch: branchName,
TreePath: f.TreePath, TreePath: f.TreePath,
Message: message, Message: message,
Files: f.Files, Files: f.Files,
}); err != nil { }); err != nil {
ctx.Data["Err_TreePath"] = true c.Data["Err_TreePath"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", f.TreePath, err), UPLOAD_FILE, &f) c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, err), UPLOAD_FILE, &f)
return return
} }
if f.IsNewBrnach() && ctx.Repo.PullRequest.Allowed { if f.IsNewBrnach() && c.Repo.PullRequest.Allowed {
ctx.Redirect(ctx.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
} else { } else {
ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath) c.Redirect(c.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath)
} }
} }
func UploadFileToServer(ctx *context.Context) { func UploadFileToServer(c *context.Context) {
file, header, err := ctx.Req.FormFile("file") file, header, err := c.Req.FormFile("file")
if err != nil { if err != nil {
ctx.Error(500, fmt.Sprintf("FormFile: %v", err)) c.Error(500, fmt.Sprintf("FormFile: %v", err))
return return
} }
defer file.Close() defer file.Close()
@ -538,34 +538,34 @@ func UploadFileToServer(ctx *context.Context) {
} }
if !allowed { if !allowed {
ctx.Error(400, ErrFileTypeForbidden.Error()) c.Error(400, ErrFileTypeForbidden.Error())
return return
} }
} }
upload, err := models.NewUpload(header.Filename, buf, file) upload, err := models.NewUpload(header.Filename, buf, file)
if err != nil { if err != nil {
ctx.Error(500, fmt.Sprintf("NewUpload: %v", err)) c.Error(500, fmt.Sprintf("NewUpload: %v", err))
return return
} }
log.Trace("New file uploaded: %s", upload.UUID) log.Trace("New file uploaded: %s", upload.UUID)
ctx.JSON(200, map[string]string{ c.JSON(200, map[string]string{
"uuid": upload.UUID, "uuid": upload.UUID,
}) })
} }
func RemoveUploadFileFromServer(ctx *context.Context, f form.RemoveUploadFile) { func RemoveUploadFileFromServer(c *context.Context, f form.RemoveUploadFile) {
if len(f.File) == 0 { if len(f.File) == 0 {
ctx.Status(204) c.Status(204)
return return
} }
if err := models.DeleteUploadByUUID(f.File); err != nil { 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 return
} }
log.Trace("Upload file removed: %s", f.File) log.Trace("Upload file removed: %s", f.File)
ctx.Status(204) c.Status(204)
} }

28
routers/repo/http.go

@ -399,9 +399,9 @@ func getGitRepoPath(dir string) (string, error) {
return filename, nil return filename, nil
} }
func HTTP(ctx *HTTPContext) { func HTTP(c *HTTPContext) {
for _, route := range routes { for _, route := range routes {
reqPath := strings.ToLower(ctx.Req.URL.Path) reqPath := strings.ToLower(c.Req.URL.Path)
m := route.reg.FindStringSubmatch(reqPath) m := route.reg.FindStringSubmatch(reqPath)
if m == nil { if m == nil {
continue 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 // but we only want to output this message only if user is really trying to access
// Git HTTP endpoints. // Git HTTP endpoints.
if setting.Repository.DisableHTTPGit { 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 return
} }
if route.method != ctx.Req.Method { if route.method != c.Req.Method {
ctx.NotFound() c.NotFound()
return return
} }
@ -424,24 +424,24 @@ func HTTP(ctx *HTTPContext) {
dir, err := getGitRepoPath(m[1]) dir, err := getGitRepoPath(m[1])
if err != nil { if err != nil {
log.Warn("HTTP.getGitRepoPath: %v", err) log.Warn("HTTP.getGitRepoPath: %v", err)
ctx.NotFound() c.NotFound()
return return
} }
route.handler(serviceHandler{ route.handler(serviceHandler{
w: ctx.Resp, w: c.Resp,
r: ctx.Req.Request, r: c.Req.Request,
dir: dir, dir: dir,
file: file, file: file,
authUser: ctx.AuthUser, authUser: c.AuthUser,
ownerName: ctx.OwnerName, ownerName: c.OwnerName,
ownerSalt: ctx.OwnerSalt, ownerSalt: c.OwnerSalt,
repoID: ctx.RepoID, repoID: c.RepoID,
repoName: ctx.RepoName, repoName: c.RepoName,
}) })
return return
} }
ctx.NotFound() c.NotFound()
} }

768
routers/repo/issue.go

File diff suppressed because it is too large Load Diff

430
routers/repo/pull.go

@ -39,124 +39,124 @@ var (
} }
) )
func parseBaseRepository(ctx *context.Context) *models.Repository { func parseBaseRepository(c *context.Context) *models.Repository {
baseRepo, err := models.GetRepositoryByID(ctx.ParamsInt64(":repoid")) baseRepo, err := models.GetRepositoryByID(c.ParamsInt64(":repoid"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err) c.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err)
return nil return nil
} }
if !baseRepo.CanBeForked() || !baseRepo.HasAccess(ctx.User.ID) { if !baseRepo.CanBeForked() || !baseRepo.HasAccess(c.User.ID) {
ctx.NotFound() c.NotFound()
return nil return nil
} }
ctx.Data["repo_name"] = baseRepo.Name c.Data["repo_name"] = baseRepo.Name
ctx.Data["description"] = baseRepo.Description c.Data["description"] = baseRepo.Description
ctx.Data["IsPrivate"] = baseRepo.IsPrivate c.Data["IsPrivate"] = baseRepo.IsPrivate
if err = baseRepo.GetOwner(); err != nil { if err = baseRepo.GetOwner(); err != nil {
ctx.Handle(500, "GetOwner", err) c.Handle(500, "GetOwner", err)
return nil 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 { if err := c.User.GetOrganizations(true); err != nil {
ctx.Handle(500, "GetOrganizations", err) c.Handle(500, "GetOrganizations", err)
return nil return nil
} }
ctx.Data["Orgs"] = ctx.User.Orgs c.Data["Orgs"] = c.User.Orgs
return baseRepo return baseRepo
} }
func Fork(ctx *context.Context) { func Fork(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("new_fork") c.Data["Title"] = c.Tr("new_fork")
parseBaseRepository(ctx) parseBaseRepository(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["ContextUser"] = ctx.User c.Data["ContextUser"] = c.User
ctx.HTML(200, FORK) c.HTML(200, FORK)
} }
func ForkPost(ctx *context.Context, f form.CreateRepo) { func ForkPost(c *context.Context, f form.CreateRepo) {
ctx.Data["Title"] = ctx.Tr("new_fork") c.Data["Title"] = c.Tr("new_fork")
baseRepo := parseBaseRepository(ctx) baseRepo := parseBaseRepository(c)
if ctx.Written() { if c.Written() {
return return
} }
ctxUser := checkContextUser(ctx, f.UserID) ctxUser := checkContextUser(c, f.UserID)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["ContextUser"] = ctxUser c.Data["ContextUser"] = ctxUser
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, FORK) c.HTML(200, FORK)
return return
} }
repo, has := models.HasForkedRepo(ctxUser.ID, baseRepo.ID) repo, has := models.HasForkedRepo(ctxUser.ID, baseRepo.ID)
if has { if has {
ctx.Redirect(repo.Link()) c.Redirect(repo.Link())
return return
} }
// Check ownership of organization. // Check ownership of organization.
if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(ctx.User.ID) { if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(c.User.ID) {
ctx.Error(403) c.Error(403)
return return
} }
// Cannot fork to same owner // Cannot fork to same owner
if ctxUser.ID == baseRepo.OwnerID { 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 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 { if err != nil {
ctx.Data["Err_RepoName"] = true c.Data["Err_RepoName"] = true
switch { switch {
case models.IsErrRepoAlreadyExist(err): 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): 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): 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: default:
ctx.Handle(500, "ForkPost", err) c.Handle(500, "ForkPost", err)
} }
return return
} }
log.Trace("Repository forked from '%s' -> '%s'", baseRepo.FullName(), repo.FullName()) 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 { func checkPullInfo(c *context.Context) *models.Issue {
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 err != nil {
ctx.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err) c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
return nil return nil
} }
ctx.Data["Title"] = issue.Title c.Data["Title"] = issue.Title
ctx.Data["Issue"] = issue c.Data["Issue"] = issue
if !issue.IsPull { if !issue.IsPull {
ctx.Handle(404, "ViewPullCommits", nil) c.Handle(404, "ViewPullCommits", nil)
return nil return nil
} }
if ctx.IsLogged { if c.IsLogged {
// Update issue-user. // Update issue-user.
if err = issue.ReadBy(ctx.User.ID); err != nil { if err = issue.ReadBy(c.User.ID); err != nil {
ctx.Handle(500, "ReadBy", err) c.Handle(500, "ReadBy", err)
return nil return nil
} }
} }
@ -164,31 +164,31 @@ func checkPullInfo(ctx *context.Context) *models.Issue {
return issue return issue
} }
func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) { func PrepareMergedViewPullInfo(c *context.Context, issue *models.Issue) {
pull := issue.PullRequest pull := issue.PullRequest
ctx.Data["HasMerged"] = true c.Data["HasMerged"] = true
ctx.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch c.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch
ctx.Data["BaseTarget"] = ctx.Repo.Owner.Name + "/" + pull.BaseBranch c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch
var err error 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 { if err != nil {
ctx.Handle(500, "Repo.GitRepo.CommitsCountBetween", err) c.Handle(500, "Repo.GitRepo.CommitsCountBetween", err)
return 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 { if err != nil {
ctx.Handle(500, "Repo.GitRepo.FilesCountBetween", err) c.Handle(500, "Repo.GitRepo.FilesCountBetween", err)
return return
} }
} }
func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullRequestInfo { func PrepareViewPullInfo(c *context.Context, issue *models.Issue) *git.PullRequestInfo {
repo := ctx.Repo.Repository repo := c.Repo.Repository
pull := issue.PullRequest pull := issue.PullRequest
ctx.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch c.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch
ctx.Data["BaseTarget"] = ctx.Repo.Owner.Name + "/" + pull.BaseBranch c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch
var ( var (
headGitRepo *git.Repository headGitRepo *git.Repository
@ -198,16 +198,16 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullReq
if pull.HeadRepo != nil { if pull.HeadRepo != nil {
headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath()) headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath())
if err != nil { if err != nil {
ctx.Handle(500, "OpenRepository", err) c.Handle(500, "OpenRepository", err)
return nil return nil
} }
} }
if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) { if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) {
ctx.Data["IsPullReuqestBroken"] = true c.Data["IsPullReuqestBroken"] = true
ctx.Data["HeadTarget"] = "deleted" c.Data["HeadTarget"] = "deleted"
ctx.Data["NumCommits"] = 0 c.Data["NumCommits"] = 0
ctx.Data["NumFiles"] = 0 c.Data["NumFiles"] = 0
return nil return nil
} }
@ -215,82 +215,82 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullReq
pull.BaseBranch, pull.HeadBranch) pull.BaseBranch, pull.HeadBranch)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "fatal: Not a valid object name") { if strings.Contains(err.Error(), "fatal: Not a valid object name") {
ctx.Data["IsPullReuqestBroken"] = true c.Data["IsPullReuqestBroken"] = true
ctx.Data["BaseTarget"] = "deleted" c.Data["BaseTarget"] = "deleted"
ctx.Data["NumCommits"] = 0 c.Data["NumCommits"] = 0
ctx.Data["NumFiles"] = 0 c.Data["NumFiles"] = 0
return nil return nil
} }
ctx.Handle(500, "GetPullRequestInfo", err) c.Handle(500, "GetPullRequestInfo", err)
return nil return nil
} }
ctx.Data["NumCommits"] = prInfo.Commits.Len() c.Data["NumCommits"] = prInfo.Commits.Len()
ctx.Data["NumFiles"] = prInfo.NumFiles c.Data["NumFiles"] = prInfo.NumFiles
return prInfo return prInfo
} }
func ViewPullCommits(ctx *context.Context) { func ViewPullCommits(c *context.Context) {
ctx.Data["PageIsPullList"] = true c.Data["PageIsPullList"] = true
ctx.Data["PageIsPullCommits"] = true c.Data["PageIsPullCommits"] = true
issue := checkPullInfo(ctx) issue := checkPullInfo(c)
if ctx.Written() { if c.Written() {
return return
} }
pull := issue.PullRequest pull := issue.PullRequest
if pull.HeadRepo != nil { if pull.HeadRepo != nil {
ctx.Data["Username"] = pull.HeadUserName c.Data["Username"] = pull.HeadUserName
ctx.Data["Reponame"] = pull.HeadRepo.Name c.Data["Reponame"] = pull.HeadRepo.Name
} }
var commits *list.List var commits *list.List
if pull.HasMerged { if pull.HasMerged {
PrepareMergedViewPullInfo(ctx, issue) PrepareMergedViewPullInfo(c, issue)
if ctx.Written() { if c.Written() {
return return
} }
startCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergeBase) startCommit, err := c.Repo.GitRepo.GetCommit(pull.MergeBase)
if err != nil { if err != nil {
ctx.Handle(500, "Repo.GitRepo.GetCommit", err) c.Handle(500, "Repo.GitRepo.GetCommit", err)
return return
} }
endCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergedCommitID) endCommit, err := c.Repo.GitRepo.GetCommit(pull.MergedCommitID)
if err != nil { if err != nil {
ctx.Handle(500, "Repo.GitRepo.GetCommit", err) c.Handle(500, "Repo.GitRepo.GetCommit", err)
return return
} }
commits, err = ctx.Repo.GitRepo.CommitsBetween(endCommit, startCommit) commits, err = c.Repo.GitRepo.CommitsBetween(endCommit, startCommit)
if err != nil { if err != nil {
ctx.Handle(500, "Repo.GitRepo.CommitsBetween", err) c.Handle(500, "Repo.GitRepo.CommitsBetween", err)
return return
} }
} else { } else {
prInfo := PrepareViewPullInfo(ctx, issue) prInfo := PrepareViewPullInfo(c, issue)
if ctx.Written() { if c.Written() {
return return
} else if prInfo == nil { } else if prInfo == nil {
ctx.Handle(404, "ViewPullCommits", nil) c.Handle(404, "ViewPullCommits", nil)
return return
} }
commits = prInfo.Commits commits = prInfo.Commits
} }
commits = models.ValidateCommitsWithEmails(commits) commits = models.ValidateCommitsWithEmails(commits)
ctx.Data["Commits"] = commits c.Data["Commits"] = commits
ctx.Data["CommitsCount"] = commits.Len() c.Data["CommitsCount"] = commits.Len()
ctx.HTML(200, PULL_COMMITS) c.HTML(200, PULL_COMMITS)
} }
func ViewPullFiles(ctx *context.Context) { func ViewPullFiles(c *context.Context) {
ctx.Data["PageIsPullList"] = true c.Data["PageIsPullList"] = true
ctx.Data["PageIsPullFiles"] = true c.Data["PageIsPullFiles"] = true
issue := checkPullInfo(ctx) issue := checkPullInfo(c)
if ctx.Written() { if c.Written() {
return return
} }
pull := issue.PullRequest pull := issue.PullRequest
@ -303,21 +303,21 @@ func ViewPullFiles(ctx *context.Context) {
) )
if pull.HasMerged { if pull.HasMerged {
PrepareMergedViewPullInfo(ctx, issue) PrepareMergedViewPullInfo(c, issue)
if ctx.Written() { if c.Written() {
return return
} }
diffRepoPath = ctx.Repo.GitRepo.Path diffRepoPath = c.Repo.GitRepo.Path
startCommitID = pull.MergeBase startCommitID = pull.MergeBase
endCommitID = pull.MergedCommitID endCommitID = pull.MergedCommitID
gitRepo = ctx.Repo.GitRepo gitRepo = c.Repo.GitRepo
} else { } else {
prInfo := PrepareViewPullInfo(ctx, issue) prInfo := PrepareViewPullInfo(c, issue)
if ctx.Written() { if c.Written() {
return return
} else if prInfo == nil { } else if prInfo == nil {
ctx.Handle(404, "ViewPullFiles", nil) c.Handle(404, "ViewPullFiles", nil)
return return
} }
@ -325,13 +325,13 @@ func ViewPullFiles(ctx *context.Context) {
headGitRepo, err := git.OpenRepository(headRepoPath) headGitRepo, err := git.OpenRepository(headRepoPath)
if err != nil { if err != nil {
ctx.Handle(500, "OpenRepository", err) c.Handle(500, "OpenRepository", err)
return return
} }
headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch) headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
if err != nil { if err != nil {
ctx.Handle(500, "GetBranchCommitID", err) c.Handle(500, "GetBranchCommitID", err)
return return
} }
@ -345,89 +345,89 @@ func ViewPullFiles(ctx *context.Context) {
startCommitID, endCommitID, setting.Git.MaxGitDiffLines, startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles) setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
if err != nil { if err != nil {
ctx.Handle(500, "GetDiffRange", err) c.Handle(500, "GetDiffRange", err)
return return
} }
ctx.Data["Diff"] = diff c.Data["Diff"] = diff
ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
commit, err := gitRepo.GetCommit(endCommitID) commit, err := gitRepo.GetCommit(endCommitID)
if err != nil { if err != nil {
ctx.Handle(500, "GetCommit", err) c.Handle(500, "GetCommit", err)
return return
} }
setEditorconfigIfExists(ctx) setEditorconfigIfExists(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split" c.Data["IsSplitStyle"] = c.Query("style") == "split"
ctx.Data["IsImageFile"] = commit.IsImageFile c.Data["IsImageFile"] = commit.IsImageFile
// It is possible head repo has been deleted for merged pull requests // It is possible head repo has been deleted for merged pull requests
if pull.HeadRepo != nil { if pull.HeadRepo != nil {
ctx.Data["Username"] = pull.HeadUserName c.Data["Username"] = pull.HeadUserName
ctx.Data["Reponame"] = pull.HeadRepo.Name c.Data["Reponame"] = pull.HeadRepo.Name
headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name) headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name)
ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID) c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID)
ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID) c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID)
ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID) c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID)
} }
ctx.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
ctx.HTML(200, PULL_FILES) c.HTML(200, PULL_FILES)
} }
func MergePullRequest(ctx *context.Context) { func MergePullRequest(c *context.Context) {
issue := checkPullInfo(ctx) issue := checkPullInfo(c)
if ctx.Written() { if c.Written() {
return return
} }
if issue.IsClosed { if issue.IsClosed {
ctx.Handle(404, "MergePullRequest", nil) c.Handle(404, "MergePullRequest", nil)
return return
} }
pr, err := models.GetPullRequestByIssueID(issue.ID) pr, err := models.GetPullRequestByIssueID(issue.ID)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetPullRequestByIssueID", models.IsErrPullRequestNotExist, err) c.NotFoundOrServerError("GetPullRequestByIssueID", models.IsErrPullRequestNotExist, err)
return return
} }
if !pr.CanAutoMerge() || pr.HasMerged { if !pr.CanAutoMerge() || pr.HasMerged {
ctx.Handle(404, "MergePullRequest", nil) c.Handle(404, "MergePullRequest", nil)
return return
} }
pr.Issue = issue pr.Issue = issue
pr.Issue.Repo = ctx.Repo.Repository pr.Issue.Repo = c.Repo.Repository
if err = pr.Merge(ctx.User, ctx.Repo.GitRepo); err != nil { if err = pr.Merge(c.User, c.Repo.GitRepo); err != nil {
ctx.Handle(500, "Merge", err) c.Handle(500, "Merge", err)
return return
} }
log.Trace("Pull request merged: %d", pr.ID) 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) { func ParseCompareInfo(c *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
baseRepo := ctx.Repo.Repository baseRepo := c.Repo.Repository
// Get compared branches information // Get compared branches information
// format: <base branch>...[<head repo>:]<head branch> // format: <base branch>...[<head repo>:]<head branch>
// base<-head: master...head:feature // base<-head: master...head:feature
// same repo: master...feature // same repo: master...feature
infos := strings.Split(ctx.Params("*"), "...") infos := strings.Split(c.Params("*"), "...")
if len(infos) != 2 { if len(infos) != 2 {
log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos) log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
ctx.Handle(404, "CompareAndPullRequest", nil) c.Handle(404, "CompareAndPullRequest", nil)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
baseBranch := infos[0] baseBranch := infos[0]
ctx.Data["BaseBranch"] = baseBranch c.Data["BaseBranch"] = baseBranch
var ( var (
headUser *models.User headUser *models.User
@ -440,29 +440,29 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
headInfos := strings.Split(infos[1], ":") headInfos := strings.Split(infos[1], ":")
if len(headInfos) == 1 { if len(headInfos) == 1 {
isSameRepo = true isSameRepo = true
headUser = ctx.Repo.Owner headUser = c.Repo.Owner
headBranch = headInfos[0] headBranch = headInfos[0]
} else if len(headInfos) == 2 { } else if len(headInfos) == 2 {
headUser, err = models.GetUserByName(headInfos[0]) headUser, err = models.GetUserByName(headInfos[0])
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
headBranch = headInfos[1] headBranch = headInfos[1]
isSameRepo = headUser.ID == baseRepo.OwnerID isSameRepo = headUser.ID == baseRepo.OwnerID
} else { } else {
ctx.Handle(404, "CompareAndPullRequest", nil) c.Handle(404, "CompareAndPullRequest", nil)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
ctx.Data["HeadUser"] = headUser c.Data["HeadUser"] = headUser
ctx.Data["HeadBranch"] = headBranch c.Data["HeadBranch"] = headBranch
ctx.Repo.PullRequest.SameRepo = isSameRepo c.Repo.PullRequest.SameRepo = isSameRepo
// Check if base branch is valid. // Check if base branch is valid.
if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) { if !c.Repo.GitRepo.IsBranchExist(baseBranch) {
ctx.Handle(404, "IsBranchExist", nil) c.Handle(404, "IsBranchExist", nil)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
@ -478,45 +478,45 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
headRepo, has = models.HasForkedRepo(headUser.ID, baseRepo.ID) headRepo, has = models.HasForkedRepo(headUser.ID, baseRepo.ID)
if !has { if !has {
log.Trace("ParseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID) log.Trace("ParseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID)
ctx.Handle(404, "ParseCompareInfo", nil) c.Handle(404, "ParseCompareInfo", nil)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name)) headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
if err != nil { if err != nil {
ctx.Handle(500, "OpenRepository", err) c.Handle(500, "OpenRepository", err)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
} else { } else {
headRepo = ctx.Repo.Repository headRepo = c.Repo.Repository
headGitRepo = ctx.Repo.GitRepo headGitRepo = c.Repo.GitRepo
} }
if !ctx.User.IsWriterOfRepo(headRepo) && !ctx.User.IsAdmin { if !c.User.IsWriterOfRepo(headRepo) && !c.User.IsAdmin {
log.Trace("ParseCompareInfo[%d]: does not have write access or site admin", baseRepo.ID) log.Trace("ParseCompareInfo[%d]: does not have write access or site admin", baseRepo.ID)
ctx.Handle(404, "ParseCompareInfo", nil) c.Handle(404, "ParseCompareInfo", nil)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
// Check if head branch is valid. // Check if head branch is valid.
if !headGitRepo.IsBranchExist(headBranch) { if !headGitRepo.IsBranchExist(headBranch) {
ctx.Handle(404, "IsBranchExist", nil) c.Handle(404, "IsBranchExist", nil)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
headBranches, err := headGitRepo.GetBranches() headBranches, err := headGitRepo.GetBranches()
if err != nil { if err != nil {
ctx.Handle(500, "GetBranches", err) c.Handle(500, "GetBranches", err)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
ctx.Data["HeadBranches"] = headBranches c.Data["HeadBranches"] = headBranches
prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch) prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
if err != nil { if err != nil {
ctx.Handle(500, "GetPullRequestInfo", err) c.Handle(500, "GetPullRequestInfo", err)
return nil, nil, nil, nil, "", "" return nil, nil, nil, nil, "", ""
} }
ctx.Data["BeforeCommitID"] = prInfo.MergeBase c.Data["BeforeCommitID"] = prInfo.MergeBase
return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
} }
@ -579,73 +579,73 @@ func PrepareCompareDiff(
return false return false
} }
func CompareAndPullRequest(ctx *context.Context) { func CompareAndPullRequest(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes") c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
ctx.Data["PageIsComparePull"] = true c.Data["PageIsComparePull"] = true
ctx.Data["IsDiffCompare"] = true c.Data["IsDiffCompare"] = true
ctx.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
setTemplateIfExists(ctx, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates) setTemplateIfExists(c, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates)
renderAttachmentSettings(ctx) renderAttachmentSettings(c)
headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx) headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
if ctx.Written() { if c.Written() {
return return
} }
pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch) pr, err := models.GetUnmergedPullRequest(headRepo.ID, c.Repo.Repository.ID, headBranch, baseBranch)
if err != nil { if err != nil {
if !models.IsErrPullRequestNotExist(err) { if !models.IsErrPullRequestNotExist(err) {
ctx.Handle(500, "GetUnmergedPullRequest", err) c.Handle(500, "GetUnmergedPullRequest", err)
return return
} }
} else { } else {
ctx.Data["HasPullRequest"] = true c.Data["HasPullRequest"] = true
ctx.Data["PullRequest"] = pr c.Data["PullRequest"] = pr
ctx.HTML(200, COMPARE_PULL) c.HTML(200, COMPARE_PULL)
return return
} }
nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch) nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
if ctx.Written() { if c.Written() {
return return
} }
if !nothingToCompare { if !nothingToCompare {
// Setup information for new form. // Setup information for new form.
RetrieveRepoMetas(ctx, ctx.Repo.Repository) RetrieveRepoMetas(c, c.Repo.Repository)
if ctx.Written() { if c.Written() {
return return
} }
} }
setEditorconfigIfExists(ctx) setEditorconfigIfExists(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split" c.Data["IsSplitStyle"] = c.Query("style") == "split"
ctx.HTML(200, COMPARE_PULL) c.HTML(200, COMPARE_PULL)
} }
func CompareAndPullRequestPost(ctx *context.Context, f form.NewIssue) { func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes") c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
ctx.Data["PageIsComparePull"] = true c.Data["PageIsComparePull"] = true
ctx.Data["IsDiffCompare"] = true c.Data["IsDiffCompare"] = true
ctx.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
renderAttachmentSettings(ctx) renderAttachmentSettings(c)
var ( var (
repo = ctx.Repo.Repository repo = c.Repo.Repository
attachments []string attachments []string
) )
headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx) headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
if ctx.Written() { if c.Written() {
return return
} }
labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, f) labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f)
if ctx.Written() { if c.Written() {
return return
} }
@ -653,23 +653,23 @@ func CompareAndPullRequestPost(ctx *context.Context, f form.NewIssue) {
attachments = f.Files attachments = f.Files
} }
if ctx.HasError() { if c.HasError() {
form.Assign(f, ctx.Data) form.Assign(f, c.Data)
// This stage is already stop creating new pull request, so it does not matter if it has // This stage is already stop creating new pull request, so it does not matter if it has
// something to compare or not. // something to compare or not.
PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch) PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
if ctx.Written() { if c.Written() {
return return
} }
ctx.HTML(200, COMPARE_PULL) c.HTML(200, COMPARE_PULL)
return return
} }
patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch) patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
if err != nil { if err != nil {
ctx.Handle(500, "GetPatch", err) c.Handle(500, "GetPatch", err)
return return
} }
@ -677,8 +677,8 @@ func CompareAndPullRequestPost(ctx *context.Context, f form.NewIssue) {
RepoID: repo.ID, RepoID: repo.ID,
Index: repo.NextIssueIndex(), Index: repo.NextIssueIndex(),
Title: f.Title, Title: f.Title,
PosterID: ctx.User.ID, PosterID: c.User.ID,
Poster: ctx.User, Poster: c.User,
MilestoneID: milestoneID, MilestoneID: milestoneID,
AssigneeID: assigneeID, AssigneeID: assigneeID,
IsPull: true, IsPull: true,
@ -698,55 +698,55 @@ func CompareAndPullRequestPost(ctx *context.Context, f form.NewIssue) {
// FIXME: check error in the case two people send pull request at almost same time, give nice error prompt // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
// instead of 500. // instead of 500.
if err := models.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil { if err := models.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil {
ctx.Handle(500, "NewPullRequest", err) c.Handle(500, "NewPullRequest", err)
return return
} else if err := pullRequest.PushToBaseRepo(); err != nil { } else if err := pullRequest.PushToBaseRepo(); err != nil {
ctx.Handle(500, "PushToBaseRepo", err) c.Handle(500, "PushToBaseRepo", err)
return return
} }
log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID) log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index)) c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
} }
func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) { func parseOwnerAndRepo(c *context.Context) (*models.User, *models.Repository) {
owner, err := models.GetUserByName(ctx.Params(":username")) owner, err := models.GetUserByName(c.Params(":username"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return nil, nil 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 err != nil {
ctx.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err) c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
return nil, nil return nil, nil
} }
return owner, repo return owner, repo
} }
func TriggerTask(ctx *context.Context) { func TriggerTask(c *context.Context) {
pusherID := ctx.QueryInt64("pusher") pusherID := c.QueryInt64("pusher")
branch := ctx.Query("branch") branch := c.Query("branch")
secret := ctx.Query("secret") secret := c.Query("secret")
if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 { if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
ctx.Error(404) c.Error(404)
log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid") log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
return return
} }
owner, repo := parseOwnerAndRepo(ctx) owner, repo := parseOwnerAndRepo(c)
if ctx.Written() { if c.Written() {
return return
} }
if secret != tool.MD5(owner.Salt) { if secret != tool.MD5(owner.Salt) {
ctx.Error(404) c.Error(404)
log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name) log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
return return
} }
pusher, err := models.GetUserByID(pusherID) pusher, err := models.GetUserByID(pusherID)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByID", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByID", errors.IsUserNotExist, err)
return return
} }
@ -754,5 +754,5 @@ func TriggerTask(ctx *context.Context) {
go models.HookQueue.Add(repo.ID) go models.HookQueue.Add(repo.ID)
go models.AddTestPullRequestTask(pusher, repo.ID, branch, true) go models.AddTestPullRequestTask(pusher, repo.ID, branch, true)
ctx.Status(202) c.Status(202)
} }

218
routers/repo/release.go

@ -44,20 +44,20 @@ func calReleaseNumCommitsBehind(repoCtx *context.Repository, release *models.Rel
return nil return nil
} }
func Releases(ctx *context.Context) { func Releases(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.release.releases") c.Data["Title"] = c.Tr("repo.release.releases")
ctx.Data["PageIsViewFiles"] = true c.Data["PageIsViewFiles"] = true
ctx.Data["PageIsReleaseList"] = true c.Data["PageIsReleaseList"] = true
tagsResult, err := ctx.Repo.GitRepo.GetTagsAfter(ctx.Query("after"), 10) tagsResult, err := c.Repo.GitRepo.GetTagsAfter(c.Query("after"), 10)
if err != nil { if err != nil {
ctx.Handle(500, fmt.Sprintf("GetTags '%s'", ctx.Repo.Repository.RepoPath()), err) c.Handle(500, fmt.Sprintf("GetTags '%s'", c.Repo.Repository.RepoPath()), err)
return return
} }
releases, err := models.GetPublishedReleasesByRepoID(ctx.Repo.Repository.ID, tagsResult.Tags...) releases, err := models.GetPublishedReleasesByRepoID(c.Repo.Repository.ID, tagsResult.Tags...)
if err != nil { if err != nil {
ctx.Handle(500, "GetPublishedReleasesByRepoID", err) c.Handle(500, "GetPublishedReleasesByRepoID", err)
return return
} }
@ -73,25 +73,25 @@ func Releases(ctx *context.Context) {
releases[j] = nil // Mark as used. releases[j] = nil // Mark as used.
if err = r.LoadAttributes(); err != nil { if err = r.LoadAttributes(); err != nil {
ctx.Handle(500, "LoadAttributes", err) c.Handle(500, "LoadAttributes", err)
return return
} }
if err := calReleaseNumCommitsBehind(ctx.Repo, r, countCache); err != nil { if err := calReleaseNumCommitsBehind(c.Repo, r, countCache); err != nil {
ctx.Handle(500, "calReleaseNumCommitsBehind", err) c.Handle(500, "calReleaseNumCommitsBehind", err)
return return
} }
r.Note = string(markup.Markdown(r.Note, ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas())) r.Note = string(markup.Markdown(r.Note, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
results[i] = r results[i] = r
break break
} }
// No published release matches this tag // No published release matches this tag
if results[i] == nil { if results[i] == nil {
commit, err := ctx.Repo.GitRepo.GetTagCommit(rawTag) commit, err := c.Repo.GitRepo.GetTagCommit(rawTag)
if err != nil { if err != nil {
ctx.Handle(500, "GetTagCommit", err) c.Handle(500, "GetTagCommit", err)
return return
} }
@ -103,10 +103,10 @@ func Releases(ctx *context.Context) {
results[i].NumCommits, err = commit.CommitsCount() results[i].NumCommits, err = commit.CommitsCount()
if err != nil { if err != nil {
ctx.Handle(500, "CommitsCount", err) c.Handle(500, "CommitsCount", err)
return return
} }
results[i].NumCommitsBehind = ctx.Repo.CommitsCount - results[i].NumCommits results[i].NumCommitsBehind = c.Repo.CommitsCount - results[i].NumCommits
} }
} }
models.SortReleases(results) models.SortReleases(results)
@ -114,24 +114,24 @@ func Releases(ctx *context.Context) {
// Only show drafts if user is viewing the latest page // Only show drafts if user is viewing the latest page
var drafts []*models.Release var drafts []*models.Release
if tagsResult.HasLatest { if tagsResult.HasLatest {
drafts, err = models.GetDraftReleasesByRepoID(ctx.Repo.Repository.ID) drafts, err = models.GetDraftReleasesByRepoID(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Handle(500, "GetDraftReleasesByRepoID", err) c.Handle(500, "GetDraftReleasesByRepoID", err)
return return
} }
for _, r := range drafts { for _, r := range drafts {
if err = r.LoadAttributes(); err != nil { if err = r.LoadAttributes(); err != nil {
ctx.Handle(500, "LoadAttributes", err) c.Handle(500, "LoadAttributes", err)
return return
} }
if err := calReleaseNumCommitsBehind(ctx.Repo, r, countCache); err != nil { if err := calReleaseNumCommitsBehind(c.Repo, r, countCache); err != nil {
ctx.Handle(500, "calReleaseNumCommitsBehind", err) c.Handle(500, "calReleaseNumCommitsBehind", err)
return return
} }
r.Note = string(markup.Markdown(r.Note, ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas())) r.Note = string(markup.Markdown(r.Note, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
} }
if len(drafts) > 0 { if len(drafts) > 0 {
@ -139,50 +139,50 @@ func Releases(ctx *context.Context) {
} }
} }
ctx.Data["Releases"] = results c.Data["Releases"] = results
ctx.Data["HasPrevious"] = !tagsResult.HasLatest c.Data["HasPrevious"] = !tagsResult.HasLatest
ctx.Data["ReachEnd"] = tagsResult.ReachEnd c.Data["ReachEnd"] = tagsResult.ReachEnd
ctx.Data["PreviousAfter"] = tagsResult.PreviousAfter c.Data["PreviousAfter"] = tagsResult.PreviousAfter
if len(results) > 0 { if len(results) > 0 {
ctx.Data["NextAfter"] = results[len(results)-1].TagName c.Data["NextAfter"] = results[len(results)-1].TagName
} }
ctx.HTML(200, RELEASES) c.HTML(200, RELEASES)
} }
func renderReleaseAttachmentSettings(ctx *context.Context) { func renderReleaseAttachmentSettings(c *context.Context) {
ctx.Data["RequireDropzone"] = true c.Data["RequireDropzone"] = true
ctx.Data["IsAttachmentEnabled"] = setting.Release.Attachment.Enabled c.Data["IsAttachmentEnabled"] = setting.Release.Attachment.Enabled
ctx.Data["AttachmentAllowedTypes"] = strings.Join(setting.Release.Attachment.AllowedTypes, ",") c.Data["AttachmentAllowedTypes"] = strings.Join(setting.Release.Attachment.AllowedTypes, ",")
ctx.Data["AttachmentMaxSize"] = setting.Release.Attachment.MaxSize c.Data["AttachmentMaxSize"] = setting.Release.Attachment.MaxSize
ctx.Data["AttachmentMaxFiles"] = setting.Release.Attachment.MaxFiles c.Data["AttachmentMaxFiles"] = setting.Release.Attachment.MaxFiles
} }
func NewRelease(ctx *context.Context) { func NewRelease(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.release.new_release") c.Data["Title"] = c.Tr("repo.release.new_release")
ctx.Data["PageIsReleaseList"] = true c.Data["PageIsReleaseList"] = true
ctx.Data["tag_target"] = ctx.Repo.Repository.DefaultBranch c.Data["tag_target"] = c.Repo.Repository.DefaultBranch
renderReleaseAttachmentSettings(ctx) renderReleaseAttachmentSettings(c)
ctx.HTML(200, RELEASE_NEW) c.HTML(200, RELEASE_NEW)
} }
func NewReleasePost(ctx *context.Context, f form.NewRelease) { func NewReleasePost(c *context.Context, f form.NewRelease) {
ctx.Data["Title"] = ctx.Tr("repo.release.new_release") c.Data["Title"] = c.Tr("repo.release.new_release")
ctx.Data["PageIsReleaseList"] = true c.Data["PageIsReleaseList"] = true
renderReleaseAttachmentSettings(ctx) renderReleaseAttachmentSettings(c)
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, RELEASE_NEW) c.HTML(200, RELEASE_NEW)
return return
} }
if !ctx.Repo.GitRepo.IsBranchExist(f.Target) { if !c.Repo.GitRepo.IsBranchExist(f.Target) {
ctx.RenderWithErr(ctx.Tr("form.target_branch_not_exist"), RELEASE_NEW, &f) c.RenderWithErr(c.Tr("form.target_branch_not_exist"), RELEASE_NEW, &f)
return return
} }
// Use current time if tag not yet exist, otherwise get time from Git // Use current time if tag not yet exist, otherwise get time from Git
var tagCreatedUnix int64 var tagCreatedUnix int64
tag, err := ctx.Repo.GitRepo.GetTag(f.TagName) tag, err := c.Repo.GitRepo.GetTag(f.TagName)
if err == nil { if err == nil {
commit, err := tag.Commit() commit, err := tag.Commit()
if err == nil { if err == nil {
@ -190,15 +190,15 @@ func NewReleasePost(ctx *context.Context, f form.NewRelease) {
} }
} }
commit, err := ctx.Repo.GitRepo.GetBranchCommit(f.Target) commit, err := c.Repo.GitRepo.GetBranchCommit(f.Target)
if err != nil { if err != nil {
ctx.Handle(500, "GetBranchCommit", err) c.Handle(500, "GetBranchCommit", err)
return return
} }
commitsCount, err := commit.CommitsCount() commitsCount, err := commit.CommitsCount()
if err != nil { if err != nil {
ctx.Handle(500, "CommitsCount", err) c.Handle(500, "CommitsCount", err)
return return
} }
@ -208,8 +208,8 @@ func NewReleasePost(ctx *context.Context, f form.NewRelease) {
} }
rel := &models.Release{ rel := &models.Release{
RepoID: ctx.Repo.Repository.ID, RepoID: c.Repo.Repository.ID,
PublisherID: ctx.User.ID, PublisherID: c.User.ID,
Title: f.Title, Title: f.Title,
TagName: f.TagName, TagName: f.TagName,
Target: f.Target, Target: f.Target,
@ -220,77 +220,77 @@ func NewReleasePost(ctx *context.Context, f form.NewRelease) {
IsPrerelease: f.Prerelease, IsPrerelease: f.Prerelease,
CreatedUnix: tagCreatedUnix, CreatedUnix: tagCreatedUnix,
} }
if err = models.NewRelease(ctx.Repo.GitRepo, rel, attachments); err != nil { if err = models.NewRelease(c.Repo.GitRepo, rel, attachments); err != nil {
ctx.Data["Err_TagName"] = true c.Data["Err_TagName"] = true
switch { switch {
case models.IsErrReleaseAlreadyExist(err): case models.IsErrReleaseAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_already_exist"), RELEASE_NEW, &f) c.RenderWithErr(c.Tr("repo.release.tag_name_already_exist"), RELEASE_NEW, &f)
case models.IsErrInvalidTagName(err): case models.IsErrInvalidTagName(err):
ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_invalid"), RELEASE_NEW, &f) c.RenderWithErr(c.Tr("repo.release.tag_name_invalid"), RELEASE_NEW, &f)
default: default:
ctx.Handle(500, "NewRelease", err) c.Handle(500, "NewRelease", err)
} }
return return
} }
log.Trace("Release created: %s/%s:%s", ctx.User.LowerName, ctx.Repo.Repository.Name, f.TagName) log.Trace("Release created: %s/%s:%s", c.User.LowerName, c.Repo.Repository.Name, f.TagName)
ctx.Redirect(ctx.Repo.RepoLink + "/releases") c.Redirect(c.Repo.RepoLink + "/releases")
} }
func EditRelease(ctx *context.Context) { func EditRelease(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.release.edit_release") c.Data["Title"] = c.Tr("repo.release.edit_release")
ctx.Data["PageIsReleaseList"] = true c.Data["PageIsReleaseList"] = true
ctx.Data["PageIsEditRelease"] = true c.Data["PageIsEditRelease"] = true
renderReleaseAttachmentSettings(ctx) renderReleaseAttachmentSettings(c)
tagName := ctx.Params("*") tagName := c.Params("*")
rel, err := models.GetRelease(ctx.Repo.Repository.ID, tagName) rel, err := models.GetRelease(c.Repo.Repository.ID, tagName)
if err != nil { if err != nil {
if models.IsErrReleaseNotExist(err) { if models.IsErrReleaseNotExist(err) {
ctx.Handle(404, "GetRelease", err) c.Handle(404, "GetRelease", err)
} else { } else {
ctx.Handle(500, "GetRelease", err) c.Handle(500, "GetRelease", err)
} }
return return
} }
ctx.Data["ID"] = rel.ID c.Data["ID"] = rel.ID
ctx.Data["tag_name"] = rel.TagName c.Data["tag_name"] = rel.TagName
ctx.Data["tag_target"] = rel.Target c.Data["tag_target"] = rel.Target
ctx.Data["title"] = rel.Title c.Data["title"] = rel.Title
ctx.Data["content"] = rel.Note c.Data["content"] = rel.Note
ctx.Data["attachments"] = rel.Attachments c.Data["attachments"] = rel.Attachments
ctx.Data["prerelease"] = rel.IsPrerelease c.Data["prerelease"] = rel.IsPrerelease
ctx.Data["IsDraft"] = rel.IsDraft c.Data["IsDraft"] = rel.IsDraft
ctx.HTML(200, RELEASE_NEW) c.HTML(200, RELEASE_NEW)
} }
func EditReleasePost(ctx *context.Context, f form.EditRelease) { func EditReleasePost(c *context.Context, f form.EditRelease) {
ctx.Data["Title"] = ctx.Tr("repo.release.edit_release") c.Data["Title"] = c.Tr("repo.release.edit_release")
ctx.Data["PageIsReleaseList"] = true c.Data["PageIsReleaseList"] = true
ctx.Data["PageIsEditRelease"] = true c.Data["PageIsEditRelease"] = true
renderReleaseAttachmentSettings(ctx) renderReleaseAttachmentSettings(c)
tagName := ctx.Params("*") tagName := c.Params("*")
rel, err := models.GetRelease(ctx.Repo.Repository.ID, tagName) rel, err := models.GetRelease(c.Repo.Repository.ID, tagName)
if err != nil { if err != nil {
if models.IsErrReleaseNotExist(err) { if models.IsErrReleaseNotExist(err) {
ctx.Handle(404, "GetRelease", err) c.Handle(404, "GetRelease", err)
} else { } else {
ctx.Handle(500, "GetRelease", err) c.Handle(500, "GetRelease", err)
} }
return return
} }
ctx.Data["tag_name"] = rel.TagName c.Data["tag_name"] = rel.TagName
ctx.Data["tag_target"] = rel.Target c.Data["tag_target"] = rel.Target
ctx.Data["title"] = rel.Title c.Data["title"] = rel.Title
ctx.Data["content"] = rel.Note c.Data["content"] = rel.Note
ctx.Data["attachments"] = rel.Attachments c.Data["attachments"] = rel.Attachments
ctx.Data["prerelease"] = rel.IsPrerelease c.Data["prerelease"] = rel.IsPrerelease
ctx.Data["IsDraft"] = rel.IsDraft c.Data["IsDraft"] = rel.IsDraft
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, RELEASE_NEW) c.HTML(200, RELEASE_NEW)
return return
} }
@ -304,29 +304,29 @@ func EditReleasePost(ctx *context.Context, f form.EditRelease) {
rel.Note = f.Content rel.Note = f.Content
rel.IsDraft = len(f.Draft) > 0 rel.IsDraft = len(f.Draft) > 0
rel.IsPrerelease = f.Prerelease rel.IsPrerelease = f.Prerelease
if err = models.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, isPublish, attachments); err != nil { if err = models.UpdateRelease(c.User, c.Repo.GitRepo, rel, isPublish, attachments); err != nil {
ctx.Handle(500, "UpdateRelease", err) c.Handle(500, "UpdateRelease", err)
return return
} }
ctx.Redirect(ctx.Repo.RepoLink + "/releases") c.Redirect(c.Repo.RepoLink + "/releases")
} }
func UploadReleaseAttachment(ctx *context.Context) { func UploadReleaseAttachment(c *context.Context) {
if !setting.Release.Attachment.Enabled { if !setting.Release.Attachment.Enabled {
ctx.NotFound() c.NotFound()
return return
} }
uploadAttachment(ctx, setting.Release.Attachment.AllowedTypes) uploadAttachment(c, setting.Release.Attachment.AllowedTypes)
} }
func DeleteRelease(ctx *context.Context) { func DeleteRelease(c *context.Context) {
if err := models.DeleteReleaseOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil { if err := models.DeleteReleaseOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteReleaseByID: " + err.Error()) c.Flash.Error("DeleteReleaseByID: " + err.Error())
} else { } else {
ctx.Flash.Success(ctx.Tr("repo.release.deletion_success")) c.Flash.Success(c.Tr("repo.release.deletion_success"))
} }
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/releases", "redirect": c.Repo.RepoLink + "/releases",
}) })
} }

212
routers/repo/repo.go

@ -28,100 +28,100 @@ const (
MIGRATE = "repo/migrate" MIGRATE = "repo/migrate"
) )
func MustBeNotBare(ctx *context.Context) { func MustBeNotBare(c *context.Context) {
if ctx.Repo.Repository.IsBare { if c.Repo.Repository.IsBare {
ctx.Handle(404, "MustBeNotBare", nil) c.Handle(404, "MustBeNotBare", nil)
} }
} }
func checkContextUser(ctx *context.Context, uid int64) *models.User { func checkContextUser(c *context.Context, uid int64) *models.User {
orgs, err := models.GetOwnedOrgsByUserIDDesc(ctx.User.ID, "updated_unix") orgs, err := models.GetOwnedOrgsByUserIDDesc(c.User.ID, "updated_unix")
if err != nil { if err != nil {
ctx.Handle(500, "GetOwnedOrgsByUserIDDesc", err) c.Handle(500, "GetOwnedOrgsByUserIDDesc", err)
return nil return nil
} }
ctx.Data["Orgs"] = orgs c.Data["Orgs"] = orgs
// Not equal means current user is an organization. // Not equal means current user is an organization.
if uid == ctx.User.ID || uid == 0 { if uid == c.User.ID || uid == 0 {
return ctx.User return c.User
} }
org, err := models.GetUserByID(uid) org, err := models.GetUserByID(uid)
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
return ctx.User return c.User
} }
if err != nil { if err != nil {
ctx.Handle(500, "GetUserByID", fmt.Errorf("[%d]: %v", uid, err)) c.Handle(500, "GetUserByID", fmt.Errorf("[%d]: %v", uid, err))
return nil return nil
} }
// Check ownership of organization. // Check ownership of organization.
if !org.IsOrganization() || !(ctx.User.IsAdmin || org.IsOwnedBy(ctx.User.ID)) { if !org.IsOrganization() || !(c.User.IsAdmin || org.IsOwnedBy(c.User.ID)) {
ctx.Error(403) c.Error(403)
return nil return nil
} }
return org return org
} }
func Create(ctx *context.Context) { func Create(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("new_repo") c.Data["Title"] = c.Tr("new_repo")
// Give default value for template to render. // Give default value for template to render.
ctx.Data["Gitignores"] = models.Gitignores c.Data["Gitignores"] = models.Gitignores
ctx.Data["Licenses"] = models.Licenses c.Data["Licenses"] = models.Licenses
ctx.Data["Readmes"] = models.Readmes c.Data["Readmes"] = models.Readmes
ctx.Data["readme"] = "Default" c.Data["readme"] = "Default"
ctx.Data["private"] = ctx.User.LastRepoVisibility c.Data["private"] = c.User.LastRepoVisibility
ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate c.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
ctxUser := checkContextUser(ctx, ctx.QueryInt64("org")) ctxUser := checkContextUser(c, c.QueryInt64("org"))
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["ContextUser"] = ctxUser c.Data["ContextUser"] = ctxUser
ctx.HTML(200, CREATE) c.HTML(200, CREATE)
} }
func handleCreateError(ctx *context.Context, owner *models.User, err error, name, tpl string, form interface{}) { func handleCreateError(c *context.Context, owner *models.User, err error, name, tpl string, form interface{}) {
switch { switch {
case errors.IsReachLimitOfRepo(err): case errors.IsReachLimitOfRepo(err):
ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_creation", owner.RepoCreationNum()), tpl, form) c.RenderWithErr(c.Tr("repo.form.reach_limit_of_creation", owner.RepoCreationNum()), tpl, form)
case models.IsErrRepoAlreadyExist(err): case models.IsErrRepoAlreadyExist(err):
ctx.Data["Err_RepoName"] = true c.Data["Err_RepoName"] = true
ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form) c.RenderWithErr(c.Tr("form.repo_name_been_taken"), tpl, form)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.Data["Err_RepoName"] = true c.Data["Err_RepoName"] = true
ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form) c.RenderWithErr(c.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_RepoName"] = true c.Data["Err_RepoName"] = true
ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form) c.RenderWithErr(c.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
default: default:
ctx.Handle(500, name, err) c.Handle(500, name, err)
} }
} }
func CreatePost(ctx *context.Context, f form.CreateRepo) { func CreatePost(c *context.Context, f form.CreateRepo) {
ctx.Data["Title"] = ctx.Tr("new_repo") c.Data["Title"] = c.Tr("new_repo")
ctx.Data["Gitignores"] = models.Gitignores c.Data["Gitignores"] = models.Gitignores
ctx.Data["Licenses"] = models.Licenses c.Data["Licenses"] = models.Licenses
ctx.Data["Readmes"] = models.Readmes c.Data["Readmes"] = models.Readmes
ctxUser := checkContextUser(ctx, f.UserID) ctxUser := checkContextUser(c, f.UserID)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["ContextUser"] = ctxUser c.Data["ContextUser"] = ctxUser
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, CREATE) c.HTML(200, CREATE)
return return
} }
repo, err := models.CreateRepository(ctx.User, ctxUser, models.CreateRepoOptions{ repo, err := models.CreateRepository(c.User, ctxUser, models.CreateRepoOptions{
Name: f.RepoName, Name: f.RepoName,
Description: f.Description, Description: f.Description,
Gitignores: f.Gitignores, Gitignores: f.Gitignores,
@ -132,7 +132,7 @@ func CreatePost(ctx *context.Context, f form.CreateRepo) {
}) })
if err == nil { if err == nil {
log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name) c.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
return return
} }
@ -142,60 +142,60 @@ func CreatePost(ctx *context.Context, f form.CreateRepo) {
} }
} }
handleCreateError(ctx, ctxUser, err, "CreatePost", CREATE, &f) handleCreateError(c, ctxUser, err, "CreatePost", CREATE, &f)
} }
func Migrate(ctx *context.Context) { func Migrate(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("new_migrate") c.Data["Title"] = c.Tr("new_migrate")
ctx.Data["private"] = ctx.User.LastRepoVisibility c.Data["private"] = c.User.LastRepoVisibility
ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate c.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
ctx.Data["mirror"] = ctx.Query("mirror") == "1" c.Data["mirror"] = c.Query("mirror") == "1"
ctxUser := checkContextUser(ctx, ctx.QueryInt64("org")) ctxUser := checkContextUser(c, c.QueryInt64("org"))
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["ContextUser"] = ctxUser c.Data["ContextUser"] = ctxUser
ctx.HTML(200, MIGRATE) c.HTML(200, MIGRATE)
} }
func MigratePost(ctx *context.Context, f form.MigrateRepo) { func MigratePost(c *context.Context, f form.MigrateRepo) {
ctx.Data["Title"] = ctx.Tr("new_migrate") c.Data["Title"] = c.Tr("new_migrate")
ctxUser := checkContextUser(ctx, f.Uid) ctxUser := checkContextUser(c, f.Uid)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["ContextUser"] = ctxUser c.Data["ContextUser"] = ctxUser
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, MIGRATE) c.HTML(200, MIGRATE)
return return
} }
remoteAddr, err := f.ParseRemoteAddr(ctx.User) remoteAddr, err := f.ParseRemoteAddr(c.User)
if err != nil { if err != nil {
if models.IsErrInvalidCloneAddr(err) { if models.IsErrInvalidCloneAddr(err) {
ctx.Data["Err_CloneAddr"] = true c.Data["Err_CloneAddr"] = true
addrErr := err.(models.ErrInvalidCloneAddr) addrErr := err.(models.ErrInvalidCloneAddr)
switch { switch {
case addrErr.IsURLError: case addrErr.IsURLError:
ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &f) c.RenderWithErr(c.Tr("form.url_error"), MIGRATE, &f)
case addrErr.IsPermissionDenied: case addrErr.IsPermissionDenied:
ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), MIGRATE, &f) c.RenderWithErr(c.Tr("repo.migrate.permission_denied"), MIGRATE, &f)
case addrErr.IsInvalidPath: case addrErr.IsInvalidPath:
ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f) c.RenderWithErr(c.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f)
default: default:
ctx.Handle(500, "Unknown error", err) c.Handle(500, "Unknown error", err)
} }
} else { } else {
ctx.Handle(500, "ParseRemoteAddr", err) c.Handle(500, "ParseRemoteAddr", err)
} }
return return
} }
repo, err := models.MigrateRepository(ctx.User, ctxUser, models.MigrateRepoOptions{ repo, err := models.MigrateRepository(c.User, ctxUser, models.MigrateRepoOptions{
Name: f.RepoName, Name: f.RepoName,
Description: f.Description, Description: f.Description,
IsPrivate: f.Private || setting.Repository.ForcePrivate, IsPrivate: f.Private || setting.Repository.ForcePrivate,
@ -204,7 +204,7 @@ func MigratePost(ctx *context.Context, f form.MigrateRepo) {
}) })
if err == nil { if err == nil {
log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, f.RepoName) log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, f.RepoName)
ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + f.RepoName) c.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + f.RepoName)
return return
} }
@ -216,55 +216,55 @@ func MigratePost(ctx *context.Context, f form.MigrateRepo) {
if strings.Contains(err.Error(), "Authentication failed") || if strings.Contains(err.Error(), "Authentication failed") ||
strings.Contains(err.Error(), "could not read Username") { strings.Contains(err.Error(), "could not read Username") {
ctx.Data["Err_Auth"] = true c.Data["Err_Auth"] = true
ctx.RenderWithErr(ctx.Tr("form.auth_failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f) c.RenderWithErr(c.Tr("form.auth_failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
return return
} else if strings.Contains(err.Error(), "fatal:") { } else if strings.Contains(err.Error(), "fatal:") {
ctx.Data["Err_CloneAddr"] = true c.Data["Err_CloneAddr"] = true
ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f) c.RenderWithErr(c.Tr("repo.migrate.failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
return return
} }
handleCreateError(ctx, ctxUser, err, "MigratePost", MIGRATE, &f) handleCreateError(c, ctxUser, err, "MigratePost", MIGRATE, &f)
} }
func Action(ctx *context.Context) { func Action(c *context.Context) {
var err error var err error
switch ctx.Params(":action") { switch c.Params(":action") {
case "watch": case "watch":
err = models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, true) err = models.WatchRepo(c.User.ID, c.Repo.Repository.ID, true)
case "unwatch": case "unwatch":
err = models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, false) err = models.WatchRepo(c.User.ID, c.Repo.Repository.ID, false)
case "star": case "star":
err = models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, true) err = models.StarRepo(c.User.ID, c.Repo.Repository.ID, true)
case "unstar": case "unstar":
err = models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, false) err = models.StarRepo(c.User.ID, c.Repo.Repository.ID, false)
case "desc": // FIXME: this is not used case "desc": // FIXME: this is not used
if !ctx.Repo.IsOwner() { if !c.Repo.IsOwner() {
ctx.Error(404) c.Error(404)
return return
} }
ctx.Repo.Repository.Description = ctx.Query("desc") c.Repo.Repository.Description = c.Query("desc")
ctx.Repo.Repository.Website = ctx.Query("site") c.Repo.Repository.Website = c.Query("site")
err = models.UpdateRepository(ctx.Repo.Repository, false) err = models.UpdateRepository(c.Repo.Repository, false)
} }
if err != nil { if err != nil {
ctx.Handle(500, fmt.Sprintf("Action (%s)", ctx.Params(":action")), err) c.Handle(500, fmt.Sprintf("Action (%s)", c.Params(":action")), err)
return return
} }
redirectTo := ctx.Query("redirect_to") redirectTo := c.Query("redirect_to")
if len(redirectTo) == 0 { if len(redirectTo) == 0 {
redirectTo = ctx.Repo.RepoLink redirectTo = c.Repo.RepoLink
} }
ctx.Redirect(redirectTo) c.Redirect(redirectTo)
} }
func Download(ctx *context.Context) { func Download(c *context.Context) {
var ( var (
uri = ctx.Params("*") uri = c.Params("*")
refName string refName string
ext string ext string
archivePath string archivePath string
@ -274,22 +274,22 @@ func Download(ctx *context.Context) {
switch { switch {
case strings.HasSuffix(uri, ".zip"): case strings.HasSuffix(uri, ".zip"):
ext = ".zip" ext = ".zip"
archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/zip") archivePath = path.Join(c.Repo.GitRepo.Path, "archives/zip")
archiveType = git.ZIP archiveType = git.ZIP
case strings.HasSuffix(uri, ".tar.gz"): case strings.HasSuffix(uri, ".tar.gz"):
ext = ".tar.gz" ext = ".tar.gz"
archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/targz") archivePath = path.Join(c.Repo.GitRepo.Path, "archives/targz")
archiveType = git.TARGZ archiveType = git.TARGZ
default: default:
log.Trace("Unknown format: %s", uri) log.Trace("Unknown format: %s", uri)
ctx.Error(404) c.Error(404)
return return
} }
refName = strings.TrimSuffix(uri, ext) refName = strings.TrimSuffix(uri, ext)
if !com.IsDir(archivePath) { if !com.IsDir(archivePath) {
if err := os.MkdirAll(archivePath, os.ModePerm); err != nil { if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
ctx.Handle(500, "Download -> os.MkdirAll(archivePath)", err) c.Handle(500, "Download -> os.MkdirAll(archivePath)", err)
return return
} }
} }
@ -299,37 +299,37 @@ func Download(ctx *context.Context) {
commit *git.Commit commit *git.Commit
err error err error
) )
gitRepo := ctx.Repo.GitRepo gitRepo := c.Repo.GitRepo
if gitRepo.IsBranchExist(refName) { if gitRepo.IsBranchExist(refName) {
commit, err = gitRepo.GetBranchCommit(refName) commit, err = gitRepo.GetBranchCommit(refName)
if err != nil { if err != nil {
ctx.Handle(500, "GetBranchCommit", err) c.Handle(500, "GetBranchCommit", err)
return return
} }
} else if gitRepo.IsTagExist(refName) { } else if gitRepo.IsTagExist(refName) {
commit, err = gitRepo.GetTagCommit(refName) commit, err = gitRepo.GetTagCommit(refName)
if err != nil { if err != nil {
ctx.Handle(500, "GetTagCommit", err) c.Handle(500, "GetTagCommit", err)
return return
} }
} else if len(refName) >= 7 && len(refName) <= 40 { } else if len(refName) >= 7 && len(refName) <= 40 {
commit, err = gitRepo.GetCommit(refName) commit, err = gitRepo.GetCommit(refName)
if err != nil { if err != nil {
ctx.NotFound() c.NotFound()
return return
} }
} else { } else {
ctx.NotFound() c.NotFound()
return return
} }
archivePath = path.Join(archivePath, tool.ShortSHA1(commit.ID.String())+ext) archivePath = path.Join(archivePath, tool.ShortSHA1(commit.ID.String())+ext)
if !com.IsFile(archivePath) { if !com.IsFile(archivePath) {
if err := commit.CreateArchive(archivePath, archiveType); err != nil { if err := commit.CreateArchive(archivePath, archiveType); err != nil {
ctx.Handle(500, "Download -> CreateArchive "+archivePath, err) c.Handle(500, "Download -> CreateArchive "+archivePath, err)
return return
} }
} }
ctx.ServeFile(archivePath, ctx.Repo.Repository.Name+"-"+refName+ext) c.ServeFile(archivePath, c.Repo.Repository.Name+"-"+refName+ext)
} }

476
routers/repo/setting.go

@ -31,22 +31,22 @@ const (
SETTINGS_DEPLOY_KEYS = "repo/settings/deploy_keys" SETTINGS_DEPLOY_KEYS = "repo/settings/deploy_keys"
) )
func Settings(ctx *context.Context) { func Settings(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings") c.Data["Title"] = c.Tr("repo.settings")
ctx.Data["PageIsSettingsOptions"] = true c.Data["PageIsSettingsOptions"] = true
ctx.HTML(200, SETTINGS_OPTIONS) c.HTML(200, SETTINGS_OPTIONS)
} }
func SettingsPost(ctx *context.Context, f form.RepoSetting) { func SettingsPost(c *context.Context, f form.RepoSetting) {
ctx.Data["Title"] = ctx.Tr("repo.settings") c.Data["Title"] = c.Tr("repo.settings")
ctx.Data["PageIsSettingsOptions"] = true c.Data["PageIsSettingsOptions"] = true
repo := ctx.Repo.Repository repo := c.Repo.Repository
switch ctx.Query("action") { switch c.Query("action") {
case "update": case "update":
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, SETTINGS_OPTIONS) c.HTML(200, SETTINGS_OPTIONS)
return return
} }
@ -56,22 +56,22 @@ func SettingsPost(ctx *context.Context, f form.RepoSetting) {
// Check if repository name has been changed. // Check if repository name has been changed.
if repo.LowerName != strings.ToLower(newRepoName) { if repo.LowerName != strings.ToLower(newRepoName) {
isNameChanged = true isNameChanged = true
if err := models.ChangeRepositoryName(ctx.Repo.Owner, repo.Name, newRepoName); err != nil { if err := models.ChangeRepositoryName(c.Repo.Owner, repo.Name, newRepoName); err != nil {
ctx.Data["Err_RepoName"] = true c.Data["Err_RepoName"] = true
switch { switch {
case models.IsErrRepoAlreadyExist(err): case models.IsErrRepoAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), SETTINGS_OPTIONS, &f) c.RenderWithErr(c.Tr("form.repo_name_been_taken"), SETTINGS_OPTIONS, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), SETTINGS_OPTIONS, &f) c.RenderWithErr(c.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), SETTINGS_OPTIONS, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SETTINGS_OPTIONS, &f) c.RenderWithErr(c.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SETTINGS_OPTIONS, &f)
default: default:
ctx.Handle(500, "ChangeRepositoryName", err) c.Handle(500, "ChangeRepositoryName", err)
} }
return return
} }
log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName) log.Trace("Repository name changed: %s/%s -> %s", c.Repo.Owner.Name, repo.Name, newRepoName)
} }
// In case it's just a case change. // In case it's just a case change.
repo.Name = newRepoName repo.Name = newRepoName
@ -88,52 +88,52 @@ func SettingsPost(ctx *context.Context, f form.RepoSetting) {
visibilityChanged := repo.IsPrivate != f.Private visibilityChanged := repo.IsPrivate != f.Private
repo.IsPrivate = f.Private repo.IsPrivate = f.Private
if err := models.UpdateRepository(repo, visibilityChanged); err != nil { if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
ctx.Handle(500, "UpdateRepository", err) c.Handle(500, "UpdateRepository", err)
return return
} }
log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name) log.Trace("Repository basic settings updated: %s/%s", c.Repo.Owner.Name, repo.Name)
if isNameChanged { if isNameChanged {
if err := models.RenameRepoAction(ctx.User, oldRepoName, repo); err != nil { if err := models.RenameRepoAction(c.User, oldRepoName, repo); err != nil {
log.Error(4, "RenameRepoAction: %v", err) log.Error(4, "RenameRepoAction: %v", err)
} }
} }
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success")) c.Flash.Success(c.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings") c.Redirect(repo.Link() + "/settings")
case "mirror": case "mirror":
if !repo.IsMirror { if !repo.IsMirror {
ctx.Handle(404, "", nil) c.Handle(404, "", nil)
return return
} }
if f.Interval > 0 { if f.Interval > 0 {
ctx.Repo.Mirror.EnablePrune = f.EnablePrune c.Repo.Mirror.EnablePrune = f.EnablePrune
ctx.Repo.Mirror.Interval = f.Interval c.Repo.Mirror.Interval = f.Interval
ctx.Repo.Mirror.NextUpdate = time.Now().Add(time.Duration(f.Interval) * time.Hour) c.Repo.Mirror.NextUpdate = time.Now().Add(time.Duration(f.Interval) * time.Hour)
if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil { if err := models.UpdateMirror(c.Repo.Mirror); err != nil {
ctx.Handle(500, "UpdateMirror", err) c.Handle(500, "UpdateMirror", err)
return return
} }
} }
if err := ctx.Repo.Mirror.SaveAddress(f.MirrorAddress); err != nil { if err := c.Repo.Mirror.SaveAddress(f.MirrorAddress); err != nil {
ctx.Handle(500, "SaveAddress", err) c.Handle(500, "SaveAddress", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success")) c.Flash.Success(c.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings") c.Redirect(repo.Link() + "/settings")
case "mirror-sync": case "mirror-sync":
if !repo.IsMirror { if !repo.IsMirror {
ctx.Handle(404, "", nil) c.Handle(404, "", nil)
return return
} }
go models.MirrorQueue.Add(repo.ID) go models.MirrorQueue.Add(repo.ID)
ctx.Flash.Info(ctx.Tr("repo.settings.mirror_sync_in_progress")) c.Flash.Info(c.Tr("repo.settings.mirror_sync_in_progress"))
ctx.Redirect(repo.Link() + "/settings") c.Redirect(repo.Link() + "/settings")
case "advanced": case "advanced":
repo.EnableWiki = f.EnableWiki repo.EnableWiki = f.EnableWiki
@ -149,290 +149,290 @@ func SettingsPost(ctx *context.Context, f form.RepoSetting) {
repo.EnablePulls = f.EnablePulls repo.EnablePulls = f.EnablePulls
if err := models.UpdateRepository(repo, false); err != nil { if err := models.UpdateRepository(repo, false); err != nil {
ctx.Handle(500, "UpdateRepository", err) c.Handle(500, "UpdateRepository", err)
return return
} }
log.Trace("Repository advanced settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name) log.Trace("Repository advanced settings updated: %s/%s", c.Repo.Owner.Name, repo.Name)
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success")) c.Flash.Success(c.Tr("repo.settings.update_settings_success"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings") c.Redirect(c.Repo.RepoLink + "/settings")
case "convert": case "convert":
if !ctx.Repo.IsOwner() { if !c.Repo.IsOwner() {
ctx.Error(404) c.Error(404)
return return
} }
if repo.Name != f.RepoName { if repo.Name != f.RepoName {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil)
return return
} }
if ctx.Repo.Owner.IsOrganization() { if c.Repo.Owner.IsOrganization() {
if !ctx.Repo.Owner.IsOwnedBy(ctx.User.ID) { if !c.Repo.Owner.IsOwnedBy(c.User.ID) {
ctx.Error(404) c.Error(404)
return return
} }
} }
if !repo.IsMirror { if !repo.IsMirror {
ctx.Error(404) c.Error(404)
return return
} }
repo.IsMirror = false repo.IsMirror = false
if _, err := models.CleanUpMigrateInfo(repo); err != nil { if _, err := models.CleanUpMigrateInfo(repo); err != nil {
ctx.Handle(500, "CleanUpMigrateInfo", err) c.Handle(500, "CleanUpMigrateInfo", err)
return return
} else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil { } else if err = models.DeleteMirrorByRepoID(c.Repo.Repository.ID); err != nil {
ctx.Handle(500, "DeleteMirrorByRepoID", err) c.Handle(500, "DeleteMirrorByRepoID", err)
return return
} }
log.Trace("Repository converted from mirror to regular: %s/%s", ctx.Repo.Owner.Name, repo.Name) log.Trace("Repository converted from mirror to regular: %s/%s", c.Repo.Owner.Name, repo.Name)
ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed")) c.Flash.Success(c.Tr("repo.settings.convert_succeed"))
ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name) c.Redirect(setting.AppSubURL + "/" + c.Repo.Owner.Name + "/" + repo.Name)
case "transfer": case "transfer":
if !ctx.Repo.IsOwner() { if !c.Repo.IsOwner() {
ctx.Error(404) c.Error(404)
return return
} }
if repo.Name != f.RepoName { if repo.Name != f.RepoName {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil)
return return
} }
if ctx.Repo.Owner.IsOrganization() && !ctx.User.IsAdmin { if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin {
if !ctx.Repo.Owner.IsOwnedBy(ctx.User.ID) { if !c.Repo.Owner.IsOwnedBy(c.User.ID) {
ctx.Error(404) c.Error(404)
return return
} }
} }
newOwner := ctx.Query("new_owner_name") newOwner := c.Query("new_owner_name")
isExist, err := models.IsUserExist(0, newOwner) isExist, err := models.IsUserExist(0, newOwner)
if err != nil { if err != nil {
ctx.Handle(500, "IsUserExist", err) c.Handle(500, "IsUserExist", err)
return return
} else if !isExist { } else if !isExist {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_owner_name"), SETTINGS_OPTIONS, nil)
return return
} }
if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil { if err = models.TransferOwnership(c.User, newOwner, repo); err != nil {
if models.IsErrRepoAlreadyExist(err) { if models.IsErrRepoAlreadyExist(err) {
ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), SETTINGS_OPTIONS, nil)
} else { } else {
ctx.Handle(500, "TransferOwnership", err) c.Handle(500, "TransferOwnership", err)
} }
return return
} }
log.Trace("Repository transfered: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner) log.Trace("Repository transfered: %s/%s -> %s", c.Repo.Owner.Name, repo.Name, newOwner)
ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed")) c.Flash.Success(c.Tr("repo.settings.transfer_succeed"))
ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name) c.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name)
case "delete": case "delete":
if !ctx.Repo.IsOwner() { if !c.Repo.IsOwner() {
ctx.Error(404) c.Error(404)
return return
} }
if repo.Name != f.RepoName { if repo.Name != f.RepoName {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil)
return return
} }
if ctx.Repo.Owner.IsOrganization() && !ctx.User.IsAdmin { if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin {
if !ctx.Repo.Owner.IsOwnedBy(ctx.User.ID) { if !c.Repo.Owner.IsOwnedBy(c.User.ID) {
ctx.Error(404) c.Error(404)
return return
} }
} }
if err := models.DeleteRepository(ctx.Repo.Owner.ID, repo.ID); err != nil { if err := models.DeleteRepository(c.Repo.Owner.ID, repo.ID); err != nil {
ctx.Handle(500, "DeleteRepository", err) c.Handle(500, "DeleteRepository", err)
return return
} }
log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name) log.Trace("Repository deleted: %s/%s", c.Repo.Owner.Name, repo.Name)
ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success")) c.Flash.Success(c.Tr("repo.settings.deletion_success"))
ctx.Redirect(ctx.Repo.Owner.DashboardLink()) c.Redirect(c.Repo.Owner.DashboardLink())
case "delete-wiki": case "delete-wiki":
if !ctx.Repo.IsOwner() { if !c.Repo.IsOwner() {
ctx.Error(404) c.Error(404)
return return
} }
if repo.Name != f.RepoName { if repo.Name != f.RepoName {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil)
return return
} }
if ctx.Repo.Owner.IsOrganization() && !ctx.User.IsAdmin { if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin {
if !ctx.Repo.Owner.IsOwnedBy(ctx.User.ID) { if !c.Repo.Owner.IsOwnedBy(c.User.ID) {
ctx.Error(404) c.Error(404)
return return
} }
} }
repo.DeleteWiki() repo.DeleteWiki()
log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name) log.Trace("Repository wiki deleted: %s/%s", c.Repo.Owner.Name, repo.Name)
repo.EnableWiki = false repo.EnableWiki = false
if err := models.UpdateRepository(repo, false); err != nil { if err := models.UpdateRepository(repo, false); err != nil {
ctx.Handle(500, "UpdateRepository", err) c.Handle(500, "UpdateRepository", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success")) c.Flash.Success(c.Tr("repo.settings.wiki_deletion_success"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings") c.Redirect(c.Repo.RepoLink + "/settings")
default: default:
ctx.Handle(404, "", nil) c.Handle(404, "", nil)
} }
} }
func SettingsCollaboration(ctx *context.Context) { func SettingsCollaboration(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings") c.Data["Title"] = c.Tr("repo.settings")
ctx.Data["PageIsSettingsCollaboration"] = true c.Data["PageIsSettingsCollaboration"] = true
users, err := ctx.Repo.Repository.GetCollaborators() users, err := c.Repo.Repository.GetCollaborators()
if err != nil { if err != nil {
ctx.Handle(500, "GetCollaborators", err) c.Handle(500, "GetCollaborators", err)
return return
} }
ctx.Data["Collaborators"] = users c.Data["Collaborators"] = users
ctx.HTML(200, SETTINGS_COLLABORATION) c.HTML(200, SETTINGS_COLLABORATION)
} }
func SettingsCollaborationPost(ctx *context.Context) { func SettingsCollaborationPost(c *context.Context) {
name := strings.ToLower(ctx.Query("collaborator")) name := strings.ToLower(c.Query("collaborator"))
if len(name) == 0 || ctx.Repo.Owner.LowerName == name { if len(name) == 0 || c.Repo.Owner.LowerName == name {
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path) c.Redirect(setting.AppSubURL + c.Req.URL.Path)
return return
} }
u, err := models.GetUserByName(name) u, err := models.GetUserByName(name)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Flash.Error(ctx.Tr("form.user_not_exist")) c.Flash.Error(c.Tr("form.user_not_exist"))
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path) c.Redirect(setting.AppSubURL + c.Req.URL.Path)
} else { } else {
ctx.Handle(500, "GetUserByName", err) c.Handle(500, "GetUserByName", err)
} }
return return
} }
// Organization is not allowed to be added as a collaborator // Organization is not allowed to be added as a collaborator
if u.IsOrganization() { if u.IsOrganization() {
ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator")) c.Flash.Error(c.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path) c.Redirect(setting.AppSubURL + c.Req.URL.Path)
return return
} }
if err = ctx.Repo.Repository.AddCollaborator(u); err != nil { if err = c.Repo.Repository.AddCollaborator(u); err != nil {
ctx.Handle(500, "AddCollaborator", err) c.Handle(500, "AddCollaborator", err)
return return
} }
if setting.Service.EnableNotifyMail { if setting.Service.EnableNotifyMail {
mailer.SendCollaboratorMail(models.NewMailerUser(u), models.NewMailerUser(ctx.User), models.NewMailerRepo(ctx.Repo.Repository)) mailer.SendCollaboratorMail(models.NewMailerUser(u), models.NewMailerUser(c.User), models.NewMailerRepo(c.Repo.Repository))
} }
ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success")) c.Flash.Success(c.Tr("repo.settings.add_collaborator_success"))
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path) c.Redirect(setting.AppSubURL + c.Req.URL.Path)
} }
func ChangeCollaborationAccessMode(ctx *context.Context) { func ChangeCollaborationAccessMode(c *context.Context) {
if err := ctx.Repo.Repository.ChangeCollaborationAccessMode( if err := c.Repo.Repository.ChangeCollaborationAccessMode(
ctx.QueryInt64("uid"), c.QueryInt64("uid"),
models.AccessMode(ctx.QueryInt("mode"))); err != nil { models.AccessMode(c.QueryInt("mode"))); err != nil {
log.Error(2, "ChangeCollaborationAccessMode: %v", err) log.Error(2, "ChangeCollaborationAccessMode: %v", err)
return return
} }
ctx.Status(204) c.Status(204)
} }
func DeleteCollaboration(ctx *context.Context) { func DeleteCollaboration(c *context.Context) {
if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil { if err := c.Repo.Repository.DeleteCollaboration(c.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteCollaboration: " + err.Error()) c.Flash.Error("DeleteCollaboration: " + err.Error())
} else { } else {
ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success")) c.Flash.Success(c.Tr("repo.settings.remove_collaborator_success"))
} }
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/settings/collaboration", "redirect": c.Repo.RepoLink + "/settings/collaboration",
}) })
} }
func SettingsBranches(ctx *context.Context) { func SettingsBranches(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.branches") c.Data["Title"] = c.Tr("repo.settings.branches")
ctx.Data["PageIsSettingsBranches"] = true c.Data["PageIsSettingsBranches"] = true
if ctx.Repo.Repository.IsBare { if c.Repo.Repository.IsBare {
ctx.Flash.Info(ctx.Tr("repo.settings.branches_bare"), true) c.Flash.Info(c.Tr("repo.settings.branches_bare"), true)
ctx.HTML(200, SETTINGS_BRANCHES) c.HTML(200, SETTINGS_BRANCHES)
return return
} }
protectBranches, err := models.GetProtectBranchesByRepoID(ctx.Repo.Repository.ID) protectBranches, err := models.GetProtectBranchesByRepoID(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Handle(500, "GetProtectBranchesByRepoID", err) c.Handle(500, "GetProtectBranchesByRepoID", err)
return return
} }
// Filter out deleted branches // Filter out deleted branches
branches := make([]string, 0, len(protectBranches)) branches := make([]string, 0, len(protectBranches))
for i := range protectBranches { for i := range protectBranches {
if ctx.Repo.GitRepo.IsBranchExist(protectBranches[i].Name) { if c.Repo.GitRepo.IsBranchExist(protectBranches[i].Name) {
branches = append(branches, protectBranches[i].Name) branches = append(branches, protectBranches[i].Name)
} }
} }
ctx.Data["ProtectBranches"] = branches c.Data["ProtectBranches"] = branches
ctx.HTML(200, SETTINGS_BRANCHES) c.HTML(200, SETTINGS_BRANCHES)
} }
func UpdateDefaultBranch(ctx *context.Context) { func UpdateDefaultBranch(c *context.Context) {
branch := ctx.Query("branch") branch := c.Query("branch")
if ctx.Repo.GitRepo.IsBranchExist(branch) && if c.Repo.GitRepo.IsBranchExist(branch) &&
ctx.Repo.Repository.DefaultBranch != branch { c.Repo.Repository.DefaultBranch != branch {
ctx.Repo.Repository.DefaultBranch = branch c.Repo.Repository.DefaultBranch = branch
if err := ctx.Repo.GitRepo.SetDefaultBranch(branch); err != nil { if err := c.Repo.GitRepo.SetDefaultBranch(branch); err != nil {
if !git.IsErrUnsupportedVersion(err) { if !git.IsErrUnsupportedVersion(err) {
ctx.Handle(500, "SetDefaultBranch", err) c.Handle(500, "SetDefaultBranch", err)
return return
} }
ctx.Flash.Warning(ctx.Tr("repo.settings.update_default_branch_unsupported")) c.Flash.Warning(c.Tr("repo.settings.update_default_branch_unsupported"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/branches") c.Redirect(c.Repo.RepoLink + "/settings/branches")
return return
} }
} }
if err := models.UpdateRepository(ctx.Repo.Repository, false); err != nil { if err := models.UpdateRepository(c.Repo.Repository, false); err != nil {
ctx.Handle(500, "UpdateRepository", err) c.Handle(500, "UpdateRepository", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.update_default_branch_success")) c.Flash.Success(c.Tr("repo.settings.update_default_branch_success"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/branches") c.Redirect(c.Repo.RepoLink + "/settings/branches")
} }
func SettingsProtectedBranch(ctx *context.Context) { func SettingsProtectedBranch(c *context.Context) {
branch := ctx.Params("*") branch := c.Params("*")
if !ctx.Repo.GitRepo.IsBranchExist(branch) { if !c.Repo.GitRepo.IsBranchExist(branch) {
ctx.NotFound() c.NotFound()
return return
} }
ctx.Data["Title"] = ctx.Tr("repo.settings.protected_branches") + " - " + branch c.Data["Title"] = c.Tr("repo.settings.protected_branches") + " - " + branch
ctx.Data["PageIsSettingsBranches"] = true c.Data["PageIsSettingsBranches"] = true
protectBranch, err := models.GetProtectBranchOfRepoByName(ctx.Repo.Repository.ID, branch) protectBranch, err := models.GetProtectBranchOfRepoByName(c.Repo.Repository.ID, branch)
if err != nil { if err != nil {
if !models.IsErrBranchNotExist(err) { if !models.IsErrBranchNotExist(err) {
ctx.Handle(500, "GetProtectBranchOfRepoByName", err) c.Handle(500, "GetProtectBranchOfRepoByName", err)
return return
} }
@ -442,45 +442,45 @@ func SettingsProtectedBranch(ctx *context.Context) {
} }
} }
if ctx.Repo.Owner.IsOrganization() { if c.Repo.Owner.IsOrganization() {
users, err := ctx.Repo.Repository.GetWriters() users, err := c.Repo.Repository.GetWriters()
if err != nil { if err != nil {
ctx.Handle(500, "Repo.Repository.GetPushers", err) c.Handle(500, "Repo.Repository.GetPushers", err)
return return
} }
ctx.Data["Users"] = users c.Data["Users"] = users
ctx.Data["whitelist_users"] = protectBranch.WhitelistUserIDs c.Data["whitelist_users"] = protectBranch.WhitelistUserIDs
teams, err := ctx.Repo.Owner.TeamsHaveAccessToRepo(ctx.Repo.Repository.ID, models.ACCESS_MODE_WRITE) teams, err := c.Repo.Owner.TeamsHaveAccessToRepo(c.Repo.Repository.ID, models.ACCESS_MODE_WRITE)
if err != nil { if err != nil {
ctx.Handle(500, "Repo.Owner.TeamsHaveAccessToRepo", err) c.Handle(500, "Repo.Owner.TeamsHaveAccessToRepo", err)
return return
} }
ctx.Data["Teams"] = teams c.Data["Teams"] = teams
ctx.Data["whitelist_teams"] = protectBranch.WhitelistTeamIDs c.Data["whitelist_teams"] = protectBranch.WhitelistTeamIDs
} }
ctx.Data["Branch"] = protectBranch c.Data["Branch"] = protectBranch
ctx.HTML(200, SETTINGS_PROTECTED_BRANCH) c.HTML(200, SETTINGS_PROTECTED_BRANCH)
} }
func SettingsProtectedBranchPost(ctx *context.Context, f form.ProtectBranch) { func SettingsProtectedBranchPost(c *context.Context, f form.ProtectBranch) {
branch := ctx.Params("*") branch := c.Params("*")
if !ctx.Repo.GitRepo.IsBranchExist(branch) { if !c.Repo.GitRepo.IsBranchExist(branch) {
ctx.NotFound() c.NotFound()
return return
} }
protectBranch, err := models.GetProtectBranchOfRepoByName(ctx.Repo.Repository.ID, branch) protectBranch, err := models.GetProtectBranchOfRepoByName(c.Repo.Repository.ID, branch)
if err != nil { if err != nil {
if !models.IsErrBranchNotExist(err) { if !models.IsErrBranchNotExist(err) {
ctx.Handle(500, "GetProtectBranchOfRepoByName", err) c.Handle(500, "GetProtectBranchOfRepoByName", err)
return return
} }
// No options found, create defaults. // No options found, create defaults.
protectBranch = &models.ProtectBranch{ protectBranch = &models.ProtectBranch{
RepoID: ctx.Repo.Repository.ID, RepoID: c.Repo.Repository.ID,
Name: branch, Name: branch,
} }
} }
@ -488,144 +488,144 @@ func SettingsProtectedBranchPost(ctx *context.Context, f form.ProtectBranch) {
protectBranch.Protected = f.Protected protectBranch.Protected = f.Protected
protectBranch.RequirePullRequest = f.RequirePullRequest protectBranch.RequirePullRequest = f.RequirePullRequest
protectBranch.EnableWhitelist = f.EnableWhitelist protectBranch.EnableWhitelist = f.EnableWhitelist
if ctx.Repo.Owner.IsOrganization() { if c.Repo.Owner.IsOrganization() {
err = models.UpdateOrgProtectBranch(ctx.Repo.Repository, protectBranch, f.WhitelistUsers, f.WhitelistTeams) err = models.UpdateOrgProtectBranch(c.Repo.Repository, protectBranch, f.WhitelistUsers, f.WhitelistTeams)
} else { } else {
err = models.UpdateProtectBranch(protectBranch) err = models.UpdateProtectBranch(protectBranch)
} }
if err != nil { if err != nil {
ctx.Handle(500, "UpdateOrgProtectBranch/UpdateProtectBranch", err) c.Handle(500, "UpdateOrgProtectBranch/UpdateProtectBranch", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.update_protect_branch_success")) c.Flash.Success(c.Tr("repo.settings.update_protect_branch_success"))
ctx.Redirect(fmt.Sprintf("%s/settings/branches/%s", ctx.Repo.RepoLink, branch)) c.Redirect(fmt.Sprintf("%s/settings/branches/%s", c.Repo.RepoLink, branch))
} }
func SettingsGitHooks(ctx *context.Context) { func SettingsGitHooks(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.githooks") c.Data["Title"] = c.Tr("repo.settings.githooks")
ctx.Data["PageIsSettingsGitHooks"] = true c.Data["PageIsSettingsGitHooks"] = true
hooks, err := ctx.Repo.GitRepo.Hooks() hooks, err := c.Repo.GitRepo.Hooks()
if err != nil { if err != nil {
ctx.Handle(500, "Hooks", err) c.Handle(500, "Hooks", err)
return return
} }
ctx.Data["Hooks"] = hooks c.Data["Hooks"] = hooks
ctx.HTML(200, SETTINGS_GITHOOKS) c.HTML(200, SETTINGS_GITHOOKS)
} }
func SettingsGitHooksEdit(ctx *context.Context) { func SettingsGitHooksEdit(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.githooks") c.Data["Title"] = c.Tr("repo.settings.githooks")
ctx.Data["PageIsSettingsGitHooks"] = true c.Data["PageIsSettingsGitHooks"] = true
ctx.Data["RequireSimpleMDE"] = true c.Data["RequireSimpleMDE"] = true
name := ctx.Params(":name") name := c.Params(":name")
hook, err := ctx.Repo.GitRepo.GetHook(name) hook, err := c.Repo.GitRepo.GetHook(name)
if err != nil { if err != nil {
if err == git.ErrNotValidHook { if err == git.ErrNotValidHook {
ctx.Handle(404, "GetHook", err) c.Handle(404, "GetHook", err)
} else { } else {
ctx.Handle(500, "GetHook", err) c.Handle(500, "GetHook", err)
} }
return return
} }
ctx.Data["Hook"] = hook c.Data["Hook"] = hook
ctx.HTML(200, SETTINGS_GITHOOK_EDIT) c.HTML(200, SETTINGS_GITHOOK_EDIT)
} }
func SettingsGitHooksEditPost(ctx *context.Context) { func SettingsGitHooksEditPost(c *context.Context) {
name := ctx.Params(":name") name := c.Params(":name")
hook, err := ctx.Repo.GitRepo.GetHook(name) hook, err := c.Repo.GitRepo.GetHook(name)
if err != nil { if err != nil {
if err == git.ErrNotValidHook { if err == git.ErrNotValidHook {
ctx.Handle(404, "GetHook", err) c.Handle(404, "GetHook", err)
} else { } else {
ctx.Handle(500, "GetHook", err) c.Handle(500, "GetHook", err)
} }
return return
} }
hook.Content = ctx.Query("content") hook.Content = c.Query("content")
if err = hook.Update(); err != nil { if err = hook.Update(); err != nil {
ctx.Handle(500, "hook.Update", err) c.Handle(500, "hook.Update", err)
return return
} }
ctx.Redirect(ctx.Data["Link"].(string)) c.Redirect(c.Data["Link"].(string))
} }
func SettingsDeployKeys(ctx *context.Context) { func SettingsDeployKeys(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") c.Data["Title"] = c.Tr("repo.settings.deploy_keys")
ctx.Data["PageIsSettingsKeys"] = true c.Data["PageIsSettingsKeys"] = true
keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) keys, err := models.ListDeployKeys(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Handle(500, "ListDeployKeys", err) c.Handle(500, "ListDeployKeys", err)
return return
} }
ctx.Data["Deploykeys"] = keys c.Data["Deploykeys"] = keys
ctx.HTML(200, SETTINGS_DEPLOY_KEYS) c.HTML(200, SETTINGS_DEPLOY_KEYS)
} }
func SettingsDeployKeysPost(ctx *context.Context, f form.AddSSHKey) { func SettingsDeployKeysPost(c *context.Context, f form.AddSSHKey) {
ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") c.Data["Title"] = c.Tr("repo.settings.deploy_keys")
ctx.Data["PageIsSettingsKeys"] = true c.Data["PageIsSettingsKeys"] = true
keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) keys, err := models.ListDeployKeys(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Handle(500, "ListDeployKeys", err) c.Handle(500, "ListDeployKeys", err)
return return
} }
ctx.Data["Deploykeys"] = keys c.Data["Deploykeys"] = keys
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, SETTINGS_DEPLOY_KEYS) c.HTML(200, SETTINGS_DEPLOY_KEYS)
return return
} }
content, err := models.CheckPublicKeyString(f.Content) content, err := models.CheckPublicKeyString(f.Content)
if err != nil { if err != nil {
if models.IsErrKeyUnableVerify(err) { if models.IsErrKeyUnableVerify(err) {
ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key")) c.Flash.Info(c.Tr("form.unable_verify_ssh_key"))
} else { } else {
ctx.Data["HasError"] = true c.Data["HasError"] = true
ctx.Data["Err_Content"] = true c.Data["Err_Content"] = true
ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error())) c.Flash.Error(c.Tr("form.invalid_ssh_key", err.Error()))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys") c.Redirect(c.Repo.RepoLink + "/settings/keys")
return return
} }
} }
key, err := models.AddDeployKey(ctx.Repo.Repository.ID, f.Title, content) key, err := models.AddDeployKey(c.Repo.Repository.ID, f.Title, content)
if err != nil { if err != nil {
ctx.Data["HasError"] = true c.Data["HasError"] = true
switch { switch {
case models.IsErrKeyAlreadyExist(err): case models.IsErrKeyAlreadyExist(err):
ctx.Data["Err_Content"] = true c.Data["Err_Content"] = true
ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), SETTINGS_DEPLOY_KEYS, &f) c.RenderWithErr(c.Tr("repo.settings.key_been_used"), SETTINGS_DEPLOY_KEYS, &f)
case models.IsErrKeyNameAlreadyUsed(err): case models.IsErrKeyNameAlreadyUsed(err):
ctx.Data["Err_Title"] = true c.Data["Err_Title"] = true
ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), SETTINGS_DEPLOY_KEYS, &f) c.RenderWithErr(c.Tr("repo.settings.key_name_used"), SETTINGS_DEPLOY_KEYS, &f)
default: default:
ctx.Handle(500, "AddDeployKey", err) c.Handle(500, "AddDeployKey", err)
} }
return return
} }
log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID) log.Trace("Deploy key added: %d", c.Repo.Repository.ID)
ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name)) c.Flash.Success(c.Tr("repo.settings.add_key_success", key.Name))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys") c.Redirect(c.Repo.RepoLink + "/settings/keys")
} }
func DeleteDeployKey(ctx *context.Context) { func DeleteDeployKey(c *context.Context) {
if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil { if err := models.DeleteDeployKey(c.User, c.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteDeployKey: " + err.Error()) c.Flash.Error("DeleteDeployKey: " + err.Error())
} else { } else {
ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success")) c.Flash.Success(c.Tr("repo.settings.deploy_key_deletion_success"))
} }
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/settings/keys", "redirect": c.Repo.RepoLink + "/settings/keys",
}) })
} }

192
routers/repo/view.go

@ -122,55 +122,55 @@ func renderDirectory(c *context.Context, treeLink string) {
} }
} }
func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) { func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
ctx.Data["IsViewFile"] = true c.Data["IsViewFile"] = true
blob := entry.Blob() blob := entry.Blob()
dataRc, err := blob.Data() dataRc, err := blob.Data()
if err != nil { if err != nil {
ctx.Handle(500, "Data", err) c.Handle(500, "Data", err)
return return
} }
ctx.Data["FileSize"] = blob.Size() c.Data["FileSize"] = blob.Size()
ctx.Data["FileName"] = blob.Name() c.Data["FileName"] = blob.Name()
ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name()) c.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath c.Data["RawFileLink"] = rawLink + "/" + c.Repo.TreePath
buf := make([]byte, 1024) buf := make([]byte, 1024)
n, _ := dataRc.Read(buf) n, _ := dataRc.Read(buf)
buf = buf[:n] buf = buf[:n]
isTextFile := tool.IsTextFile(buf) isTextFile := tool.IsTextFile(buf)
ctx.Data["IsTextFile"] = isTextFile c.Data["IsTextFile"] = isTextFile
// Assume file is not editable first. // Assume file is not editable first.
if !isTextFile { if !isTextFile {
ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files") c.Data["EditFileTooltip"] = c.Tr("repo.editor.cannot_edit_non_text_files")
} }
canEnableEditor := ctx.Repo.CanEnableEditor() canEnableEditor := c.Repo.CanEnableEditor()
switch { switch {
case isTextFile: case isTextFile:
if blob.Size() >= setting.UI.MaxDisplayFileSize { if blob.Size() >= setting.UI.MaxDisplayFileSize {
ctx.Data["IsFileTooLarge"] = true c.Data["IsFileTooLarge"] = true
break break
} }
ctx.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name()) c.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name())
d, _ := ioutil.ReadAll(dataRc) d, _ := ioutil.ReadAll(dataRc)
buf = append(buf, d...) buf = append(buf, d...)
switch markup.Detect(blob.Name()) { switch markup.Detect(blob.Name()) {
case markup.MARKDOWN: case markup.MARKDOWN:
ctx.Data["IsMarkdown"] = true c.Data["IsMarkdown"] = true
ctx.Data["FileContent"] = string(markup.Markdown(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas())) c.Data["FileContent"] = string(markup.Markdown(buf, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
case markup.ORG_MODE: case markup.ORG_MODE:
ctx.Data["IsMarkdown"] = true c.Data["IsMarkdown"] = true
ctx.Data["FileContent"] = string(markup.OrgMode(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas())) c.Data["FileContent"] = string(markup.OrgMode(buf, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
case markup.IPYTHON_NOTEBOOK: case markup.IPYTHON_NOTEBOOK:
ctx.Data["IsIPythonNotebook"] = true c.Data["IsIPythonNotebook"] = true
default: default:
// Building code view blocks with line number on server side. // Building code view blocks with line number on server side.
var fileContent string var fileContent string
@ -188,180 +188,180 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
for index, line := range lines { for index, line := range lines {
output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n") output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
} }
ctx.Data["FileContent"] = gotemplate.HTML(output.String()) c.Data["FileContent"] = gotemplate.HTML(output.String())
output.Reset() output.Reset()
for i := 0; i < len(lines); i++ { for i := 0; i < len(lines); i++ {
output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1)) output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
} }
ctx.Data["LineNums"] = gotemplate.HTML(output.String()) c.Data["LineNums"] = gotemplate.HTML(output.String())
} }
if canEnableEditor { if canEnableEditor {
ctx.Data["CanEditFile"] = true c.Data["CanEditFile"] = true
ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file") c.Data["EditFileTooltip"] = c.Tr("repo.editor.edit_this_file")
} else if !ctx.Repo.IsViewBranch { } else if !c.Repo.IsViewBranch {
ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch") c.Data["EditFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
} else if !ctx.Repo.IsWriter() { } else if !c.Repo.IsWriter() {
ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit") c.Data["EditFileTooltip"] = c.Tr("repo.editor.fork_before_edit")
} }
case tool.IsPDFFile(buf): case tool.IsPDFFile(buf):
ctx.Data["IsPDFFile"] = true c.Data["IsPDFFile"] = true
case tool.IsVideoFile(buf): case tool.IsVideoFile(buf):
ctx.Data["IsVideoFile"] = true c.Data["IsVideoFile"] = true
case tool.IsImageFile(buf): case tool.IsImageFile(buf):
ctx.Data["IsImageFile"] = true c.Data["IsImageFile"] = true
} }
if canEnableEditor { if canEnableEditor {
ctx.Data["CanDeleteFile"] = true c.Data["CanDeleteFile"] = true
ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file") c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.delete_this_file")
} else if !ctx.Repo.IsViewBranch { } else if !c.Repo.IsViewBranch {
ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch") c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
} else if !ctx.Repo.IsWriter() { } else if !c.Repo.IsWriter() {
ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access") c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_have_write_access")
} }
} }
func setEditorconfigIfExists(ctx *context.Context) { func setEditorconfigIfExists(c *context.Context) {
ec, err := ctx.Repo.GetEditorconfig() ec, err := c.Repo.GetEditorconfig()
if err != nil && !git.IsErrNotExist(err) { if err != nil && !git.IsErrNotExist(err) {
log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", ctx.Repo.Repository.ID, err) log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", c.Repo.Repository.ID, err)
return return
} }
ctx.Data["Editorconfig"] = ec c.Data["Editorconfig"] = ec
} }
func Home(ctx *context.Context) { func Home(c *context.Context) {
ctx.Data["PageIsViewFiles"] = true c.Data["PageIsViewFiles"] = true
if ctx.Repo.Repository.IsBare { if c.Repo.Repository.IsBare {
ctx.HTML(200, BARE) c.HTML(200, BARE)
return return
} }
title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name title := c.Repo.Repository.Owner.Name + "/" + c.Repo.Repository.Name
if len(ctx.Repo.Repository.Description) > 0 { if len(c.Repo.Repository.Description) > 0 {
title += ": " + ctx.Repo.Repository.Description title += ": " + c.Repo.Repository.Description
} }
ctx.Data["Title"] = title c.Data["Title"] = title
if ctx.Repo.BranchName != ctx.Repo.Repository.DefaultBranch { if c.Repo.BranchName != c.Repo.Repository.DefaultBranch {
ctx.Data["Title"] = title + " @ " + ctx.Repo.BranchName c.Data["Title"] = title + " @ " + c.Repo.BranchName
} }
ctx.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName branchLink := c.Repo.RepoLink + "/src/" + c.Repo.BranchName
treeLink := branchLink treeLink := branchLink
rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName rawLink := c.Repo.RepoLink + "/raw/" + c.Repo.BranchName
isRootDir := false isRootDir := false
if len(ctx.Repo.TreePath) > 0 { if len(c.Repo.TreePath) > 0 {
treeLink += "/" + ctx.Repo.TreePath treeLink += "/" + c.Repo.TreePath
} else { } else {
isRootDir = true isRootDir = true
// Only show Git stats panel when view root directory // Only show Git stats panel when view root directory
var err error var err error
ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount() c.Repo.CommitsCount, err = c.Repo.Commit.CommitsCount()
if err != nil { if err != nil {
ctx.Handle(500, "CommitsCount", err) c.Handle(500, "CommitsCount", err)
return return
} }
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount c.Data["CommitsCount"] = c.Repo.CommitsCount
} }
ctx.Data["PageIsRepoHome"] = isRootDir c.Data["PageIsRepoHome"] = isRootDir
// Get current entry user currently looking at. // Get current entry user currently looking at.
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath) entry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err) c.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
return return
} }
if entry.IsDir() { if entry.IsDir() {
renderDirectory(ctx, treeLink) renderDirectory(c, treeLink)
} else { } else {
renderFile(ctx, entry, treeLink, rawLink) renderFile(c, entry, treeLink, rawLink)
} }
if ctx.Written() { if c.Written() {
return return
} }
setEditorconfigIfExists(ctx) setEditorconfigIfExists(c)
if ctx.Written() { if c.Written() {
return return
} }
var treeNames []string var treeNames []string
paths := make([]string, 0, 5) paths := make([]string, 0, 5)
if len(ctx.Repo.TreePath) > 0 { if len(c.Repo.TreePath) > 0 {
treeNames = strings.Split(ctx.Repo.TreePath, "/") treeNames = strings.Split(c.Repo.TreePath, "/")
for i := range treeNames { for i := range treeNames {
paths = append(paths, strings.Join(treeNames[:i+1], "/")) paths = append(paths, strings.Join(treeNames[:i+1], "/"))
} }
ctx.Data["HasParentPath"] = true c.Data["HasParentPath"] = true
if len(paths)-2 >= 0 { if len(paths)-2 >= 0 {
ctx.Data["ParentPath"] = "/" + paths[len(paths)-2] c.Data["ParentPath"] = "/" + paths[len(paths)-2]
} }
} }
ctx.Data["Paths"] = paths c.Data["Paths"] = paths
ctx.Data["TreeLink"] = treeLink c.Data["TreeLink"] = treeLink
ctx.Data["TreeNames"] = treeNames c.Data["TreeNames"] = treeNames
ctx.Data["BranchLink"] = branchLink c.Data["BranchLink"] = branchLink
ctx.HTML(200, HOME) c.HTML(200, HOME)
} }
func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl string) { func RenderUserCards(c *context.Context, total int, getter func(page int) ([]*models.User, error), tpl string) {
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page <= 0 { if page <= 0 {
page = 1 page = 1
} }
pager := paginater.New(total, models.ItemsPerPage, page, 5) pager := paginater.New(total, models.ItemsPerPage, page, 5)
ctx.Data["Page"] = pager c.Data["Page"] = pager
items, err := getter(pager.Current()) items, err := getter(pager.Current())
if err != nil { if err != nil {
ctx.Handle(500, "getter", err) c.Handle(500, "getter", err)
return return
} }
ctx.Data["Cards"] = items c.Data["Cards"] = items
ctx.HTML(200, tpl) c.HTML(200, tpl)
} }
func Watchers(ctx *context.Context) { func Watchers(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.watchers") c.Data["Title"] = c.Tr("repo.watchers")
ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers") c.Data["CardsTitle"] = c.Tr("repo.watchers")
ctx.Data["PageIsWatchers"] = true c.Data["PageIsWatchers"] = true
RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, WATCHERS) RenderUserCards(c, c.Repo.Repository.NumWatches, c.Repo.Repository.GetWatchers, WATCHERS)
} }
func Stars(ctx *context.Context) { func Stars(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.stargazers") c.Data["Title"] = c.Tr("repo.stargazers")
ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers") c.Data["CardsTitle"] = c.Tr("repo.stargazers")
ctx.Data["PageIsStargazers"] = true c.Data["PageIsStargazers"] = true
RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, WATCHERS) RenderUserCards(c, c.Repo.Repository.NumStars, c.Repo.Repository.GetStargazers, WATCHERS)
} }
func Forks(ctx *context.Context) { func Forks(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repos.forks") c.Data["Title"] = c.Tr("repos.forks")
forks, err := ctx.Repo.Repository.GetForks() forks, err := c.Repo.Repository.GetForks()
if err != nil { if err != nil {
ctx.Handle(500, "GetForks", err) c.Handle(500, "GetForks", err)
return return
} }
for _, fork := range forks { for _, fork := range forks {
if err = fork.GetOwner(); err != nil { if err = fork.GetOwner(); err != nil {
ctx.Handle(500, "GetOwner", err) c.Handle(500, "GetOwner", err)
return return
} }
} }
ctx.Data["Forks"] = forks c.Data["Forks"] = forks
ctx.HTML(200, FORKS) c.HTML(200, FORKS)
} }

338
routers/repo/webhook.go

@ -27,21 +27,21 @@ const (
ORG_WEBHOOK_NEW = "org/settings/webhook_new" ORG_WEBHOOK_NEW = "org/settings/webhook_new"
) )
func Webhooks(ctx *context.Context) { func Webhooks(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.hooks") c.Data["Title"] = c.Tr("repo.settings.hooks")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["BaseLink"] = ctx.Repo.RepoLink c.Data["BaseLink"] = c.Repo.RepoLink
ctx.Data["Description"] = ctx.Tr("repo.settings.hooks_desc", "https://github.com/gogits/go-gogs-client/wiki/Repositories-Webhooks") c.Data["Description"] = c.Tr("repo.settings.hooks_desc", "https://github.com/gogits/go-gogs-client/wiki/Repositories-Webhooks")
ctx.Data["Types"] = setting.Webhook.Types c.Data["Types"] = setting.Webhook.Types
ws, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID) ws, err := models.GetWebhooksByRepoID(c.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Handle(500, "GetWebhooksByRepoID", err) c.Handle(500, "GetWebhooksByRepoID", err)
return return
} }
ctx.Data["Webhooks"] = ws c.Data["Webhooks"] = ws
ctx.HTML(200, WEBHOOKS) c.HTML(200, WEBHOOKS)
} }
type OrgRepoCtx struct { type OrgRepoCtx struct {
@ -52,21 +52,21 @@ type OrgRepoCtx struct {
} }
// getOrgRepoCtx determines whether this is a repo context or organization context. // getOrgRepoCtx determines whether this is a repo context or organization context.
func getOrgRepoCtx(ctx *context.Context) (*OrgRepoCtx, error) { func getOrgRepoCtx(c *context.Context) (*OrgRepoCtx, error) {
if len(ctx.Repo.RepoLink) > 0 { if len(c.Repo.RepoLink) > 0 {
ctx.Data["PageIsRepositoryContext"] = true c.Data["PageIsRepositoryContext"] = true
return &OrgRepoCtx{ return &OrgRepoCtx{
RepoID: ctx.Repo.Repository.ID, RepoID: c.Repo.Repository.ID,
Link: ctx.Repo.RepoLink, Link: c.Repo.RepoLink,
NewTemplate: WEBHOOK_NEW, NewTemplate: WEBHOOK_NEW,
}, nil }, nil
} }
if len(ctx.Org.OrgLink) > 0 { if len(c.Org.OrgLink) > 0 {
ctx.Data["PageIsOrganizationContext"] = true c.Data["PageIsOrganizationContext"] = true
return &OrgRepoCtx{ return &OrgRepoCtx{
OrgID: ctx.Org.Organization.ID, OrgID: c.Org.Organization.ID,
Link: ctx.Org.OrgLink, Link: c.Org.OrgLink,
NewTemplate: ORG_WEBHOOK_NEW, NewTemplate: ORG_WEBHOOK_NEW,
}, nil }, nil
} }
@ -74,34 +74,34 @@ func getOrgRepoCtx(ctx *context.Context) (*OrgRepoCtx, error) {
return nil, errors.New("Unable to set OrgRepo context") return nil, errors.New("Unable to set OrgRepo context")
} }
func checkHookType(ctx *context.Context) string { func checkHookType(c *context.Context) string {
hookType := strings.ToLower(ctx.Params(":type")) hookType := strings.ToLower(c.Params(":type"))
if !com.IsSliceContainsStr(setting.Webhook.Types, hookType) { if !com.IsSliceContainsStr(setting.Webhook.Types, hookType) {
ctx.Handle(404, "checkHookType", nil) c.Handle(404, "checkHookType", nil)
return "" return ""
} }
return hookType return hookType
} }
func WebhooksNew(ctx *context.Context) { func WebhooksNew(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") c.Data["Title"] = c.Tr("repo.settings.add_webhook")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true c.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
orCtx, err := getOrgRepoCtx(ctx) orCtx, err := getOrgRepoCtx(c)
if err != nil { if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err) c.Handle(500, "getOrgRepoCtx", err)
return return
} }
ctx.Data["HookType"] = checkHookType(ctx) c.Data["HookType"] = checkHookType(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["BaseLink"] = orCtx.Link c.Data["BaseLink"] = orCtx.Link
ctx.HTML(200, orCtx.NewTemplate) c.HTML(200, orCtx.NewTemplate)
} }
func ParseHookEvent(f form.Webhook) *models.HookEvent { func ParseHookEvent(f form.Webhook) *models.HookEvent {
@ -122,22 +122,22 @@ func ParseHookEvent(f form.Webhook) *models.HookEvent {
} }
} }
func WebHooksNewPost(ctx *context.Context, f form.NewWebhook) { func WebHooksNewPost(c *context.Context, f form.NewWebhook) {
ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") c.Data["Title"] = c.Tr("repo.settings.add_webhook")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true c.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
ctx.Data["HookType"] = "gogs" c.Data["HookType"] = "gogs"
orCtx, err := getOrgRepoCtx(ctx) orCtx, err := getOrgRepoCtx(c)
if err != nil { if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err) c.Handle(500, "getOrgRepoCtx", err)
return return
} }
ctx.Data["BaseLink"] = orCtx.Link c.Data["BaseLink"] = orCtx.Link
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, orCtx.NewTemplate) c.HTML(200, orCtx.NewTemplate)
return return
} }
@ -157,31 +157,31 @@ func WebHooksNewPost(ctx *context.Context, f form.NewWebhook) {
OrgID: orCtx.OrgID, OrgID: orCtx.OrgID,
} }
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) c.Handle(500, "UpdateEvent", err)
return return
} else if err := models.CreateWebhook(w); err != nil { } else if err := models.CreateWebhook(w); err != nil {
ctx.Handle(500, "CreateWebhook", err) c.Handle(500, "CreateWebhook", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success")) c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
ctx.Redirect(orCtx.Link + "/settings/hooks") c.Redirect(orCtx.Link + "/settings/hooks")
} }
func SlackHooksNewPost(ctx *context.Context, f form.NewSlackHook) { func SlackHooksNewPost(c *context.Context, f form.NewSlackHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings") c.Data["Title"] = c.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true c.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
orCtx, err := getOrgRepoCtx(ctx) orCtx, err := getOrgRepoCtx(c)
if err != nil { if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err) c.Handle(500, "getOrgRepoCtx", err)
return return
} }
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, orCtx.NewTemplate) c.HTML(200, orCtx.NewTemplate)
return return
} }
@ -192,7 +192,7 @@ func SlackHooksNewPost(ctx *context.Context, f form.NewSlackHook) {
Color: f.Color, Color: f.Color,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "Marshal", err) c.Handle(500, "Marshal", err)
return return
} }
@ -207,32 +207,32 @@ func SlackHooksNewPost(ctx *context.Context, f form.NewSlackHook) {
OrgID: orCtx.OrgID, OrgID: orCtx.OrgID,
} }
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) c.Handle(500, "UpdateEvent", err)
return return
} else if err := models.CreateWebhook(w); err != nil { } else if err := models.CreateWebhook(w); err != nil {
ctx.Handle(500, "CreateWebhook", err) c.Handle(500, "CreateWebhook", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success")) c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
ctx.Redirect(orCtx.Link + "/settings/hooks") c.Redirect(orCtx.Link + "/settings/hooks")
} }
// FIXME: merge logic to Slack // FIXME: merge logic to Slack
func DiscordHooksNewPost(ctx *context.Context, f form.NewDiscordHook) { func DiscordHooksNewPost(c *context.Context, f form.NewDiscordHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings") c.Data["Title"] = c.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true c.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}} c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
orCtx, err := getOrgRepoCtx(ctx) orCtx, err := getOrgRepoCtx(c)
if err != nil { if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err) c.Handle(500, "getOrgRepoCtx", err)
return return
} }
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, orCtx.NewTemplate) c.HTML(200, orCtx.NewTemplate)
return return
} }
@ -242,7 +242,7 @@ func DiscordHooksNewPost(ctx *context.Context, f form.NewDiscordHook) {
Color: f.Color, Color: f.Color,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "Marshal", err) c.Handle(500, "Marshal", err)
return return
} }
@ -257,83 +257,83 @@ func DiscordHooksNewPost(ctx *context.Context, f form.NewDiscordHook) {
OrgID: orCtx.OrgID, OrgID: orCtx.OrgID,
} }
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) c.Handle(500, "UpdateEvent", err)
return return
} else if err := models.CreateWebhook(w); err != nil { } else if err := models.CreateWebhook(w); err != nil {
ctx.Handle(500, "CreateWebhook", err) c.Handle(500, "CreateWebhook", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success")) c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
ctx.Redirect(orCtx.Link + "/settings/hooks") c.Redirect(orCtx.Link + "/settings/hooks")
} }
func checkWebhook(ctx *context.Context) (*OrgRepoCtx, *models.Webhook) { func checkWebhook(c *context.Context) (*OrgRepoCtx, *models.Webhook) {
ctx.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
orCtx, err := getOrgRepoCtx(ctx) orCtx, err := getOrgRepoCtx(c)
if err != nil { if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err) c.Handle(500, "getOrgRepoCtx", err)
return nil, nil return nil, nil
} }
ctx.Data["BaseLink"] = orCtx.Link c.Data["BaseLink"] = orCtx.Link
var w *models.Webhook var w *models.Webhook
if orCtx.RepoID > 0 { if orCtx.RepoID > 0 {
w, err = models.GetWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) w, err = models.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
} else { } else {
w, err = models.GetWebhookByOrgID(ctx.Org.Organization.ID, ctx.ParamsInt64(":id")) w, err = models.GetWebhookByOrgID(c.Org.Organization.ID, c.ParamsInt64(":id"))
} }
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err) c.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
return nil, nil return nil, nil
} }
switch w.HookTaskType { switch w.HookTaskType {
case models.SLACK: case models.SLACK:
ctx.Data["SlackHook"] = w.GetSlackHook() c.Data["SlackHook"] = w.GetSlackHook()
ctx.Data["HookType"] = "slack" c.Data["HookType"] = "slack"
case models.DISCORD: case models.DISCORD:
ctx.Data["SlackHook"] = w.GetSlackHook() c.Data["SlackHook"] = w.GetSlackHook()
ctx.Data["HookType"] = "discord" c.Data["HookType"] = "discord"
default: default:
ctx.Data["HookType"] = "gogs" c.Data["HookType"] = "gogs"
} }
ctx.Data["History"], err = w.History(1) c.Data["History"], err = w.History(1)
if err != nil { if err != nil {
ctx.Handle(500, "History", err) c.Handle(500, "History", err)
} }
return orCtx, w return orCtx, w
} }
func WebHooksEdit(ctx *context.Context) { func WebHooksEdit(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook") c.Data["Title"] = c.Tr("repo.settings.update_webhook")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true c.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx) orCtx, w := checkWebhook(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["Webhook"] = w c.Data["Webhook"] = w
ctx.HTML(200, orCtx.NewTemplate) c.HTML(200, orCtx.NewTemplate)
} }
func WebHooksEditPost(ctx *context.Context, f form.NewWebhook) { func WebHooksEditPost(c *context.Context, f form.NewWebhook) {
ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook") c.Data["Title"] = c.Tr("repo.settings.update_webhook")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true c.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx) orCtx, w := checkWebhook(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["Webhook"] = w c.Data["Webhook"] = w
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, orCtx.NewTemplate) c.HTML(200, orCtx.NewTemplate)
return return
} }
@ -348,30 +348,30 @@ func WebHooksEditPost(ctx *context.Context, f form.NewWebhook) {
w.HookEvent = ParseHookEvent(f.Webhook) w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = f.Active w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) c.Handle(500, "UpdateEvent", err)
return return
} else if err := models.UpdateWebhook(w); err != nil { } else if err := models.UpdateWebhook(w); err != nil {
ctx.Handle(500, "WebHooksEditPost", err) c.Handle(500, "WebHooksEditPost", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success")) c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
} }
func SlackHooksEditPost(ctx *context.Context, f form.NewSlackHook) { func SlackHooksEditPost(c *context.Context, f form.NewSlackHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings") c.Data["Title"] = c.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true c.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx) orCtx, w := checkWebhook(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["Webhook"] = w c.Data["Webhook"] = w
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, orCtx.NewTemplate) c.HTML(200, orCtx.NewTemplate)
return return
} }
@ -382,7 +382,7 @@ func SlackHooksEditPost(ctx *context.Context, f form.NewSlackHook) {
Color: f.Color, Color: f.Color,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "Marshal", err) c.Handle(500, "Marshal", err)
return return
} }
@ -391,31 +391,31 @@ func SlackHooksEditPost(ctx *context.Context, f form.NewSlackHook) {
w.HookEvent = ParseHookEvent(f.Webhook) w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = f.Active w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) c.Handle(500, "UpdateEvent", err)
return return
} else if err := models.UpdateWebhook(w); err != nil { } else if err := models.UpdateWebhook(w); err != nil {
ctx.Handle(500, "UpdateWebhook", err) c.Handle(500, "UpdateWebhook", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success")) c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
} }
// FIXME: merge logic to Slack // FIXME: merge logic to Slack
func DiscordHooksEditPost(ctx *context.Context, f form.NewDiscordHook) { func DiscordHooksEditPost(c *context.Context, f form.NewDiscordHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings") c.Data["Title"] = c.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true c.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true c.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx) orCtx, w := checkWebhook(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["Webhook"] = w c.Data["Webhook"] = w
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, orCtx.NewTemplate) c.HTML(200, orCtx.NewTemplate)
return return
} }
@ -425,7 +425,7 @@ func DiscordHooksEditPost(ctx *context.Context, f form.NewDiscordHook) {
Color: f.Color, Color: f.Color,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "Marshal", err) c.Handle(500, "Marshal", err)
return return
} }
@ -434,22 +434,22 @@ func DiscordHooksEditPost(ctx *context.Context, f form.NewDiscordHook) {
w.HookEvent = ParseHookEvent(f.Webhook) w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = f.Active w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err) c.Handle(500, "UpdateEvent", err)
return return
} else if err := models.UpdateWebhook(w); err != nil { } else if err := models.UpdateWebhook(w); err != nil {
ctx.Handle(500, "UpdateWebhook", err) c.Handle(500, "UpdateWebhook", err)
return return
} }
ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success")) c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
} }
func TestWebhook(ctx *context.Context) { func TestWebhook(c *context.Context) {
var authorUsername, committerUsername string var authorUsername, committerUsername string
// Grab latest commit or fake one if it's empty repository. // Grab latest commit or fake one if it's empty repository.
commit := ctx.Repo.Commit commit := c.Repo.Commit
if commit == nil { if commit == nil {
ghost := models.NewGhostUser() ghost := models.NewGhostUser()
commit = &git.Commit{ commit = &git.Commit{
@ -466,7 +466,7 @@ func TestWebhook(ctx *context.Context) {
if err == nil { if err == nil {
authorUsername = author.Name authorUsername = author.Name
} else if !errors.IsUserNotExist(err) { } else if !errors.IsUserNotExist(err) {
ctx.Handle(500, "GetUserByEmail.(author)", err) c.Handle(500, "GetUserByEmail.(author)", err)
return return
} }
@ -474,27 +474,27 @@ func TestWebhook(ctx *context.Context) {
if err == nil { if err == nil {
committerUsername = committer.Name committerUsername = committer.Name
} else if !errors.IsUserNotExist(err) { } else if !errors.IsUserNotExist(err) {
ctx.Handle(500, "GetUserByEmail.(committer)", err) c.Handle(500, "GetUserByEmail.(committer)", err)
return return
} }
} }
fileStatus, err := commit.FileStatus() fileStatus, err := commit.FileStatus()
if err != nil { if err != nil {
ctx.Handle(500, "FileStatus", err) c.Handle(500, "FileStatus", err)
return return
} }
apiUser := ctx.User.APIFormat() apiUser := c.User.APIFormat()
p := &api.PushPayload{ p := &api.PushPayload{
Ref: git.BRANCH_PREFIX + ctx.Repo.Repository.DefaultBranch, Ref: git.BRANCH_PREFIX + c.Repo.Repository.DefaultBranch,
Before: commit.ID.String(), Before: commit.ID.String(),
After: commit.ID.String(), After: commit.ID.String(),
Commits: []*api.PayloadCommit{ Commits: []*api.PayloadCommit{
{ {
ID: commit.ID.String(), ID: commit.ID.String(),
Message: commit.Message(), Message: commit.Message(),
URL: ctx.Repo.Repository.HTMLURL() + "/commit/" + commit.ID.String(), URL: c.Repo.Repository.HTMLURL() + "/commit/" + commit.ID.String(),
Author: &api.PayloadUser{ Author: &api.PayloadUser{
Name: commit.Author.Name, Name: commit.Author.Name,
Email: commit.Author.Email, Email: commit.Author.Email,
@ -510,49 +510,49 @@ func TestWebhook(ctx *context.Context) {
Modified: fileStatus.Modified, Modified: fileStatus.Modified,
}, },
}, },
Repo: ctx.Repo.Repository.APIFormat(nil), Repo: c.Repo.Repository.APIFormat(nil),
Pusher: apiUser, Pusher: apiUser,
Sender: apiUser, Sender: apiUser,
} }
if err := models.TestWebhook(ctx.Repo.Repository, models.HOOK_EVENT_PUSH, p, ctx.ParamsInt64("id")); err != nil { if err := models.TestWebhook(c.Repo.Repository, models.HOOK_EVENT_PUSH, p, c.ParamsInt64("id")); err != nil {
ctx.Handle(500, "TestWebhook", err) c.Handle(500, "TestWebhook", err)
} else { } else {
ctx.Flash.Info(ctx.Tr("repo.settings.webhook.test_delivery_success")) c.Flash.Info(c.Tr("repo.settings.webhook.test_delivery_success"))
ctx.Status(200) c.Status(200)
} }
} }
func RedeliveryWebhook(ctx *context.Context) { func RedeliveryWebhook(c *context.Context) {
webhook, err := models.GetWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) webhook, err := models.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err) c.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
return return
} }
hookTask, err := models.GetHookTaskOfWebhookByUUID(webhook.ID, ctx.Query("uuid")) hookTask, err := models.GetHookTaskOfWebhookByUUID(webhook.ID, c.Query("uuid"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetHookTaskOfWebhookByUUID/GetWebhookByOrgID", errors.IsHookTaskNotExist, err) c.NotFoundOrServerError("GetHookTaskOfWebhookByUUID/GetWebhookByOrgID", errors.IsHookTaskNotExist, err)
return return
} }
hookTask.IsDelivered = false hookTask.IsDelivered = false
if err = models.UpdateHookTask(hookTask); err != nil { if err = models.UpdateHookTask(hookTask); err != nil {
ctx.Handle(500, "UpdateHookTask", err) c.Handle(500, "UpdateHookTask", err)
} else { } else {
go models.HookQueue.Add(ctx.Repo.Repository.ID) go models.HookQueue.Add(c.Repo.Repository.ID)
ctx.Flash.Info(ctx.Tr("repo.settings.webhook.redelivery_success", hookTask.UUID)) c.Flash.Info(c.Tr("repo.settings.webhook.redelivery_success", hookTask.UUID))
ctx.Status(200) c.Status(200)
} }
} }
func DeleteWebhook(ctx *context.Context) { func DeleteWebhook(c *context.Context) {
if err := models.DeleteWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil { if err := models.DeleteWebhookOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error()) c.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
} else { } 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{}{ c.JSON(200, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/settings/hooks", "redirect": c.Repo.RepoLink + "/settings/hooks",
}) })
} }

178
routers/repo/wiki.go

@ -24,14 +24,14 @@ const (
WIKI_PAGES = "repo/wiki/pages" WIKI_PAGES = "repo/wiki/pages"
) )
func MustEnableWiki(ctx *context.Context) { func MustEnableWiki(c *context.Context) {
if !ctx.Repo.Repository.EnableWiki { if !c.Repo.Repository.EnableWiki {
ctx.Handle(404, "MustEnableWiki", nil) c.Handle(404, "MustEnableWiki", nil)
return return
} }
if ctx.Repo.Repository.EnableExternalWiki { if c.Repo.Repository.EnableExternalWiki {
ctx.Redirect(ctx.Repo.Repository.ExternalWikiURL) c.Redirect(c.Repo.Repository.ExternalWikiURL)
return return
} }
} }
@ -42,15 +42,15 @@ type PageMeta struct {
Updated time.Time Updated time.Time
} }
func renderWikiPage(ctx *context.Context, isViewPage bool) (*git.Repository, string) { func renderWikiPage(c *context.Context, isViewPage bool) (*git.Repository, string) {
wikiRepo, err := git.OpenRepository(ctx.Repo.Repository.WikiPath()) wikiRepo, err := git.OpenRepository(c.Repo.Repository.WikiPath())
if err != nil { if err != nil {
ctx.Handle(500, "OpenRepository", err) c.Handle(500, "OpenRepository", err)
return nil, "" return nil, ""
} }
commit, err := wikiRepo.GetBranchCommit("master") commit, err := wikiRepo.GetBranchCommit("master")
if err != nil { if err != nil {
ctx.Handle(500, "GetBranchCommit", err) c.Handle(500, "GetBranchCommit", err)
return nil, "" return nil, ""
} }
@ -58,7 +58,7 @@ func renderWikiPage(ctx *context.Context, isViewPage bool) (*git.Repository, str
if isViewPage { if isViewPage {
entries, err := commit.ListEntries() entries, err := commit.ListEntries()
if err != nil { if err != nil {
ctx.Handle(500, "ListEntries", err) c.Handle(500, "ListEntries", err)
return nil, "" return nil, ""
} }
pages := make([]PageMeta, 0, len(entries)) pages := make([]PageMeta, 0, len(entries))
@ -71,204 +71,204 @@ func renderWikiPage(ctx *context.Context, isViewPage bool) (*git.Repository, str
}) })
} }
} }
ctx.Data["Pages"] = pages c.Data["Pages"] = pages
} }
pageURL := ctx.Params(":page") pageURL := c.Params(":page")
if len(pageURL) == 0 { if len(pageURL) == 0 {
pageURL = "Home" pageURL = "Home"
} }
ctx.Data["PageURL"] = pageURL c.Data["PageURL"] = pageURL
pageName := models.ToWikiPageName(pageURL) pageName := models.ToWikiPageName(pageURL)
ctx.Data["old_title"] = pageName c.Data["old_title"] = pageName
ctx.Data["Title"] = pageName c.Data["Title"] = pageName
ctx.Data["title"] = pageName c.Data["title"] = pageName
ctx.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
blob, err := commit.GetBlobByPath(pageName + ".md") blob, err := commit.GetBlobByPath(pageName + ".md")
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.Redirect(ctx.Repo.RepoLink + "/wiki/_pages") c.Redirect(c.Repo.RepoLink + "/wiki/_pages")
} else { } else {
ctx.Handle(500, "GetBlobByPath", err) c.Handle(500, "GetBlobByPath", err)
} }
return nil, "" return nil, ""
} }
r, err := blob.Data() r, err := blob.Data()
if err != nil { if err != nil {
ctx.Handle(500, "Data", err) c.Handle(500, "Data", err)
return nil, "" return nil, ""
} }
data, err := ioutil.ReadAll(r) data, err := ioutil.ReadAll(r)
if err != nil { if err != nil {
ctx.Handle(500, "ReadAll", err) c.Handle(500, "ReadAll", err)
return nil, "" return nil, ""
} }
if isViewPage { if isViewPage {
ctx.Data["content"] = string(markup.Markdown(data, ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas())) c.Data["content"] = string(markup.Markdown(data, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
} else { } else {
ctx.Data["content"] = string(data) c.Data["content"] = string(data)
} }
return wikiRepo, pageName return wikiRepo, pageName
} }
func Wiki(ctx *context.Context) { func Wiki(c *context.Context) {
ctx.Data["PageIsWiki"] = true c.Data["PageIsWiki"] = true
if !ctx.Repo.Repository.HasWiki() { if !c.Repo.Repository.HasWiki() {
ctx.Data["Title"] = ctx.Tr("repo.wiki") c.Data["Title"] = c.Tr("repo.wiki")
ctx.HTML(200, WIKI_START) c.HTML(200, WIKI_START)
return return
} }
wikiRepo, pageName := renderWikiPage(ctx, true) wikiRepo, pageName := renderWikiPage(c, true)
if ctx.Written() { if c.Written() {
return return
} }
// Get last change information. // Get last change information.
lastCommit, err := wikiRepo.GetCommitByPath(pageName + ".md") lastCommit, err := wikiRepo.GetCommitByPath(pageName + ".md")
if err != nil { if err != nil {
ctx.Handle(500, "GetCommitByPath", err) c.Handle(500, "GetCommitByPath", err)
return return
} }
ctx.Data["Author"] = lastCommit.Author c.Data["Author"] = lastCommit.Author
ctx.HTML(200, WIKI_VIEW) c.HTML(200, WIKI_VIEW)
} }
func WikiPages(ctx *context.Context) { func WikiPages(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.pages") c.Data["Title"] = c.Tr("repo.wiki.pages")
ctx.Data["PageIsWiki"] = true c.Data["PageIsWiki"] = true
if !ctx.Repo.Repository.HasWiki() { if !c.Repo.Repository.HasWiki() {
ctx.Redirect(ctx.Repo.RepoLink + "/wiki") c.Redirect(c.Repo.RepoLink + "/wiki")
return return
} }
wikiRepo, err := git.OpenRepository(ctx.Repo.Repository.WikiPath()) wikiRepo, err := git.OpenRepository(c.Repo.Repository.WikiPath())
if err != nil { if err != nil {
ctx.Handle(500, "OpenRepository", err) c.Handle(500, "OpenRepository", err)
return return
} }
commit, err := wikiRepo.GetBranchCommit("master") commit, err := wikiRepo.GetBranchCommit("master")
if err != nil { if err != nil {
ctx.Handle(500, "GetBranchCommit", err) c.Handle(500, "GetBranchCommit", err)
return return
} }
entries, err := commit.ListEntries() entries, err := commit.ListEntries()
if err != nil { if err != nil {
ctx.Handle(500, "ListEntries", err) c.Handle(500, "ListEntries", err)
return return
} }
pages := make([]PageMeta, 0, len(entries)) pages := make([]PageMeta, 0, len(entries))
for i := range entries { for i := range entries {
if entries[i].Type == git.OBJECT_BLOB && strings.HasSuffix(entries[i].Name(), ".md") { if entries[i].Type == git.OBJECT_BLOB && strings.HasSuffix(entries[i].Name(), ".md") {
c, err := wikiRepo.GetCommitByPath(entries[i].Name()) commit, err := wikiRepo.GetCommitByPath(entries[i].Name())
if err != nil { if err != nil {
ctx.Handle(500, "GetCommit", err) c.ServerError("GetCommitByPath", err)
return return
} }
name := strings.TrimSuffix(entries[i].Name(), ".md") name := strings.TrimSuffix(entries[i].Name(), ".md")
pages = append(pages, PageMeta{ pages = append(pages, PageMeta{
Name: name, Name: name,
URL: models.ToWikiPageURL(name), URL: models.ToWikiPageURL(name),
Updated: c.Author.When, Updated: commit.Author.When,
}) })
} }
} }
ctx.Data["Pages"] = pages c.Data["Pages"] = pages
ctx.HTML(200, WIKI_PAGES) c.HTML(200, WIKI_PAGES)
} }
func NewWiki(ctx *context.Context) { func NewWiki(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page") c.Data["Title"] = c.Tr("repo.wiki.new_page")
ctx.Data["PageIsWiki"] = true c.Data["PageIsWiki"] = true
ctx.Data["RequireSimpleMDE"] = true c.Data["RequireSimpleMDE"] = true
if !ctx.Repo.Repository.HasWiki() { if !c.Repo.Repository.HasWiki() {
ctx.Data["title"] = "Home" c.Data["title"] = "Home"
} }
ctx.HTML(200, WIKI_NEW) c.HTML(200, WIKI_NEW)
} }
func NewWikiPost(ctx *context.Context, f form.NewWiki) { func NewWikiPost(c *context.Context, f form.NewWiki) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page") c.Data["Title"] = c.Tr("repo.wiki.new_page")
ctx.Data["PageIsWiki"] = true c.Data["PageIsWiki"] = true
ctx.Data["RequireSimpleMDE"] = true c.Data["RequireSimpleMDE"] = true
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, WIKI_NEW) c.HTML(200, WIKI_NEW)
return return
} }
if err := ctx.Repo.Repository.AddWikiPage(ctx.User, f.Title, f.Content, f.Message); err != nil { if err := c.Repo.Repository.AddWikiPage(c.User, f.Title, f.Content, f.Message); err != nil {
if models.IsErrWikiAlreadyExist(err) { if models.IsErrWikiAlreadyExist(err) {
ctx.Data["Err_Title"] = true c.Data["Err_Title"] = true
ctx.RenderWithErr(ctx.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &f) c.RenderWithErr(c.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &f)
} else { } else {
ctx.Handle(500, "AddWikiPage", err) c.Handle(500, "AddWikiPage", err)
} }
return return
} }
ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(models.ToWikiPageName(f.Title))) c.Redirect(c.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(models.ToWikiPageName(f.Title)))
} }
func EditWiki(ctx *context.Context) { func EditWiki(c *context.Context) {
ctx.Data["PageIsWiki"] = true c.Data["PageIsWiki"] = true
ctx.Data["PageIsWikiEdit"] = true c.Data["PageIsWikiEdit"] = true
ctx.Data["RequireSimpleMDE"] = true c.Data["RequireSimpleMDE"] = true
if !ctx.Repo.Repository.HasWiki() { if !c.Repo.Repository.HasWiki() {
ctx.Redirect(ctx.Repo.RepoLink + "/wiki") c.Redirect(c.Repo.RepoLink + "/wiki")
return return
} }
renderWikiPage(ctx, false) renderWikiPage(c, false)
if ctx.Written() { if c.Written() {
return return
} }
ctx.HTML(200, WIKI_NEW) c.HTML(200, WIKI_NEW)
} }
func EditWikiPost(ctx *context.Context, f form.NewWiki) { func EditWikiPost(c *context.Context, f form.NewWiki) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page") c.Data["Title"] = c.Tr("repo.wiki.new_page")
ctx.Data["PageIsWiki"] = true c.Data["PageIsWiki"] = true
ctx.Data["RequireSimpleMDE"] = true c.Data["RequireSimpleMDE"] = true
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, WIKI_NEW) c.HTML(200, WIKI_NEW)
return return
} }
if err := ctx.Repo.Repository.EditWikiPage(ctx.User, f.OldTitle, f.Title, f.Content, f.Message); err != nil { if err := c.Repo.Repository.EditWikiPage(c.User, f.OldTitle, f.Title, f.Content, f.Message); err != nil {
ctx.Handle(500, "EditWikiPage", err) c.Handle(500, "EditWikiPage", err)
return return
} }
ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(models.ToWikiPageName(f.Title))) c.Redirect(c.Repo.RepoLink + "/wiki/" + models.ToWikiPageURL(models.ToWikiPageName(f.Title)))
} }
func DeleteWikiPagePost(ctx *context.Context) { func DeleteWikiPagePost(c *context.Context) {
pageURL := ctx.Params(":page") pageURL := c.Params(":page")
if len(pageURL) == 0 { if len(pageURL) == 0 {
pageURL = "Home" pageURL = "Home"
} }
pageName := models.ToWikiPageName(pageURL) pageName := models.ToWikiPageName(pageURL)
if err := ctx.Repo.Repository.DeleteWikiPage(ctx.User, pageName); err != nil { if err := c.Repo.Repository.DeleteWikiPage(c.User, pageName); err != nil {
ctx.Handle(500, "DeleteWikiPage", err) c.Handle(500, "DeleteWikiPage", err)
return return
} }
ctx.JSON(200, map[string]interface{}{ c.JSON(200, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/wiki/", "redirect": c.Repo.RepoLink + "/wiki/",
}) })
} }

230
routers/user/auth.go

@ -240,53 +240,53 @@ func LoginTwoFactorRecoveryCodePost(c *context.Context) {
afterLogin(c, u, c.Session.Get("twoFactorRemember").(bool)) afterLogin(c, u, c.Session.Get("twoFactorRemember").(bool))
} }
func SignOut(ctx *context.Context) { func SignOut(c *context.Context) {
ctx.Session.Delete("uid") c.Session.Delete("uid")
ctx.Session.Delete("uname") c.Session.Delete("uname")
ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL) c.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL) c.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL) c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
ctx.Redirect(setting.AppSubURL + "/") c.Redirect(setting.AppSubURL + "/")
} }
func SignUp(ctx *context.Context) { func SignUp(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("sign_up") c.Data["Title"] = c.Tr("sign_up")
ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
if setting.Service.DisableRegistration { if setting.Service.DisableRegistration {
ctx.Data["DisableRegistration"] = true c.Data["DisableRegistration"] = true
ctx.HTML(200, SIGNUP) c.HTML(200, SIGNUP)
return return
} }
ctx.HTML(200, SIGNUP) c.HTML(200, SIGNUP)
} }
func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) { func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
ctx.Data["Title"] = ctx.Tr("sign_up") c.Data["Title"] = c.Tr("sign_up")
ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
if setting.Service.DisableRegistration { if setting.Service.DisableRegistration {
ctx.Error(403) c.Error(403)
return return
} }
if ctx.HasError() { if c.HasError() {
ctx.HTML(200, SIGNUP) c.HTML(200, SIGNUP)
return return
} }
if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) { if setting.Service.EnableCaptcha && !cpt.VerifyReq(c.Req) {
ctx.Data["Err_Captcha"] = true c.Data["Err_Captcha"] = true
ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), SIGNUP, &f) c.RenderWithErr(c.Tr("form.captcha_incorrect"), SIGNUP, &f)
return return
} }
if f.Password != f.Retype { if f.Password != f.Retype {
ctx.Data["Err_Password"] = true c.Data["Err_Password"] = true
ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &f) c.RenderWithErr(c.Tr("form.password_not_match"), SIGNUP, &f)
return return
} }
@ -299,19 +299,19 @@ func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) {
if err := models.CreateUser(u); err != nil { if err := models.CreateUser(u); err != nil {
switch { switch {
case models.IsErrUserAlreadyExist(err): case models.IsErrUserAlreadyExist(err):
ctx.Data["Err_UserName"] = true c.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SIGNUP, &f) c.RenderWithErr(c.Tr("form.username_been_taken"), SIGNUP, &f)
case models.IsErrEmailAlreadyUsed(err): case models.IsErrEmailAlreadyUsed(err):
ctx.Data["Err_Email"] = true c.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &f) c.RenderWithErr(c.Tr("form.email_been_used"), SIGNUP, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
ctx.Data["Err_UserName"] = true c.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f) c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_UserName"] = true c.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f) c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f)
default: default:
ctx.Handle(500, "CreateUser", err) c.Handle(500, "CreateUser", err)
} }
return return
} }
@ -322,53 +322,53 @@ func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) {
u.IsAdmin = true u.IsAdmin = true
u.IsActive = true u.IsActive = true
if err := models.UpdateUser(u); err != nil { if err := models.UpdateUser(u); err != nil {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
return return
} }
} }
// Send confirmation email, no need for social account. // Send confirmation email, no need for social account.
if setting.Service.RegisterEmailConfirm && u.ID > 1 { if setting.Service.RegisterEmailConfirm && u.ID > 1 {
mailer.SendActivateAccountMail(ctx.Context, models.NewMailerUser(u)) mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(u))
ctx.Data["IsSendRegisterMail"] = true c.Data["IsSendRegisterMail"] = true
ctx.Data["Email"] = u.Email c.Data["Email"] = u.Email
ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
ctx.HTML(200, ACTIVATE) c.HTML(200, ACTIVATE)
if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { if err := c.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error(4, "Set cache(MailResendLimit) fail: %v", err) log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
} }
return return
} }
ctx.Redirect(setting.AppSubURL + "/user/login") c.Redirect(setting.AppSubURL + "/user/login")
} }
func Activate(ctx *context.Context) { func Activate(c *context.Context) {
code := ctx.Query("code") code := c.Query("code")
if len(code) == 0 { if len(code) == 0 {
ctx.Data["IsActivatePage"] = true c.Data["IsActivatePage"] = true
if ctx.User.IsActive { if c.User.IsActive {
ctx.Error(404) c.Error(404)
return return
} }
// Resend confirmation email. // Resend confirmation email.
if setting.Service.RegisterEmailConfirm { if setting.Service.RegisterEmailConfirm {
if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) { if c.Cache.IsExist("MailResendLimit_" + c.User.LowerName) {
ctx.Data["ResendLimited"] = true c.Data["ResendLimited"] = true
} else { } else {
ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
mailer.SendActivateAccountMail(ctx.Context, models.NewMailerUser(ctx.User)) mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(c.User))
keyName := "MailResendLimit_" + ctx.User.LowerName keyName := "MailResendLimit_" + c.User.LowerName
if err := ctx.Cache.Put(keyName, ctx.User.LowerName, 180); err != nil { if err := c.Cache.Put(keyName, c.User.LowerName, 180); err != nil {
log.Error(2, "Set cache '%s' fail: %v", keyName, err) log.Error(2, "Set cache '%s' fail: %v", keyName, err)
} }
} }
} else { } else {
ctx.Data["ServiceNotEnabled"] = true c.Data["ServiceNotEnabled"] = true
} }
ctx.HTML(200, ACTIVATE) c.HTML(200, ACTIVATE)
return return
} }
@ -377,158 +377,158 @@ func Activate(ctx *context.Context) {
user.IsActive = true user.IsActive = true
var err error var err error
if user.Rands, err = models.GetUserSalt(); err != nil { if user.Rands, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
return return
} }
if err := models.UpdateUser(user); err != nil { if err := models.UpdateUser(user); err != nil {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
return return
} }
log.Trace("User activated: %s", user.Name) log.Trace("User activated: %s", user.Name)
ctx.Session.Set("uid", user.ID) c.Session.Set("uid", user.ID)
ctx.Session.Set("uname", user.Name) c.Session.Set("uname", user.Name)
ctx.Redirect(setting.AppSubURL + "/") c.Redirect(setting.AppSubURL + "/")
return return
} }
ctx.Data["IsActivateFailed"] = true c.Data["IsActivateFailed"] = true
ctx.HTML(200, ACTIVATE) c.HTML(200, ACTIVATE)
} }
func ActivateEmail(ctx *context.Context) { func ActivateEmail(c *context.Context) {
code := ctx.Query("code") code := c.Query("code")
email_string := ctx.Query("email") email_string := c.Query("email")
// Verify code. // Verify code.
if email := models.VerifyActiveEmailCode(code, email_string); email != nil { if email := models.VerifyActiveEmailCode(code, email_string); email != nil {
if err := email.Activate(); err != nil { if err := email.Activate(); err != nil {
ctx.Handle(500, "ActivateEmail", err) c.Handle(500, "ActivateEmail", err)
} }
log.Trace("Email activated: %s", email.Email) log.Trace("Email activated: %s", email.Email)
ctx.Flash.Success(ctx.Tr("settings.add_email_success")) c.Flash.Success(c.Tr("settings.add_email_success"))
} }
ctx.Redirect(setting.AppSubURL + "/user/settings/email") c.Redirect(setting.AppSubURL + "/user/settings/email")
return return
} }
func ForgotPasswd(ctx *context.Context) { func ForgotPasswd(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("auth.forgot_password") c.Data["Title"] = c.Tr("auth.forgot_password")
if setting.MailService == nil { if setting.MailService == nil {
ctx.Data["IsResetDisable"] = true c.Data["IsResetDisable"] = true
ctx.HTML(200, FORGOT_PASSWORD) c.HTML(200, FORGOT_PASSWORD)
return return
} }
ctx.Data["IsResetRequest"] = true c.Data["IsResetRequest"] = true
ctx.HTML(200, FORGOT_PASSWORD) c.HTML(200, FORGOT_PASSWORD)
} }
func ForgotPasswdPost(ctx *context.Context) { func ForgotPasswdPost(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("auth.forgot_password") c.Data["Title"] = c.Tr("auth.forgot_password")
if setting.MailService == nil { if setting.MailService == nil {
ctx.Handle(403, "ForgotPasswdPost", nil) c.Handle(403, "ForgotPasswdPost", nil)
return return
} }
ctx.Data["IsResetRequest"] = true c.Data["IsResetRequest"] = true
email := ctx.Query("email") email := c.Query("email")
ctx.Data["Email"] = email c.Data["Email"] = email
u, err := models.GetUserByEmail(email) u, err := models.GetUserByEmail(email)
if err != nil { if err != nil {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
ctx.Data["IsResetSent"] = true c.Data["IsResetSent"] = true
ctx.HTML(200, FORGOT_PASSWORD) c.HTML(200, FORGOT_PASSWORD)
return return
} else { } else {
ctx.Handle(500, "user.ResetPasswd(check existence)", err) c.Handle(500, "user.ResetPasswd(check existence)", err)
} }
return return
} }
if !u.IsLocal() { if !u.IsLocal() {
ctx.Data["Err_Email"] = true c.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil) c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
return return
} }
if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) { if c.Cache.IsExist("MailResendLimit_" + u.LowerName) {
ctx.Data["ResendLimited"] = true c.Data["ResendLimited"] = true
ctx.HTML(200, FORGOT_PASSWORD) c.HTML(200, FORGOT_PASSWORD)
return return
} }
mailer.SendResetPasswordMail(ctx.Context, models.NewMailerUser(u)) mailer.SendResetPasswordMail(c.Context, models.NewMailerUser(u))
if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { if err = c.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error(4, "Set cache(MailResendLimit) fail: %v", err) log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
} }
ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
ctx.Data["IsResetSent"] = true c.Data["IsResetSent"] = true
ctx.HTML(200, FORGOT_PASSWORD) c.HTML(200, FORGOT_PASSWORD)
} }
func ResetPasswd(ctx *context.Context) { func ResetPasswd(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("auth.reset_password") c.Data["Title"] = c.Tr("auth.reset_password")
code := ctx.Query("code") code := c.Query("code")
if len(code) == 0 { if len(code) == 0 {
ctx.Error(404) c.Error(404)
return return
} }
ctx.Data["Code"] = code c.Data["Code"] = code
ctx.Data["IsResetForm"] = true c.Data["IsResetForm"] = true
ctx.HTML(200, RESET_PASSWORD) c.HTML(200, RESET_PASSWORD)
} }
func ResetPasswdPost(ctx *context.Context) { func ResetPasswdPost(c *context.Context) {
ctx.Data["Title"] = ctx.Tr("auth.reset_password") c.Data["Title"] = c.Tr("auth.reset_password")
code := ctx.Query("code") code := c.Query("code")
if len(code) == 0 { if len(code) == 0 {
ctx.Error(404) c.Error(404)
return return
} }
ctx.Data["Code"] = code c.Data["Code"] = code
if u := models.VerifyUserActiveCode(code); u != nil { if u := models.VerifyUserActiveCode(code); u != nil {
// Validate password length. // Validate password length.
passwd := ctx.Query("password") passwd := c.Query("password")
if len(passwd) < 6 { if len(passwd) < 6 {
ctx.Data["IsResetForm"] = true c.Data["IsResetForm"] = true
ctx.Data["Err_Password"] = true c.Data["Err_Password"] = true
ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil) c.RenderWithErr(c.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
return return
} }
u.Passwd = passwd u.Passwd = passwd
var err error var err error
if u.Rands, err = models.GetUserSalt(); err != nil { if u.Rands, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
return return
} }
if u.Salt, err = models.GetUserSalt(); err != nil { if u.Salt, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
return return
} }
u.EncodePasswd() u.EncodePasswd()
if err := models.UpdateUser(u); err != nil { if err := models.UpdateUser(u); err != nil {
ctx.Handle(500, "UpdateUser", err) c.Handle(500, "UpdateUser", err)
return return
} }
log.Trace("User password reset: %s", u.Name) log.Trace("User password reset: %s", u.Name)
ctx.Redirect(setting.AppSubURL + "/user/login") c.Redirect(setting.AppSubURL + "/user/login")
return return
} }
ctx.Data["IsResetFailed"] = true c.Data["IsResetFailed"] = true
ctx.HTML(200, RESET_PASSWORD) c.HTML(200, RESET_PASSWORD)
} }

204
routers/user/home.go

@ -26,25 +26,25 @@ const (
) )
// getDashboardContextUser finds out dashboard is viewing as which context user. // getDashboardContextUser finds out dashboard is viewing as which context user.
func getDashboardContextUser(ctx *context.Context) *models.User { func getDashboardContextUser(c *context.Context) *models.User {
ctxUser := ctx.User ctxUser := c.User
orgName := ctx.Params(":org") orgName := c.Params(":org")
if len(orgName) > 0 { if len(orgName) > 0 {
// Organization. // Organization.
org, err := models.GetUserByName(orgName) org, err := models.GetUserByName(orgName)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return nil return nil
} }
ctxUser = org ctxUser = org
} }
ctx.Data["ContextUser"] = ctxUser c.Data["ContextUser"] = ctxUser
if err := ctx.User.GetOrganizations(true); err != nil { if err := c.User.GetOrganizations(true); err != nil {
ctx.Handle(500, "GetOrganizations", err) c.Handle(500, "GetOrganizations", err)
return nil return nil
} }
ctx.Data["Orgs"] = ctx.User.Orgs c.Data["Orgs"] = c.User.Orgs
return ctxUser return ctxUser
} }
@ -52,10 +52,10 @@ func getDashboardContextUser(ctx *context.Context) *models.User {
// retrieveFeeds loads feeds from database by given context user. // retrieveFeeds loads feeds from database by given context user.
// The user could be organization so it is not always the logged in user, // The user could be organization so it is not always the logged in user,
// which is why we have to explicitly pass the context user ID. // which is why we have to explicitly pass the context user ID.
func retrieveFeeds(ctx *context.Context, ctxUser *models.User, userID int64, isProfile bool) { func retrieveFeeds(c *context.Context, ctxUser *models.User, userID int64, isProfile bool) {
actions, err := models.GetFeeds(ctxUser, userID, ctx.QueryInt64("after_id"), isProfile) actions, err := models.GetFeeds(ctxUser, userID, c.QueryInt64("after_id"), isProfile)
if err != nil { if err != nil {
ctx.Handle(500, "GetFeeds", err) c.Handle(500, "GetFeeds", err)
return return
} }
@ -71,7 +71,7 @@ func retrieveFeeds(ctx *context.Context, ctxUser *models.User, userID int64, isP
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
continue continue
} }
ctx.Handle(500, "GetUserByName", err) c.Handle(500, "GetUserByName", err)
return return
} }
unameAvatars[act.ActUserName] = u.RelAvatarLink() unameAvatars[act.ActUserName] = u.RelAvatarLink()
@ -80,65 +80,65 @@ func retrieveFeeds(ctx *context.Context, ctxUser *models.User, userID int64, isP
act.ActAvatar = unameAvatars[act.ActUserName] act.ActAvatar = unameAvatars[act.ActUserName]
feeds = append(feeds, act) feeds = append(feeds, act)
} }
ctx.Data["Feeds"] = feeds c.Data["Feeds"] = feeds
if len(feeds) > 0 { if len(feeds) > 0 {
afterID := feeds[len(feeds)-1].ID afterID := feeds[len(feeds)-1].ID
ctx.Data["AfterID"] = afterID c.Data["AfterID"] = afterID
ctx.Header().Set("X-AJAX-URL", fmt.Sprintf("%s?after_id=%d", ctx.Data["Link"], afterID)) c.Header().Set("X-AJAX-URL", fmt.Sprintf("%s?after_id=%d", c.Data["Link"], afterID))
} }
} }
func Dashboard(ctx *context.Context) { func Dashboard(c *context.Context) {
ctxUser := getDashboardContextUser(ctx) ctxUser := getDashboardContextUser(c)
if ctx.Written() { if c.Written() {
return return
} }
retrieveFeeds(ctx, ctxUser, ctx.User.ID, false) retrieveFeeds(c, ctxUser, c.User.ID, false)
if ctx.Written() { if c.Written() {
return return
} }
if ctx.Req.Header.Get("X-AJAX") == "true" { if c.Req.Header.Get("X-AJAX") == "true" {
ctx.HTML(200, NEWS_FEED) c.HTML(200, NEWS_FEED)
return return
} }
ctx.Data["Title"] = ctxUser.DisplayName() + " - " + ctx.Tr("dashboard") c.Data["Title"] = ctxUser.DisplayName() + " - " + c.Tr("dashboard")
ctx.Data["PageIsDashboard"] = true c.Data["PageIsDashboard"] = true
ctx.Data["PageIsNews"] = true c.Data["PageIsNews"] = true
// Only user can have collaborative repositories. // Only user can have collaborative repositories.
if !ctxUser.IsOrganization() { if !ctxUser.IsOrganization() {
collaborateRepos, err := ctx.User.GetAccessibleRepositories(setting.UI.User.RepoPagingNum) collaborateRepos, err := c.User.GetAccessibleRepositories(setting.UI.User.RepoPagingNum)
if err != nil { if err != nil {
ctx.Handle(500, "GetAccessibleRepositories", err) c.Handle(500, "GetAccessibleRepositories", err)
return return
} else if err = models.RepositoryList(collaborateRepos).LoadAttributes(); err != nil { } else if err = models.RepositoryList(collaborateRepos).LoadAttributes(); err != nil {
ctx.Handle(500, "RepositoryList.LoadAttributes", err) c.Handle(500, "RepositoryList.LoadAttributes", err)
return return
} }
ctx.Data["CollaborativeRepos"] = collaborateRepos c.Data["CollaborativeRepos"] = collaborateRepos
} }
var err error var err error
var repos, mirrors []*models.Repository var repos, mirrors []*models.Repository
var repoCount int64 var repoCount int64
if ctxUser.IsOrganization() { if ctxUser.IsOrganization() {
repos, repoCount, err = ctxUser.GetUserRepositories(ctx.User.ID, 1, setting.UI.User.RepoPagingNum) repos, repoCount, err = ctxUser.GetUserRepositories(c.User.ID, 1, setting.UI.User.RepoPagingNum)
if err != nil { if err != nil {
ctx.Handle(500, "GetUserRepositories", err) c.Handle(500, "GetUserRepositories", err)
return return
} }
mirrors, err = ctxUser.GetUserMirrorRepositories(ctx.User.ID) mirrors, err = ctxUser.GetUserMirrorRepositories(c.User.ID)
if err != nil { if err != nil {
ctx.Handle(500, "GetUserMirrorRepositories", err) c.Handle(500, "GetUserMirrorRepositories", err)
return return
} }
} else { } else {
if err = ctxUser.GetRepositories(1, setting.UI.User.RepoPagingNum); err != nil { if err = ctxUser.GetRepositories(1, setting.UI.User.RepoPagingNum); err != nil {
ctx.Handle(500, "GetRepositories", err) c.Handle(500, "GetRepositories", err)
return return
} }
repos = ctxUser.Repos repos = ctxUser.Repos
@ -146,47 +146,47 @@ func Dashboard(ctx *context.Context) {
mirrors, err = ctxUser.GetMirrorRepositories() mirrors, err = ctxUser.GetMirrorRepositories()
if err != nil { if err != nil {
ctx.Handle(500, "GetMirrorRepositories", err) c.Handle(500, "GetMirrorRepositories", err)
return return
} }
} }
ctx.Data["Repos"] = repos c.Data["Repos"] = repos
ctx.Data["RepoCount"] = repoCount c.Data["RepoCount"] = repoCount
ctx.Data["MaxShowRepoNum"] = setting.UI.User.RepoPagingNum c.Data["MaxShowRepoNum"] = setting.UI.User.RepoPagingNum
if err := models.MirrorRepositoryList(mirrors).LoadAttributes(); err != nil { if err := models.MirrorRepositoryList(mirrors).LoadAttributes(); err != nil {
ctx.Handle(500, "MirrorRepositoryList.LoadAttributes", err) c.Handle(500, "MirrorRepositoryList.LoadAttributes", err)
return return
} }
ctx.Data["MirrorCount"] = len(mirrors) c.Data["MirrorCount"] = len(mirrors)
ctx.Data["Mirrors"] = mirrors c.Data["Mirrors"] = mirrors
ctx.HTML(200, DASHBOARD) c.HTML(200, DASHBOARD)
} }
func Issues(ctx *context.Context) { func Issues(c *context.Context) {
isPullList := ctx.Params(":type") == "pulls" isPullList := c.Params(":type") == "pulls"
if isPullList { if isPullList {
ctx.Data["Title"] = ctx.Tr("pull_requests") c.Data["Title"] = c.Tr("pull_requests")
ctx.Data["PageIsPulls"] = true c.Data["PageIsPulls"] = true
} else { } else {
ctx.Data["Title"] = ctx.Tr("issues") c.Data["Title"] = c.Tr("issues")
ctx.Data["PageIsIssues"] = true c.Data["PageIsIssues"] = true
} }
ctxUser := getDashboardContextUser(ctx) ctxUser := getDashboardContextUser(c)
if ctx.Written() { if c.Written() {
return return
} }
var ( var (
sortType = ctx.Query("sort") sortType = c.Query("sort")
filterMode = models.FILTER_MODE_YOUR_REPOS filterMode = models.FILTER_MODE_YOUR_REPOS
) )
// Note: Organization does not have view type and filter mode. // Note: Organization does not have view type and filter mode.
if !ctxUser.IsOrganization() { if !ctxUser.IsOrganization() {
viewType := ctx.Query("type") viewType := c.Query("type")
types := []string{ types := []string{
string(models.FILTER_MODE_YOUR_REPOS), string(models.FILTER_MODE_YOUR_REPOS),
string(models.FILTER_MODE_ASSIGN), string(models.FILTER_MODE_ASSIGN),
@ -198,13 +198,13 @@ func Issues(ctx *context.Context) {
filterMode = models.FilterMode(viewType) filterMode = models.FilterMode(viewType)
} }
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page <= 1 { if page <= 1 {
page = 1 page = 1
} }
repoID := ctx.QueryInt64("repo") repoID := c.QueryInt64("repo")
isShowClosed := ctx.Query("state") == "closed" isShowClosed := c.Query("state") == "closed"
// Get repositories. // Get repositories.
var ( var (
@ -214,14 +214,14 @@ func Issues(ctx *context.Context) {
showRepos = make([]*models.Repository, 0, 10) showRepos = make([]*models.Repository, 0, 10)
) )
if ctxUser.IsOrganization() { if ctxUser.IsOrganization() {
repos, _, err = ctxUser.GetUserRepositories(ctx.User.ID, 1, ctxUser.NumRepos) repos, _, err = ctxUser.GetUserRepositories(c.User.ID, 1, ctxUser.NumRepos)
if err != nil { if err != nil {
ctx.Handle(500, "GetRepositories", err) c.Handle(500, "GetRepositories", err)
return return
} }
} else { } else {
if err := ctxUser.GetRepositories(1, ctx.User.NumRepos); err != nil { if err := ctxUser.GetRepositories(1, c.User.NumRepos); err != nil {
ctx.Handle(500, "GetRepositories", err) c.Handle(500, "GetRepositories", err)
return return
} }
repos = ctxUser.Repos repos = ctxUser.Repos
@ -255,7 +255,7 @@ func Issues(ctx *context.Context) {
if !isPullList { if !isPullList {
userRepoIDs, err = models.FilterRepositoryWithIssues(userRepoIDs) userRepoIDs, err = models.FilterRepositoryWithIssues(userRepoIDs)
if err != nil { if err != nil {
ctx.Handle(500, "FilterRepositoryWithIssues", err) c.Handle(500, "FilterRepositoryWithIssues", err)
return return
} }
} }
@ -287,32 +287,32 @@ func Issues(ctx *context.Context) {
issues, err := models.Issues(issueOptions) issues, err := models.Issues(issueOptions)
if err != nil { if err != nil {
ctx.Handle(500, "Issues", err) c.Handle(500, "Issues", err)
return return
} }
if repoID > 0 { if repoID > 0 {
repo, err := models.GetRepositoryByID(repoID) repo, err := models.GetRepositoryByID(repoID)
if err != nil { if err != nil {
ctx.Handle(500, "GetRepositoryByID", fmt.Errorf("[#%d] %v", repoID, err)) c.Handle(500, "GetRepositoryByID", fmt.Errorf("[#%d] %v", repoID, err))
return return
} }
if err = repo.GetOwner(); err != nil { if err = repo.GetOwner(); err != nil {
ctx.Handle(500, "GetOwner", fmt.Errorf("[#%d] %v", repoID, err)) c.Handle(500, "GetOwner", fmt.Errorf("[#%d] %v", repoID, err))
return return
} }
// Check if user has access to given repository. // Check if user has access to given repository.
if !repo.IsOwnedBy(ctxUser.ID) && !repo.HasAccess(ctxUser.ID) { if !repo.IsOwnedBy(ctxUser.ID) && !repo.HasAccess(ctxUser.ID) {
ctx.Handle(404, "Issues", fmt.Errorf("#%d", repoID)) c.Handle(404, "Issues", fmt.Errorf("#%d", repoID))
return return
} }
} }
for _, issue := range issues { for _, issue := range issues {
if err = issue.Repo.GetOwner(); err != nil { if err = issue.Repo.GetOwner(); err != nil {
ctx.Handle(500, "GetOwner", fmt.Errorf("[#%d] %v", issue.RepoID, err)) c.Handle(500, "GetOwner", fmt.Errorf("[#%d] %v", issue.RepoID, err))
return return
} }
} }
@ -326,28 +326,28 @@ func Issues(ctx *context.Context) {
total = int(issueStats.ClosedCount) total = int(issueStats.ClosedCount)
} }
ctx.Data["Issues"] = issues c.Data["Issues"] = issues
ctx.Data["Repos"] = showRepos c.Data["Repos"] = showRepos
ctx.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5) c.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5)
ctx.Data["IssueStats"] = issueStats c.Data["IssueStats"] = issueStats
ctx.Data["ViewType"] = string(filterMode) c.Data["ViewType"] = string(filterMode)
ctx.Data["SortType"] = sortType c.Data["SortType"] = sortType
ctx.Data["RepoID"] = repoID c.Data["RepoID"] = repoID
ctx.Data["IsShowClosed"] = isShowClosed c.Data["IsShowClosed"] = isShowClosed
if isShowClosed { if isShowClosed {
ctx.Data["State"] = "closed" c.Data["State"] = "closed"
} else { } else {
ctx.Data["State"] = "open" c.Data["State"] = "open"
} }
ctx.HTML(200, ISSUES) c.HTML(200, ISSUES)
} }
func ShowSSHKeys(ctx *context.Context, uid int64) { func ShowSSHKeys(c *context.Context, uid int64) {
keys, err := models.ListPublicKeys(uid) keys, err := models.ListPublicKeys(uid)
if err != nil { if err != nil {
ctx.Handle(500, "ListPublicKeys", err) c.Handle(500, "ListPublicKeys", err)
return return
} }
@ -356,20 +356,20 @@ func ShowSSHKeys(ctx *context.Context, uid int64) {
buf.WriteString(keys[i].OmitEmail()) buf.WriteString(keys[i].OmitEmail())
buf.WriteString("\n") buf.WriteString("\n")
} }
ctx.PlainText(200, buf.Bytes()) c.PlainText(200, buf.Bytes())
} }
func showOrgProfile(ctx *context.Context) { func showOrgProfile(c *context.Context) {
ctx.SetParams(":org", ctx.Params(":username")) c.SetParams(":org", c.Params(":username"))
context.HandleOrgAssignment(ctx) context.HandleOrgAssignment(c)
if ctx.Written() { if c.Written() {
return return
} }
org := ctx.Org.Organization org := c.Org.Organization
ctx.Data["Title"] = org.FullName c.Data["Title"] = org.FullName
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page <= 0 { if page <= 0 {
page = 1 page = 1
} }
@ -379,15 +379,15 @@ func showOrgProfile(ctx *context.Context) {
count int64 count int64
err error err error
) )
if ctx.IsLogged && !ctx.User.IsAdmin { if c.IsLogged && !c.User.IsAdmin {
repos, count, err = org.GetUserRepositories(ctx.User.ID, page, setting.UI.User.RepoPagingNum) repos, count, err = org.GetUserRepositories(c.User.ID, page, setting.UI.User.RepoPagingNum)
if err != nil { if err != nil {
ctx.Handle(500, "GetUserRepositories", err) c.Handle(500, "GetUserRepositories", err)
return return
} }
ctx.Data["Repos"] = repos c.Data["Repos"] = repos
} else { } else {
showPrivate := ctx.IsLogged && ctx.User.IsAdmin showPrivate := c.IsLogged && c.User.IsAdmin
repos, err = models.GetUserRepositories(&models.UserRepoOptions{ repos, err = models.GetUserRepositories(&models.UserRepoOptions{
UserID: org.ID, UserID: org.ID,
Private: showPrivate, Private: showPrivate,
@ -395,30 +395,30 @@ func showOrgProfile(ctx *context.Context) {
PageSize: setting.UI.User.RepoPagingNum, PageSize: setting.UI.User.RepoPagingNum,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "GetRepositories", err) c.Handle(500, "GetRepositories", err)
return return
} }
ctx.Data["Repos"] = repos c.Data["Repos"] = repos
count = models.CountUserRepositories(org.ID, showPrivate) count = models.CountUserRepositories(org.ID, showPrivate)
} }
ctx.Data["Page"] = paginater.New(int(count), setting.UI.User.RepoPagingNum, page, 5) c.Data["Page"] = paginater.New(int(count), setting.UI.User.RepoPagingNum, page, 5)
if err := org.GetMembers(); err != nil { if err := org.GetMembers(); err != nil {
ctx.Handle(500, "GetMembers", err) c.Handle(500, "GetMembers", err)
return return
} }
ctx.Data["Members"] = org.Members c.Data["Members"] = org.Members
ctx.Data["Teams"] = org.Teams c.Data["Teams"] = org.Teams
ctx.HTML(200, ORG_HOME) c.HTML(200, ORG_HOME)
} }
func Email2User(ctx *context.Context) { func Email2User(c *context.Context) {
u, err := models.GetUserByEmail(ctx.Query("email")) u, err := models.GetUserByEmail(c.Query("email"))
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByEmail", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByEmail", errors.IsUserNotExist, err)
return return
} }
ctx.Redirect(setting.AppSubURL + "/user/" + u.Name) c.Redirect(setting.AppSubURL + "/user/" + u.Name)
} }

108
routers/user/profile.go

@ -23,28 +23,28 @@ const (
STARS = "user/meta/stars" STARS = "user/meta/stars"
) )
func GetUserByName(ctx *context.Context, name string) *models.User { func GetUserByName(c *context.Context, name string) *models.User {
user, err := models.GetUserByName(name) user, err := models.GetUserByName(name)
if err != nil { if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err) c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return nil return nil
} }
return user return user
} }
// GetUserByParams returns user whose name is presented in URL paramenter. // GetUserByParams returns user whose name is presented in URL paramenter.
func GetUserByParams(ctx *context.Context) *models.User { func GetUserByParams(c *context.Context) *models.User {
return GetUserByName(ctx, ctx.Params(":username")) return GetUserByName(c, c.Params(":username"))
} }
func Profile(ctx *context.Context) { func Profile(c *context.Context) {
uname := ctx.Params(":username") uname := c.Params(":username")
// Special handle for FireFox requests favicon.ico. // Special handle for FireFox requests favicon.ico.
if uname == "favicon.ico" { if uname == "favicon.ico" {
ctx.ServeFile(path.Join(setting.StaticRootPath, "public/img/favicon.png")) c.ServeFile(path.Join(setting.StaticRootPath, "public/img/favicon.png"))
return return
} else if strings.HasSuffix(uname, ".png") { } else if strings.HasSuffix(uname, ".png") {
ctx.Error(404) c.Error(404)
return return
} }
@ -53,117 +53,117 @@ func Profile(ctx *context.Context) {
isShowKeys = true isShowKeys = true
} }
ctxUser := GetUserByName(ctx, strings.TrimSuffix(uname, ".keys")) ctxUser := GetUserByName(c, strings.TrimSuffix(uname, ".keys"))
if ctx.Written() { if c.Written() {
return return
} }
// Show SSH keys. // Show SSH keys.
if isShowKeys { if isShowKeys {
ShowSSHKeys(ctx, ctxUser.ID) ShowSSHKeys(c, ctxUser.ID)
return return
} }
if ctxUser.IsOrganization() { if ctxUser.IsOrganization() {
showOrgProfile(ctx) showOrgProfile(c)
return return
} }
ctx.Data["Title"] = ctxUser.DisplayName() c.Data["Title"] = ctxUser.DisplayName()
ctx.Data["PageIsUserProfile"] = true c.Data["PageIsUserProfile"] = true
ctx.Data["Owner"] = ctxUser c.Data["Owner"] = ctxUser
orgs, err := models.GetOrgsByUserID(ctxUser.ID, ctx.IsLogged && (ctx.User.IsAdmin || ctx.User.ID == ctxUser.ID)) orgs, err := models.GetOrgsByUserID(ctxUser.ID, c.IsLogged && (c.User.IsAdmin || c.User.ID == ctxUser.ID))
if err != nil { if err != nil {
ctx.Handle(500, "GetOrgsByUserIDDesc", err) c.Handle(500, "GetOrgsByUserIDDesc", err)
return return
} }
ctx.Data["Orgs"] = orgs c.Data["Orgs"] = orgs
tab := ctx.Query("tab") tab := c.Query("tab")
ctx.Data["TabName"] = tab c.Data["TabName"] = tab
switch tab { switch tab {
case "activity": case "activity":
retrieveFeeds(ctx, ctxUser, -1, true) retrieveFeeds(c, ctxUser, -1, true)
if ctx.Written() { if c.Written() {
return return
} }
default: default:
page := ctx.QueryInt("page") page := c.QueryInt("page")
if page <= 0 { if page <= 0 {
page = 1 page = 1
} }
showPrivate := ctx.IsLogged && (ctxUser.ID == ctx.User.ID || ctx.User.IsAdmin) showPrivate := c.IsLogged && (ctxUser.ID == c.User.ID || c.User.IsAdmin)
ctx.Data["Repos"], err = models.GetUserRepositories(&models.UserRepoOptions{ c.Data["Repos"], err = models.GetUserRepositories(&models.UserRepoOptions{
UserID: ctxUser.ID, UserID: ctxUser.ID,
Private: showPrivate, Private: showPrivate,
Page: page, Page: page,
PageSize: setting.UI.User.RepoPagingNum, PageSize: setting.UI.User.RepoPagingNum,
}) })
if err != nil { if err != nil {
ctx.Handle(500, "GetRepositories", err) c.Handle(500, "GetRepositories", err)
return return
} }
count := models.CountUserRepositories(ctxUser.ID, showPrivate) count := models.CountUserRepositories(ctxUser.ID, showPrivate)
ctx.Data["Page"] = paginater.New(int(count), setting.UI.User.RepoPagingNum, page, 5) c.Data["Page"] = paginater.New(int(count), setting.UI.User.RepoPagingNum, page, 5)
} }
ctx.HTML(200, PROFILE) c.HTML(200, PROFILE)
} }
func Followers(ctx *context.Context) { func Followers(c *context.Context) {
u := GetUserByParams(ctx) u := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["Title"] = u.DisplayName() c.Data["Title"] = u.DisplayName()
ctx.Data["CardsTitle"] = ctx.Tr("user.followers") c.Data["CardsTitle"] = c.Tr("user.followers")
ctx.Data["PageIsFollowers"] = true c.Data["PageIsFollowers"] = true
ctx.Data["Owner"] = u c.Data["Owner"] = u
repo.RenderUserCards(ctx, u.NumFollowers, u.GetFollowers, FOLLOWERS) repo.RenderUserCards(c, u.NumFollowers, u.GetFollowers, FOLLOWERS)
} }
func Following(ctx *context.Context) { func Following(c *context.Context) {
u := GetUserByParams(ctx) u := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
ctx.Data["Title"] = u.DisplayName() c.Data["Title"] = u.DisplayName()
ctx.Data["CardsTitle"] = ctx.Tr("user.following") c.Data["CardsTitle"] = c.Tr("user.following")
ctx.Data["PageIsFollowing"] = true c.Data["PageIsFollowing"] = true
ctx.Data["Owner"] = u c.Data["Owner"] = u
repo.RenderUserCards(ctx, u.NumFollowing, u.GetFollowing, FOLLOWERS) repo.RenderUserCards(c, u.NumFollowing, u.GetFollowing, FOLLOWERS)
} }
func Stars(ctx *context.Context) { func Stars(c *context.Context) {
} }
func Action(ctx *context.Context) { func Action(c *context.Context) {
u := GetUserByParams(ctx) u := GetUserByParams(c)
if ctx.Written() { if c.Written() {
return return
} }
var err error var err error
switch ctx.Params(":action") { switch c.Params(":action") {
case "follow": case "follow":
err = models.FollowUser(ctx.User.ID, u.ID) err = models.FollowUser(c.User.ID, u.ID)
case "unfollow": case "unfollow":
err = models.UnfollowUser(ctx.User.ID, u.ID) err = models.UnfollowUser(c.User.ID, u.ID)
} }
if err != nil { if err != nil {
ctx.Handle(500, fmt.Sprintf("Action (%s)", ctx.Params(":action")), err) c.Handle(500, fmt.Sprintf("Action (%s)", c.Params(":action")), err)
return return
} }
redirectTo := ctx.Query("redirect_to") redirectTo := c.Query("redirect_to")
if len(redirectTo) == 0 { if len(redirectTo) == 0 {
redirectTo = u.HomeLink() redirectTo = u.HomeLink()
} }
ctx.Redirect(redirectTo) c.Redirect(redirectTo)
} }

Loading…
Cancel
Save