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

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.
// If status is 500, also it prints error to log.
func (ctx *APIContext) Error(status int, title string, obj interface{}) {
func (c *APIContext) Error(status int, title string, obj interface{}) {
var message string
if err, ok := obj.(error); ok {
message = err.Error()
@ -37,39 +37,39 @@ func (ctx *APIContext) Error(status int, title string, obj interface{}) {
log.Error(3, "%s: %s", title, message)
}
ctx.JSON(status, map[string]string{
c.JSON(status, map[string]string{
"message": message,
"url": DOC_URL,
})
}
// SetLinkHeader sets pagination link header by given totol number and page size.
func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
page := paginater.New(total, pageSize, ctx.QueryInt("page"), 0)
func (c *APIContext) SetLinkHeader(total, pageSize int) {
page := paginater.New(total, pageSize, c.QueryInt("page"), 0)
links := make([]string, 0, 4)
if page.HasNext() {
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, ctx.Req.URL.Path[1:], page.Next()))
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, c.Req.URL.Path[1:], page.Next()))
}
if !page.IsLast() {
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, ctx.Req.URL.Path[1:], page.TotalPages()))
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, c.Req.URL.Path[1:], page.TotalPages()))
}
if !page.IsFirst() {
links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, ctx.Req.URL.Path[1:]))
links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, c.Req.URL.Path[1:]))
}
if page.HasPrevious() {
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, ctx.Req.URL.Path[1:], page.Previous()))
links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, c.Req.URL.Path[1:], page.Previous()))
}
if len(links) > 0 {
ctx.Header().Set("Link", strings.Join(links, ","))
c.Header().Set("Link", strings.Join(links, ","))
}
}
func APIContexter() macaron.Handler {
return func(c *Context) {
ctx := &APIContext{
Context: c,
return func(ctx *Context) {
c := &APIContext{
Context: ctx,
}
c.Map(ctx)
ctx.Map(c)
}
}

54
pkg/context/auth.go

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

78
pkg/context/context.go

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

94
pkg/context/org.go

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

270
pkg/context/repo.go

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

126
routers/admin/admin.go

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

156
routers/admin/auths.go

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

42
routers/admin/notice.go

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

10
routers/admin/orgs.go

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

42
routers/admin/repos.go

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

164
routers/admin/users.go

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

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
func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) {
u := user.GetUserByParams(ctx)
if ctx.Written() {
func CreateOrg(c *context.APIContext, form api.CreateOrgOption) {
u := user.GetUserByParams(c)
if c.Written() {
return
}
@ -33,12 +33,12 @@ func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) {
if models.IsErrUserAlreadyExist(err) ||
models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) {
ctx.Error(422, "", err)
c.Error(422, "", err)
} else {
ctx.Error(500, "CreateOrganization", err)
c.Error(500, "CreateOrganization", err)
}
return
}
ctx.JSON(201, convert.ToOrganization(org))
c.JSON(201, convert.ToOrganization(org))
}

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

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

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

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

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
func CreateRepo(ctx *context.APIContext, form api.CreateRepoOption) {
owner := user.GetUserByParams(ctx)
if ctx.Written() {
func CreateRepo(c *context.APIContext, form api.CreateRepoOption) {
owner := user.GetUserByParams(c)
if c.Written() {
return
}
repo.CreateUserRepo(ctx, owner, form)
repo.CreateUserRepo(c, owner, form)
}

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

@ -16,7 +16,7 @@ import (
"github.com/gogits/gogs/routers/api/v1/user"
)
func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, loginName string) {
func parseLoginSource(c *context.APIContext, u *models.User, sourceID int64, loginName string) {
if sourceID == 0 {
return
}
@ -24,9 +24,9 @@ func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, l
source, err := models.GetLoginSourceByID(sourceID)
if err != nil {
if models.IsErrLoginSourceNotExist(err) {
ctx.Error(422, "", err)
c.Error(422, "", err)
} else {
ctx.Error(500, "GetLoginSourceByID", err)
c.Error(500, "GetLoginSourceByID", err)
}
return
}
@ -37,7 +37,7 @@ func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, l
}
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-new-user
func CreateUser(ctx *context.APIContext, form api.CreateUserOption) {
func CreateUser(c *context.APIContext, form api.CreateUserOption) {
u := &models.User{
Name: form.Username,
FullName: form.FullName,
@ -47,8 +47,8 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) {
LoginType: models.LOGIN_PLAIN,
}
parseLoginSource(ctx, u, form.SourceID, form.LoginName)
if ctx.Written() {
parseLoginSource(c, u, form.SourceID, form.LoginName)
if c.Written() {
return
}
@ -57,31 +57,31 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) {
models.IsErrEmailAlreadyUsed(err) ||
models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) {
ctx.Error(422, "", err)
c.Error(422, "", err)
} else {
ctx.Error(500, "CreateUser", err)
c.Error(500, "CreateUser", err)
}
return
}
log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name)
log.Trace("Account created by admin (%s): %s", c.User.Name, u.Name)
// Send email notification.
if form.SendNotify && setting.MailService != nil {
mailer.SendRegisterNotifyMail(ctx.Context.Context, models.NewMailerUser(u))
mailer.SendRegisterNotifyMail(c.Context.Context, models.NewMailerUser(u))
}
ctx.JSON(201, u.APIFormat())
c.JSON(201, u.APIFormat())
}
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#edit-an-existing-user
func EditUser(ctx *context.APIContext, form api.EditUserOption) {
u := user.GetUserByParams(ctx)
if ctx.Written() {
func EditUser(c *context.APIContext, form api.EditUserOption) {
u := user.GetUserByParams(c)
if c.Written() {
return
}
parseLoginSource(ctx, u, form.SourceID, form.LoginName)
if ctx.Written() {
parseLoginSource(c, u, form.SourceID, form.LoginName)
if c.Written() {
return
}
@ -89,7 +89,7 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) {
u.Passwd = form.Password
var err error
if u.Salt, err = models.GetUserSalt(); err != nil {
ctx.Error(500, "UpdateUser", err)
c.Error(500, "UpdateUser", err)
return
}
u.EncodePasswd()
@ -118,43 +118,43 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) {
if err := models.UpdateUser(u); err != nil {
if models.IsErrEmailAlreadyUsed(err) {
ctx.Error(422, "", err)
c.Error(422, "", err)
} else {
ctx.Error(500, "UpdateUser", err)
c.Error(500, "UpdateUser", err)
}
return
}
log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name)
log.Trace("Account profile updated by admin (%s): %s", c.User.Name, u.Name)
ctx.JSON(200, u.APIFormat())
c.JSON(200, u.APIFormat())
}
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#delete-a-user
func DeleteUser(ctx *context.APIContext) {
u := user.GetUserByParams(ctx)
if ctx.Written() {
func DeleteUser(c *context.APIContext) {
u := user.GetUserByParams(c)
if c.Written() {
return
}
if err := models.DeleteUser(u); err != nil {
if models.IsErrUserOwnRepos(err) ||
models.IsErrUserHasOrgs(err) {
ctx.Error(422, "", err)
c.Error(422, "", err)
} else {
ctx.Error(500, "DeleteUser", err)
c.Error(500, "DeleteUser", err)
}
return
}
log.Trace("Account deleted by admin(%s): %s", ctx.User.Name, u.Name)
log.Trace("Account deleted by admin(%s): %s", c.User.Name, u.Name)
ctx.Status(204)
c.Status(204)
}
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-public-key-for-user
func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) {
u := user.GetUserByParams(ctx)
if ctx.Written() {
func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) {
u := user.GetUserByParams(c)
if c.Written() {
return
}
user.CreateUserPublicKey(ctx, form, u.ID)
user.CreateUserPublicKey(c, form, u.ID)
}

88
routers/api/v1/api.go

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

20
routers/dev/template.go

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

94
routers/home.go

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

80
routers/org/members.go

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

28
routers/org/org.go

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

122
routers/org/setting.go

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

202
routers/org/teams.go

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

68
routers/repo/branch.go

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

194
routers/repo/commit.go

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

30
routers/repo/download.go

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

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

28
routers/repo/http.go

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

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 {
baseRepo, err := models.GetRepositoryByID(ctx.ParamsInt64(":repoid"))
func parseBaseRepository(c *context.Context) *models.Repository {
baseRepo, err := models.GetRepositoryByID(c.ParamsInt64(":repoid"))
if err != nil {
ctx.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err)
c.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err)
return nil
}
if !baseRepo.CanBeForked() || !baseRepo.HasAccess(ctx.User.ID) {
ctx.NotFound()
if !baseRepo.CanBeForked() || !baseRepo.HasAccess(c.User.ID) {
c.NotFound()
return nil
}
ctx.Data["repo_name"] = baseRepo.Name
ctx.Data["description"] = baseRepo.Description
ctx.Data["IsPrivate"] = baseRepo.IsPrivate
c.Data["repo_name"] = baseRepo.Name
c.Data["description"] = baseRepo.Description
c.Data["IsPrivate"] = baseRepo.IsPrivate
if err = baseRepo.GetOwner(); err != nil {
ctx.Handle(500, "GetOwner", err)
c.Handle(500, "GetOwner", err)
return nil
}
ctx.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name
c.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name
if err := ctx.User.GetOrganizations(true); err != nil {
ctx.Handle(500, "GetOrganizations", err)
if err := c.User.GetOrganizations(true); err != nil {
c.Handle(500, "GetOrganizations", err)
return nil
}
ctx.Data["Orgs"] = ctx.User.Orgs
c.Data["Orgs"] = c.User.Orgs
return baseRepo
}
func Fork(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("new_fork")
func Fork(c *context.Context) {
c.Data["Title"] = c.Tr("new_fork")
parseBaseRepository(ctx)
if ctx.Written() {
parseBaseRepository(c)
if c.Written() {
return
}
ctx.Data["ContextUser"] = ctx.User
ctx.HTML(200, FORK)
c.Data["ContextUser"] = c.User
c.HTML(200, FORK)
}
func ForkPost(ctx *context.Context, f form.CreateRepo) {
ctx.Data["Title"] = ctx.Tr("new_fork")
func ForkPost(c *context.Context, f form.CreateRepo) {
c.Data["Title"] = c.Tr("new_fork")
baseRepo := parseBaseRepository(ctx)
if ctx.Written() {
baseRepo := parseBaseRepository(c)
if c.Written() {
return
}
ctxUser := checkContextUser(ctx, f.UserID)
if ctx.Written() {
ctxUser := checkContextUser(c, f.UserID)
if c.Written() {
return
}
ctx.Data["ContextUser"] = ctxUser
c.Data["ContextUser"] = ctxUser
if ctx.HasError() {
ctx.HTML(200, FORK)
if c.HasError() {
c.HTML(200, FORK)
return
}
repo, has := models.HasForkedRepo(ctxUser.ID, baseRepo.ID)
if has {
ctx.Redirect(repo.Link())
c.Redirect(repo.Link())
return
}
// Check ownership of organization.
if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(ctx.User.ID) {
ctx.Error(403)
if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(c.User.ID) {
c.Error(403)
return
}
// Cannot fork to same owner
if ctxUser.ID == baseRepo.OwnerID {
ctx.RenderWithErr(ctx.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &f)
c.RenderWithErr(c.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &f)
return
}
repo, err := models.ForkRepository(ctx.User, ctxUser, baseRepo, f.RepoName, f.Description)
repo, err := models.ForkRepository(c.User, ctxUser, baseRepo, f.RepoName, f.Description)
if err != nil {
ctx.Data["Err_RepoName"] = true
c.Data["Err_RepoName"] = true
switch {
case models.IsErrRepoAlreadyExist(err):
ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), FORK, &f)
c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), FORK, &f)
case models.IsErrNameReserved(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &f)
c.RenderWithErr(c.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &f)
case models.IsErrNamePatternNotAllowed(err):
ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &f)
c.RenderWithErr(c.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &f)
default:
ctx.Handle(500, "ForkPost", err)
c.Handle(500, "ForkPost", err)
}
return
}
log.Trace("Repository forked from '%s' -> '%s'", baseRepo.FullName(), repo.FullName())
ctx.Redirect(repo.Link())
c.Redirect(repo.Link())
}
func checkPullInfo(ctx *context.Context) *models.Issue {
issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
func checkPullInfo(c *context.Context) *models.Issue {
issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index"))
if err != nil {
ctx.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
return nil
}
ctx.Data["Title"] = issue.Title
ctx.Data["Issue"] = issue
c.Data["Title"] = issue.Title
c.Data["Issue"] = issue
if !issue.IsPull {
ctx.Handle(404, "ViewPullCommits", nil)
c.Handle(404, "ViewPullCommits", nil)
return nil
}
if ctx.IsLogged {
if c.IsLogged {
// Update issue-user.
if err = issue.ReadBy(ctx.User.ID); err != nil {
ctx.Handle(500, "ReadBy", err)
if err = issue.ReadBy(c.User.ID); err != nil {
c.Handle(500, "ReadBy", err)
return nil
}
}
@ -164,31 +164,31 @@ func checkPullInfo(ctx *context.Context) *models.Issue {
return issue
}
func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) {
func PrepareMergedViewPullInfo(c *context.Context, issue *models.Issue) {
pull := issue.PullRequest
ctx.Data["HasMerged"] = true
ctx.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch
ctx.Data["BaseTarget"] = ctx.Repo.Owner.Name + "/" + pull.BaseBranch
c.Data["HasMerged"] = true
c.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch
c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch
var err error
ctx.Data["NumCommits"], err = ctx.Repo.GitRepo.CommitsCountBetween(pull.MergeBase, pull.MergedCommitID)
c.Data["NumCommits"], err = c.Repo.GitRepo.CommitsCountBetween(pull.MergeBase, pull.MergedCommitID)
if err != nil {
ctx.Handle(500, "Repo.GitRepo.CommitsCountBetween", err)
c.Handle(500, "Repo.GitRepo.CommitsCountBetween", err)
return
}
ctx.Data["NumFiles"], err = ctx.Repo.GitRepo.FilesCountBetween(pull.MergeBase, pull.MergedCommitID)
c.Data["NumFiles"], err = c.Repo.GitRepo.FilesCountBetween(pull.MergeBase, pull.MergedCommitID)
if err != nil {
ctx.Handle(500, "Repo.GitRepo.FilesCountBetween", err)
c.Handle(500, "Repo.GitRepo.FilesCountBetween", err)
return
}
}
func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullRequestInfo {
repo := ctx.Repo.Repository
func PrepareViewPullInfo(c *context.Context, issue *models.Issue) *git.PullRequestInfo {
repo := c.Repo.Repository
pull := issue.PullRequest
ctx.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch
ctx.Data["BaseTarget"] = ctx.Repo.Owner.Name + "/" + pull.BaseBranch
c.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch
c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch
var (
headGitRepo *git.Repository
@ -198,16 +198,16 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullReq
if pull.HeadRepo != nil {
headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath())
if err != nil {
ctx.Handle(500, "OpenRepository", err)
c.Handle(500, "OpenRepository", err)
return nil
}
}
if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) {
ctx.Data["IsPullReuqestBroken"] = true
ctx.Data["HeadTarget"] = "deleted"
ctx.Data["NumCommits"] = 0
ctx.Data["NumFiles"] = 0
c.Data["IsPullReuqestBroken"] = true
c.Data["HeadTarget"] = "deleted"
c.Data["NumCommits"] = 0
c.Data["NumFiles"] = 0
return nil
}
@ -215,82 +215,82 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullReq
pull.BaseBranch, pull.HeadBranch)
if err != nil {
if strings.Contains(err.Error(), "fatal: Not a valid object name") {
ctx.Data["IsPullReuqestBroken"] = true
ctx.Data["BaseTarget"] = "deleted"
ctx.Data["NumCommits"] = 0
ctx.Data["NumFiles"] = 0
c.Data["IsPullReuqestBroken"] = true
c.Data["BaseTarget"] = "deleted"
c.Data["NumCommits"] = 0
c.Data["NumFiles"] = 0
return nil
}
ctx.Handle(500, "GetPullRequestInfo", err)
c.Handle(500, "GetPullRequestInfo", err)
return nil
}
ctx.Data["NumCommits"] = prInfo.Commits.Len()
ctx.Data["NumFiles"] = prInfo.NumFiles
c.Data["NumCommits"] = prInfo.Commits.Len()
c.Data["NumFiles"] = prInfo.NumFiles
return prInfo
}
func ViewPullCommits(ctx *context.Context) {
ctx.Data["PageIsPullList"] = true
ctx.Data["PageIsPullCommits"] = true
func ViewPullCommits(c *context.Context) {
c.Data["PageIsPullList"] = true
c.Data["PageIsPullCommits"] = true
issue := checkPullInfo(ctx)
if ctx.Written() {
issue := checkPullInfo(c)
if c.Written() {
return
}
pull := issue.PullRequest
if pull.HeadRepo != nil {
ctx.Data["Username"] = pull.HeadUserName
ctx.Data["Reponame"] = pull.HeadRepo.Name
c.Data["Username"] = pull.HeadUserName
c.Data["Reponame"] = pull.HeadRepo.Name
}
var commits *list.List
if pull.HasMerged {
PrepareMergedViewPullInfo(ctx, issue)
if ctx.Written() {
PrepareMergedViewPullInfo(c, issue)
if c.Written() {
return
}
startCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergeBase)
startCommit, err := c.Repo.GitRepo.GetCommit(pull.MergeBase)
if err != nil {
ctx.Handle(500, "Repo.GitRepo.GetCommit", err)
c.Handle(500, "Repo.GitRepo.GetCommit", err)
return
}
endCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergedCommitID)
endCommit, err := c.Repo.GitRepo.GetCommit(pull.MergedCommitID)
if err != nil {
ctx.Handle(500, "Repo.GitRepo.GetCommit", err)
c.Handle(500, "Repo.GitRepo.GetCommit", err)
return
}
commits, err = ctx.Repo.GitRepo.CommitsBetween(endCommit, startCommit)
commits, err = c.Repo.GitRepo.CommitsBetween(endCommit, startCommit)
if err != nil {
ctx.Handle(500, "Repo.GitRepo.CommitsBetween", err)
c.Handle(500, "Repo.GitRepo.CommitsBetween", err)
return
}
} else {
prInfo := PrepareViewPullInfo(ctx, issue)
if ctx.Written() {
prInfo := PrepareViewPullInfo(c, issue)
if c.Written() {
return
} else if prInfo == nil {
ctx.Handle(404, "ViewPullCommits", nil)
c.Handle(404, "ViewPullCommits", nil)
return
}
commits = prInfo.Commits
}
commits = models.ValidateCommitsWithEmails(commits)
ctx.Data["Commits"] = commits
ctx.Data["CommitsCount"] = commits.Len()
c.Data["Commits"] = commits
c.Data["CommitsCount"] = commits.Len()
ctx.HTML(200, PULL_COMMITS)
c.HTML(200, PULL_COMMITS)
}
func ViewPullFiles(ctx *context.Context) {
ctx.Data["PageIsPullList"] = true
ctx.Data["PageIsPullFiles"] = true
func ViewPullFiles(c *context.Context) {
c.Data["PageIsPullList"] = true
c.Data["PageIsPullFiles"] = true
issue := checkPullInfo(ctx)
if ctx.Written() {
issue := checkPullInfo(c)
if c.Written() {
return
}
pull := issue.PullRequest
@ -303,21 +303,21 @@ func ViewPullFiles(ctx *context.Context) {
)
if pull.HasMerged {
PrepareMergedViewPullInfo(ctx, issue)
if ctx.Written() {
PrepareMergedViewPullInfo(c, issue)
if c.Written() {
return
}
diffRepoPath = ctx.Repo.GitRepo.Path
diffRepoPath = c.Repo.GitRepo.Path
startCommitID = pull.MergeBase
endCommitID = pull.MergedCommitID
gitRepo = ctx.Repo.GitRepo
gitRepo = c.Repo.GitRepo
} else {
prInfo := PrepareViewPullInfo(ctx, issue)
if ctx.Written() {
prInfo := PrepareViewPullInfo(c, issue)
if c.Written() {
return
} else if prInfo == nil {
ctx.Handle(404, "ViewPullFiles", nil)
c.Handle(404, "ViewPullFiles", nil)
return
}
@ -325,13 +325,13 @@ func ViewPullFiles(ctx *context.Context) {
headGitRepo, err := git.OpenRepository(headRepoPath)
if err != nil {
ctx.Handle(500, "OpenRepository", err)
c.Handle(500, "OpenRepository", err)
return
}
headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
if err != nil {
ctx.Handle(500, "GetBranchCommitID", err)
c.Handle(500, "GetBranchCommitID", err)
return
}
@ -345,89 +345,89 @@ func ViewPullFiles(ctx *context.Context) {
startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
if err != nil {
ctx.Handle(500, "GetDiffRange", err)
c.Handle(500, "GetDiffRange", err)
return
}
ctx.Data["Diff"] = diff
ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
c.Data["Diff"] = diff
c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
commit, err := gitRepo.GetCommit(endCommitID)
if err != nil {
ctx.Handle(500, "GetCommit", err)
c.Handle(500, "GetCommit", err)
return
}
setEditorconfigIfExists(ctx)
if ctx.Written() {
setEditorconfigIfExists(c)
if c.Written() {
return
}
ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split"
ctx.Data["IsImageFile"] = commit.IsImageFile
c.Data["IsSplitStyle"] = c.Query("style") == "split"
c.Data["IsImageFile"] = commit.IsImageFile
// It is possible head repo has been deleted for merged pull requests
if pull.HeadRepo != nil {
ctx.Data["Username"] = pull.HeadUserName
ctx.Data["Reponame"] = pull.HeadRepo.Name
c.Data["Username"] = pull.HeadUserName
c.Data["Reponame"] = pull.HeadRepo.Name
headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name)
ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID)
ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID)
ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID)
c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID)
c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID)
c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID)
}
ctx.Data["RequireHighlightJS"] = true
ctx.HTML(200, PULL_FILES)
c.Data["RequireHighlightJS"] = true
c.HTML(200, PULL_FILES)
}
func MergePullRequest(ctx *context.Context) {
issue := checkPullInfo(ctx)
if ctx.Written() {
func MergePullRequest(c *context.Context) {
issue := checkPullInfo(c)
if c.Written() {
return
}
if issue.IsClosed {
ctx.Handle(404, "MergePullRequest", nil)
c.Handle(404, "MergePullRequest", nil)
return
}
pr, err := models.GetPullRequestByIssueID(issue.ID)
if err != nil {
ctx.NotFoundOrServerError("GetPullRequestByIssueID", models.IsErrPullRequestNotExist, err)
c.NotFoundOrServerError("GetPullRequestByIssueID", models.IsErrPullRequestNotExist, err)
return
}
if !pr.CanAutoMerge() || pr.HasMerged {
ctx.Handle(404, "MergePullRequest", nil)
c.Handle(404, "MergePullRequest", nil)
return
}
pr.Issue = issue
pr.Issue.Repo = ctx.Repo.Repository
if err = pr.Merge(ctx.User, ctx.Repo.GitRepo); err != nil {
ctx.Handle(500, "Merge", err)
pr.Issue.Repo = c.Repo.Repository
if err = pr.Merge(c.User, c.Repo.GitRepo); err != nil {
c.Handle(500, "Merge", err)
return
}
log.Trace("Pull request merged: %d", pr.ID)
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
}
func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
baseRepo := ctx.Repo.Repository
func ParseCompareInfo(c *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
baseRepo := c.Repo.Repository
// Get compared branches information
// format: <base branch>...[<head repo>:]<head branch>
// base<-head: master...head:feature
// same repo: master...feature
infos := strings.Split(ctx.Params("*"), "...")
infos := strings.Split(c.Params("*"), "...")
if len(infos) != 2 {
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, "", ""
}
baseBranch := infos[0]
ctx.Data["BaseBranch"] = baseBranch
c.Data["BaseBranch"] = baseBranch
var (
headUser *models.User
@ -440,29 +440,29 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *
headInfos := strings.Split(infos[1], ":")
if len(headInfos) == 1 {
isSameRepo = true
headUser = ctx.Repo.Owner
headUser = c.Repo.Owner
headBranch = headInfos[0]
} else if len(headInfos) == 2 {
headUser, err = models.GetUserByName(headInfos[0])
if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return nil, nil, nil, nil, "", ""
}
headBranch = headInfos[1]
isSameRepo = headUser.ID == baseRepo.OwnerID
} else {
ctx.Handle(404, "CompareAndPullRequest", nil)
c.Handle(404, "CompareAndPullRequest", nil)
return nil, nil, nil, nil, "", ""
}
ctx.Data["HeadUser"] = headUser
ctx.Data["HeadBranch"] = headBranch
ctx.Repo.PullRequest.SameRepo = isSameRepo
c.Data["HeadUser"] = headUser
c.Data["HeadBranch"] = headBranch
c.Repo.PullRequest.SameRepo = isSameRepo
// Check if base branch is valid.
if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) {
ctx.Handle(404, "IsBranchExist", nil)
if !c.Repo.GitRepo.IsBranchExist(baseBranch) {
c.Handle(404, "IsBranchExist", 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)
if !has {
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, "", ""
}
headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
if err != nil {
ctx.Handle(500, "OpenRepository", err)
c.Handle(500, "OpenRepository", err)
return nil, nil, nil, nil, "", ""
}
} else {
headRepo = ctx.Repo.Repository
headGitRepo = ctx.Repo.GitRepo
headRepo = c.Repo.Repository
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)
ctx.Handle(404, "ParseCompareInfo", nil)
c.Handle(404, "ParseCompareInfo", nil)
return nil, nil, nil, nil, "", ""
}
// Check if head branch is valid.
if !headGitRepo.IsBranchExist(headBranch) {
ctx.Handle(404, "IsBranchExist", nil)
c.Handle(404, "IsBranchExist", nil)
return nil, nil, nil, nil, "", ""
}
headBranches, err := headGitRepo.GetBranches()
if err != nil {
ctx.Handle(500, "GetBranches", err)
c.Handle(500, "GetBranches", err)
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)
if err != nil {
ctx.Handle(500, "GetPullRequestInfo", err)
c.Handle(500, "GetPullRequestInfo", err)
return nil, nil, nil, nil, "", ""
}
ctx.Data["BeforeCommitID"] = prInfo.MergeBase
c.Data["BeforeCommitID"] = prInfo.MergeBase
return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
}
@ -579,73 +579,73 @@ func PrepareCompareDiff(
return false
}
func CompareAndPullRequest(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
ctx.Data["PageIsComparePull"] = true
ctx.Data["IsDiffCompare"] = true
ctx.Data["RequireHighlightJS"] = true
setTemplateIfExists(ctx, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates)
renderAttachmentSettings(ctx)
func CompareAndPullRequest(c *context.Context) {
c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
c.Data["PageIsComparePull"] = true
c.Data["IsDiffCompare"] = true
c.Data["RequireHighlightJS"] = true
setTemplateIfExists(c, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates)
renderAttachmentSettings(c)
headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
if ctx.Written() {
headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
if c.Written() {
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 !models.IsErrPullRequestNotExist(err) {
ctx.Handle(500, "GetUnmergedPullRequest", err)
c.Handle(500, "GetUnmergedPullRequest", err)
return
}
} else {
ctx.Data["HasPullRequest"] = true
ctx.Data["PullRequest"] = pr
ctx.HTML(200, COMPARE_PULL)
c.Data["HasPullRequest"] = true
c.Data["PullRequest"] = pr
c.HTML(200, COMPARE_PULL)
return
}
nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
if ctx.Written() {
nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
if c.Written() {
return
}
if !nothingToCompare {
// Setup information for new form.
RetrieveRepoMetas(ctx, ctx.Repo.Repository)
if ctx.Written() {
RetrieveRepoMetas(c, c.Repo.Repository)
if c.Written() {
return
}
}
setEditorconfigIfExists(ctx)
if ctx.Written() {
setEditorconfigIfExists(c)
if c.Written() {
return
}
ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split"
ctx.HTML(200, COMPARE_PULL)
c.Data["IsSplitStyle"] = c.Query("style") == "split"
c.HTML(200, COMPARE_PULL)
}
func CompareAndPullRequestPost(ctx *context.Context, f form.NewIssue) {
ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
ctx.Data["PageIsComparePull"] = true
ctx.Data["IsDiffCompare"] = true
ctx.Data["RequireHighlightJS"] = true
renderAttachmentSettings(ctx)
func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
c.Data["PageIsComparePull"] = true
c.Data["IsDiffCompare"] = true
c.Data["RequireHighlightJS"] = true
renderAttachmentSettings(c)
var (
repo = ctx.Repo.Repository
repo = c.Repo.Repository
attachments []string
)
headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
if ctx.Written() {
headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
if c.Written() {
return
}
labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, f)
if ctx.Written() {
labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f)
if c.Written() {
return
}
@ -653,23 +653,23 @@ func CompareAndPullRequestPost(ctx *context.Context, f form.NewIssue) {
attachments = f.Files
}
if ctx.HasError() {
form.Assign(f, ctx.Data)
if c.HasError() {
form.Assign(f, c.Data)
// This stage is already stop creating new pull request, so it does not matter if it has
// something to compare or not.
PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
if ctx.Written() {
PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
if c.Written() {
return
}
ctx.HTML(200, COMPARE_PULL)
c.HTML(200, COMPARE_PULL)
return
}
patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
if err != nil {
ctx.Handle(500, "GetPatch", err)
c.Handle(500, "GetPatch", err)
return
}
@ -677,8 +677,8 @@ func CompareAndPullRequestPost(ctx *context.Context, f form.NewIssue) {
RepoID: repo.ID,
Index: repo.NextIssueIndex(),
Title: f.Title,
PosterID: ctx.User.ID,
Poster: ctx.User,
PosterID: c.User.ID,
Poster: c.User,
MilestoneID: milestoneID,
AssigneeID: assigneeID,
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
// instead of 500.
if err := models.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil {
ctx.Handle(500, "NewPullRequest", err)
c.Handle(500, "NewPullRequest", err)
return
} else if err := pullRequest.PushToBaseRepo(); err != nil {
ctx.Handle(500, "PushToBaseRepo", err)
c.Handle(500, "PushToBaseRepo", err)
return
}
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) {
owner, err := models.GetUserByName(ctx.Params(":username"))
func parseOwnerAndRepo(c *context.Context) (*models.User, *models.Repository) {
owner, err := models.GetUserByName(c.Params(":username"))
if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return nil, nil
}
repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
repo, err := models.GetRepositoryByName(owner.ID, c.Params(":reponame"))
if err != nil {
ctx.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
return nil, nil
}
return owner, repo
}
func TriggerTask(ctx *context.Context) {
pusherID := ctx.QueryInt64("pusher")
branch := ctx.Query("branch")
secret := ctx.Query("secret")
func TriggerTask(c *context.Context) {
pusherID := c.QueryInt64("pusher")
branch := c.Query("branch")
secret := c.Query("secret")
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")
return
}
owner, repo := parseOwnerAndRepo(ctx)
if ctx.Written() {
owner, repo := parseOwnerAndRepo(c)
if c.Written() {
return
}
if secret != tool.MD5(owner.Salt) {
ctx.Error(404)
c.Error(404)
log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
return
}
pusher, err := models.GetUserByID(pusherID)
if err != nil {
ctx.NotFoundOrServerError("GetUserByID", errors.IsUserNotExist, err)
c.NotFoundOrServerError("GetUserByID", errors.IsUserNotExist, err)
return
}
@ -754,5 +754,5 @@ func TriggerTask(ctx *context.Context) {
go models.HookQueue.Add(repo.ID)
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
}
func Releases(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.release.releases")
ctx.Data["PageIsViewFiles"] = true
ctx.Data["PageIsReleaseList"] = true
func Releases(c *context.Context) {
c.Data["Title"] = c.Tr("repo.release.releases")
c.Data["PageIsViewFiles"] = 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 {
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
}
releases, err := models.GetPublishedReleasesByRepoID(ctx.Repo.Repository.ID, tagsResult.Tags...)
releases, err := models.GetPublishedReleasesByRepoID(c.Repo.Repository.ID, tagsResult.Tags...)
if err != nil {
ctx.Handle(500, "GetPublishedReleasesByRepoID", err)
c.Handle(500, "GetPublishedReleasesByRepoID", err)
return
}
@ -73,25 +73,25 @@ func Releases(ctx *context.Context) {
releases[j] = nil // Mark as used.
if err = r.LoadAttributes(); err != nil {
ctx.Handle(500, "LoadAttributes", err)
c.Handle(500, "LoadAttributes", err)
return
}
if err := calReleaseNumCommitsBehind(ctx.Repo, r, countCache); err != nil {
ctx.Handle(500, "calReleaseNumCommitsBehind", err)
if err := calReleaseNumCommitsBehind(c.Repo, r, countCache); err != nil {
c.Handle(500, "calReleaseNumCommitsBehind", err)
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
break
}
// No published release matches this tag
if results[i] == nil {
commit, err := ctx.Repo.GitRepo.GetTagCommit(rawTag)
commit, err := c.Repo.GitRepo.GetTagCommit(rawTag)
if err != nil {
ctx.Handle(500, "GetTagCommit", err)
c.Handle(500, "GetTagCommit", err)
return
}
@ -103,10 +103,10 @@ func Releases(ctx *context.Context) {
results[i].NumCommits, err = commit.CommitsCount()
if err != nil {
ctx.Handle(500, "CommitsCount", err)
c.Handle(500, "CommitsCount", err)
return
}
results[i].NumCommitsBehind = ctx.Repo.CommitsCount - results[i].NumCommits
results[i].NumCommitsBehind = c.Repo.CommitsCount - results[i].NumCommits
}
}
models.SortReleases(results)
@ -114,24 +114,24 @@ func Releases(ctx *context.Context) {
// Only show drafts if user is viewing the latest page
var drafts []*models.Release
if tagsResult.HasLatest {
drafts, err = models.GetDraftReleasesByRepoID(ctx.Repo.Repository.ID)
drafts, err = models.GetDraftReleasesByRepoID(c.Repo.Repository.ID)
if err != nil {
ctx.Handle(500, "GetDraftReleasesByRepoID", err)
c.Handle(500, "GetDraftReleasesByRepoID", err)
return
}
for _, r := range drafts {
if err = r.LoadAttributes(); err != nil {
ctx.Handle(500, "LoadAttributes", err)
c.Handle(500, "LoadAttributes", err)
return
}
if err := calReleaseNumCommitsBehind(ctx.Repo, r, countCache); err != nil {
ctx.Handle(500, "calReleaseNumCommitsBehind", err)
if err := calReleaseNumCommitsBehind(c.Repo, r, countCache); err != nil {
c.Handle(500, "calReleaseNumCommitsBehind", err)
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 {
@ -139,50 +139,50 @@ func Releases(ctx *context.Context) {
}
}
ctx.Data["Releases"] = results
ctx.Data["HasPrevious"] = !tagsResult.HasLatest
ctx.Data["ReachEnd"] = tagsResult.ReachEnd
ctx.Data["PreviousAfter"] = tagsResult.PreviousAfter
c.Data["Releases"] = results
c.Data["HasPrevious"] = !tagsResult.HasLatest
c.Data["ReachEnd"] = tagsResult.ReachEnd
c.Data["PreviousAfter"] = tagsResult.PreviousAfter
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) {
ctx.Data["RequireDropzone"] = true
ctx.Data["IsAttachmentEnabled"] = setting.Release.Attachment.Enabled
ctx.Data["AttachmentAllowedTypes"] = strings.Join(setting.Release.Attachment.AllowedTypes, ",")
ctx.Data["AttachmentMaxSize"] = setting.Release.Attachment.MaxSize
ctx.Data["AttachmentMaxFiles"] = setting.Release.Attachment.MaxFiles
func renderReleaseAttachmentSettings(c *context.Context) {
c.Data["RequireDropzone"] = true
c.Data["IsAttachmentEnabled"] = setting.Release.Attachment.Enabled
c.Data["AttachmentAllowedTypes"] = strings.Join(setting.Release.Attachment.AllowedTypes, ",")
c.Data["AttachmentMaxSize"] = setting.Release.Attachment.MaxSize
c.Data["AttachmentMaxFiles"] = setting.Release.Attachment.MaxFiles
}
func NewRelease(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.release.new_release")
ctx.Data["PageIsReleaseList"] = true
ctx.Data["tag_target"] = ctx.Repo.Repository.DefaultBranch
renderReleaseAttachmentSettings(ctx)
ctx.HTML(200, RELEASE_NEW)
func NewRelease(c *context.Context) {
c.Data["Title"] = c.Tr("repo.release.new_release")
c.Data["PageIsReleaseList"] = true
c.Data["tag_target"] = c.Repo.Repository.DefaultBranch
renderReleaseAttachmentSettings(c)
c.HTML(200, RELEASE_NEW)
}
func NewReleasePost(ctx *context.Context, f form.NewRelease) {
ctx.Data["Title"] = ctx.Tr("repo.release.new_release")
ctx.Data["PageIsReleaseList"] = true
renderReleaseAttachmentSettings(ctx)
func NewReleasePost(c *context.Context, f form.NewRelease) {
c.Data["Title"] = c.Tr("repo.release.new_release")
c.Data["PageIsReleaseList"] = true
renderReleaseAttachmentSettings(c)
if ctx.HasError() {
ctx.HTML(200, RELEASE_NEW)
if c.HasError() {
c.HTML(200, RELEASE_NEW)
return
}
if !ctx.Repo.GitRepo.IsBranchExist(f.Target) {
ctx.RenderWithErr(ctx.Tr("form.target_branch_not_exist"), RELEASE_NEW, &f)
if !c.Repo.GitRepo.IsBranchExist(f.Target) {
c.RenderWithErr(c.Tr("form.target_branch_not_exist"), RELEASE_NEW, &f)
return
}
// Use current time if tag not yet exist, otherwise get time from Git
var tagCreatedUnix int64
tag, err := ctx.Repo.GitRepo.GetTag(f.TagName)
tag, err := c.Repo.GitRepo.GetTag(f.TagName)
if err == nil {
commit, err := tag.Commit()
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 {
ctx.Handle(500, "GetBranchCommit", err)
c.Handle(500, "GetBranchCommit", err)
return
}
commitsCount, err := commit.CommitsCount()
if err != nil {
ctx.Handle(500, "CommitsCount", err)
c.Handle(500, "CommitsCount", err)
return
}
@ -208,8 +208,8 @@ func NewReleasePost(ctx *context.Context, f form.NewRelease) {
}
rel := &models.Release{
RepoID: ctx.Repo.Repository.ID,
PublisherID: ctx.User.ID,
RepoID: c.Repo.Repository.ID,
PublisherID: c.User.ID,
Title: f.Title,
TagName: f.TagName,
Target: f.Target,
@ -220,77 +220,77 @@ func NewReleasePost(ctx *context.Context, f form.NewRelease) {
IsPrerelease: f.Prerelease,
CreatedUnix: tagCreatedUnix,
}
if err = models.NewRelease(ctx.Repo.GitRepo, rel, attachments); err != nil {
ctx.Data["Err_TagName"] = true
if err = models.NewRelease(c.Repo.GitRepo, rel, attachments); err != nil {
c.Data["Err_TagName"] = true
switch {
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):
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:
ctx.Handle(500, "NewRelease", err)
c.Handle(500, "NewRelease", err)
}
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) {
ctx.Data["Title"] = ctx.Tr("repo.release.edit_release")
ctx.Data["PageIsReleaseList"] = true
ctx.Data["PageIsEditRelease"] = true
renderReleaseAttachmentSettings(ctx)
func EditRelease(c *context.Context) {
c.Data["Title"] = c.Tr("repo.release.edit_release")
c.Data["PageIsReleaseList"] = true
c.Data["PageIsEditRelease"] = true
renderReleaseAttachmentSettings(c)
tagName := ctx.Params("*")
rel, err := models.GetRelease(ctx.Repo.Repository.ID, tagName)
tagName := c.Params("*")
rel, err := models.GetRelease(c.Repo.Repository.ID, tagName)
if err != nil {
if models.IsErrReleaseNotExist(err) {
ctx.Handle(404, "GetRelease", err)
c.Handle(404, "GetRelease", err)
} else {
ctx.Handle(500, "GetRelease", err)
c.Handle(500, "GetRelease", err)
}
return
}
ctx.Data["ID"] = rel.ID
ctx.Data["tag_name"] = rel.TagName
ctx.Data["tag_target"] = rel.Target
ctx.Data["title"] = rel.Title
ctx.Data["content"] = rel.Note
ctx.Data["attachments"] = rel.Attachments
ctx.Data["prerelease"] = rel.IsPrerelease
ctx.Data["IsDraft"] = rel.IsDraft
c.Data["ID"] = rel.ID
c.Data["tag_name"] = rel.TagName
c.Data["tag_target"] = rel.Target
c.Data["title"] = rel.Title
c.Data["content"] = rel.Note
c.Data["attachments"] = rel.Attachments
c.Data["prerelease"] = rel.IsPrerelease
c.Data["IsDraft"] = rel.IsDraft
ctx.HTML(200, RELEASE_NEW)
c.HTML(200, RELEASE_NEW)
}
func EditReleasePost(ctx *context.Context, f form.EditRelease) {
ctx.Data["Title"] = ctx.Tr("repo.release.edit_release")
ctx.Data["PageIsReleaseList"] = true
ctx.Data["PageIsEditRelease"] = true
renderReleaseAttachmentSettings(ctx)
func EditReleasePost(c *context.Context, f form.EditRelease) {
c.Data["Title"] = c.Tr("repo.release.edit_release")
c.Data["PageIsReleaseList"] = true
c.Data["PageIsEditRelease"] = true
renderReleaseAttachmentSettings(c)
tagName := ctx.Params("*")
rel, err := models.GetRelease(ctx.Repo.Repository.ID, tagName)
tagName := c.Params("*")
rel, err := models.GetRelease(c.Repo.Repository.ID, tagName)
if err != nil {
if models.IsErrReleaseNotExist(err) {
ctx.Handle(404, "GetRelease", err)
c.Handle(404, "GetRelease", err)
} else {
ctx.Handle(500, "GetRelease", err)
c.Handle(500, "GetRelease", err)
}
return
}
ctx.Data["tag_name"] = rel.TagName
ctx.Data["tag_target"] = rel.Target
ctx.Data["title"] = rel.Title
ctx.Data["content"] = rel.Note
ctx.Data["attachments"] = rel.Attachments
ctx.Data["prerelease"] = rel.IsPrerelease
ctx.Data["IsDraft"] = rel.IsDraft
c.Data["tag_name"] = rel.TagName
c.Data["tag_target"] = rel.Target
c.Data["title"] = rel.Title
c.Data["content"] = rel.Note
c.Data["attachments"] = rel.Attachments
c.Data["prerelease"] = rel.IsPrerelease
c.Data["IsDraft"] = rel.IsDraft
if ctx.HasError() {
ctx.HTML(200, RELEASE_NEW)
if c.HasError() {
c.HTML(200, RELEASE_NEW)
return
}
@ -304,29 +304,29 @@ func EditReleasePost(ctx *context.Context, f form.EditRelease) {
rel.Note = f.Content
rel.IsDraft = len(f.Draft) > 0
rel.IsPrerelease = f.Prerelease
if err = models.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, isPublish, attachments); err != nil {
ctx.Handle(500, "UpdateRelease", err)
if err = models.UpdateRelease(c.User, c.Repo.GitRepo, rel, isPublish, attachments); err != nil {
c.Handle(500, "UpdateRelease", err)
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 {
ctx.NotFound()
c.NotFound()
return
}
uploadAttachment(ctx, setting.Release.Attachment.AllowedTypes)
uploadAttachment(c, setting.Release.Attachment.AllowedTypes)
}
func DeleteRelease(ctx *context.Context) {
if err := models.DeleteReleaseOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteReleaseByID: " + err.Error())
func DeleteRelease(c *context.Context) {
if err := models.DeleteReleaseOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
c.Flash.Error("DeleteReleaseByID: " + err.Error())
} 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{}{
"redirect": ctx.Repo.RepoLink + "/releases",
c.JSON(200, map[string]interface{}{
"redirect": c.Repo.RepoLink + "/releases",
})
}

212
routers/repo/repo.go

@ -28,100 +28,100 @@ const (
MIGRATE = "repo/migrate"
)
func MustBeNotBare(ctx *context.Context) {
if ctx.Repo.Repository.IsBare {
ctx.Handle(404, "MustBeNotBare", nil)
func MustBeNotBare(c *context.Context) {
if c.Repo.Repository.IsBare {
c.Handle(404, "MustBeNotBare", nil)
}
}
func checkContextUser(ctx *context.Context, uid int64) *models.User {
orgs, err := models.GetOwnedOrgsByUserIDDesc(ctx.User.ID, "updated_unix")
func checkContextUser(c *context.Context, uid int64) *models.User {
orgs, err := models.GetOwnedOrgsByUserIDDesc(c.User.ID, "updated_unix")
if err != nil {
ctx.Handle(500, "GetOwnedOrgsByUserIDDesc", err)
c.Handle(500, "GetOwnedOrgsByUserIDDesc", err)
return nil
}
ctx.Data["Orgs"] = orgs
c.Data["Orgs"] = orgs
// Not equal means current user is an organization.
if uid == ctx.User.ID || uid == 0 {
return ctx.User
if uid == c.User.ID || uid == 0 {
return c.User
}
org, err := models.GetUserByID(uid)
if errors.IsUserNotExist(err) {
return ctx.User
return c.User
}
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
}
// Check ownership of organization.
if !org.IsOrganization() || !(ctx.User.IsAdmin || org.IsOwnedBy(ctx.User.ID)) {
ctx.Error(403)
if !org.IsOrganization() || !(c.User.IsAdmin || org.IsOwnedBy(c.User.ID)) {
c.Error(403)
return nil
}
return org
}
func Create(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("new_repo")
func Create(c *context.Context) {
c.Data["Title"] = c.Tr("new_repo")
// Give default value for template to render.
ctx.Data["Gitignores"] = models.Gitignores
ctx.Data["Licenses"] = models.Licenses
ctx.Data["Readmes"] = models.Readmes
ctx.Data["readme"] = "Default"
ctx.Data["private"] = ctx.User.LastRepoVisibility
ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
if ctx.Written() {
c.Data["Gitignores"] = models.Gitignores
c.Data["Licenses"] = models.Licenses
c.Data["Readmes"] = models.Readmes
c.Data["readme"] = "Default"
c.Data["private"] = c.User.LastRepoVisibility
c.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
ctxUser := checkContextUser(c, c.QueryInt64("org"))
if c.Written() {
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 {
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):
ctx.Data["Err_RepoName"] = true
ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form)
c.Data["Err_RepoName"] = true
c.RenderWithErr(c.Tr("form.repo_name_been_taken"), tpl, form)
case models.IsErrNameReserved(err):
ctx.Data["Err_RepoName"] = true
ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
c.Data["Err_RepoName"] = true
c.RenderWithErr(c.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
case models.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_RepoName"] = true
ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
c.Data["Err_RepoName"] = true
c.RenderWithErr(c.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
default:
ctx.Handle(500, name, err)
c.Handle(500, name, err)
}
}
func CreatePost(ctx *context.Context, f form.CreateRepo) {
ctx.Data["Title"] = ctx.Tr("new_repo")
func CreatePost(c *context.Context, f form.CreateRepo) {
c.Data["Title"] = c.Tr("new_repo")
ctx.Data["Gitignores"] = models.Gitignores
ctx.Data["Licenses"] = models.Licenses
ctx.Data["Readmes"] = models.Readmes
c.Data["Gitignores"] = models.Gitignores
c.Data["Licenses"] = models.Licenses
c.Data["Readmes"] = models.Readmes
ctxUser := checkContextUser(ctx, f.UserID)
if ctx.Written() {
ctxUser := checkContextUser(c, f.UserID)
if c.Written() {
return
}
ctx.Data["ContextUser"] = ctxUser
c.Data["ContextUser"] = ctxUser
if ctx.HasError() {
ctx.HTML(200, CREATE)
if c.HasError() {
c.HTML(200, CREATE)
return
}
repo, err := models.CreateRepository(ctx.User, ctxUser, models.CreateRepoOptions{
repo, err := models.CreateRepository(c.User, ctxUser, models.CreateRepoOptions{
Name: f.RepoName,
Description: f.Description,
Gitignores: f.Gitignores,
@ -132,7 +132,7 @@ func CreatePost(ctx *context.Context, f form.CreateRepo) {
})
if err == nil {
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
}
@ -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) {
ctx.Data["Title"] = ctx.Tr("new_migrate")
ctx.Data["private"] = ctx.User.LastRepoVisibility
ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
ctx.Data["mirror"] = ctx.Query("mirror") == "1"
func Migrate(c *context.Context) {
c.Data["Title"] = c.Tr("new_migrate")
c.Data["private"] = c.User.LastRepoVisibility
c.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
c.Data["mirror"] = c.Query("mirror") == "1"
ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
if ctx.Written() {
ctxUser := checkContextUser(c, c.QueryInt64("org"))
if c.Written() {
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) {
ctx.Data["Title"] = ctx.Tr("new_migrate")
func MigratePost(c *context.Context, f form.MigrateRepo) {
c.Data["Title"] = c.Tr("new_migrate")
ctxUser := checkContextUser(ctx, f.Uid)
if ctx.Written() {
ctxUser := checkContextUser(c, f.Uid)
if c.Written() {
return
}
ctx.Data["ContextUser"] = ctxUser
c.Data["ContextUser"] = ctxUser
if ctx.HasError() {
ctx.HTML(200, MIGRATE)
if c.HasError() {
c.HTML(200, MIGRATE)
return
}
remoteAddr, err := f.ParseRemoteAddr(ctx.User)
remoteAddr, err := f.ParseRemoteAddr(c.User)
if err != nil {
if models.IsErrInvalidCloneAddr(err) {
ctx.Data["Err_CloneAddr"] = true
c.Data["Err_CloneAddr"] = true
addrErr := err.(models.ErrInvalidCloneAddr)
switch {
case addrErr.IsURLError:
ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &f)
c.RenderWithErr(c.Tr("form.url_error"), MIGRATE, &f)
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:
ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f)
c.RenderWithErr(c.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f)
default:
ctx.Handle(500, "Unknown error", err)
c.Handle(500, "Unknown error", err)
}
} else {
ctx.Handle(500, "ParseRemoteAddr", err)
c.Handle(500, "ParseRemoteAddr", err)
}
return
}
repo, err := models.MigrateRepository(ctx.User, ctxUser, models.MigrateRepoOptions{
repo, err := models.MigrateRepository(c.User, ctxUser, models.MigrateRepoOptions{
Name: f.RepoName,
Description: f.Description,
IsPrivate: f.Private || setting.Repository.ForcePrivate,
@ -204,7 +204,7 @@ func MigratePost(ctx *context.Context, f form.MigrateRepo) {
})
if err == nil {
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
}
@ -216,55 +216,55 @@ func MigratePost(ctx *context.Context, f form.MigrateRepo) {
if strings.Contains(err.Error(), "Authentication failed") ||
strings.Contains(err.Error(), "could not read Username") {
ctx.Data["Err_Auth"] = true
ctx.RenderWithErr(ctx.Tr("form.auth_failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
c.Data["Err_Auth"] = true
c.RenderWithErr(c.Tr("form.auth_failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
return
} else if strings.Contains(err.Error(), "fatal:") {
ctx.Data["Err_CloneAddr"] = true
ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
c.Data["Err_CloneAddr"] = true
c.RenderWithErr(c.Tr("repo.migrate.failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
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
switch ctx.Params(":action") {
switch c.Params(":action") {
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":
err = models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, false)
err = models.WatchRepo(c.User.ID, c.Repo.Repository.ID, false)
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":
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
if !ctx.Repo.IsOwner() {
ctx.Error(404)
if !c.Repo.IsOwner() {
c.Error(404)
return
}
ctx.Repo.Repository.Description = ctx.Query("desc")
ctx.Repo.Repository.Website = ctx.Query("site")
err = models.UpdateRepository(ctx.Repo.Repository, false)
c.Repo.Repository.Description = c.Query("desc")
c.Repo.Repository.Website = c.Query("site")
err = models.UpdateRepository(c.Repo.Repository, false)
}
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
}
redirectTo := ctx.Query("redirect_to")
redirectTo := c.Query("redirect_to")
if len(redirectTo) == 0 {
redirectTo = ctx.Repo.RepoLink
redirectTo = c.Repo.RepoLink
}
ctx.Redirect(redirectTo)
c.Redirect(redirectTo)
}
func Download(ctx *context.Context) {
func Download(c *context.Context) {
var (
uri = ctx.Params("*")
uri = c.Params("*")
refName string
ext string
archivePath string
@ -274,22 +274,22 @@ func Download(ctx *context.Context) {
switch {
case strings.HasSuffix(uri, ".zip"):
ext = ".zip"
archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/zip")
archivePath = path.Join(c.Repo.GitRepo.Path, "archives/zip")
archiveType = git.ZIP
case strings.HasSuffix(uri, ".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
default:
log.Trace("Unknown format: %s", uri)
ctx.Error(404)
c.Error(404)
return
}
refName = strings.TrimSuffix(uri, ext)
if !com.IsDir(archivePath) {
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
}
}
@ -299,37 +299,37 @@ func Download(ctx *context.Context) {
commit *git.Commit
err error
)
gitRepo := ctx.Repo.GitRepo
gitRepo := c.Repo.GitRepo
if gitRepo.IsBranchExist(refName) {
commit, err = gitRepo.GetBranchCommit(refName)
if err != nil {
ctx.Handle(500, "GetBranchCommit", err)
c.Handle(500, "GetBranchCommit", err)
return
}
} else if gitRepo.IsTagExist(refName) {
commit, err = gitRepo.GetTagCommit(refName)
if err != nil {
ctx.Handle(500, "GetTagCommit", err)
c.Handle(500, "GetTagCommit", err)
return
}
} else if len(refName) >= 7 && len(refName) <= 40 {
commit, err = gitRepo.GetCommit(refName)
if err != nil {
ctx.NotFound()
c.NotFound()
return
}
} else {
ctx.NotFound()
c.NotFound()
return
}
archivePath = path.Join(archivePath, tool.ShortSHA1(commit.ID.String())+ext)
if !com.IsFile(archivePath) {
if err := commit.CreateArchive(archivePath, archiveType); err != nil {
ctx.Handle(500, "Download -> CreateArchive "+archivePath, err)
c.Handle(500, "Download -> CreateArchive "+archivePath, err)
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"
)
func Settings(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsOptions"] = true
ctx.HTML(200, SETTINGS_OPTIONS)
func Settings(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings")
c.Data["PageIsSettingsOptions"] = true
c.HTML(200, SETTINGS_OPTIONS)
}
func SettingsPost(ctx *context.Context, f form.RepoSetting) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsOptions"] = true
func SettingsPost(c *context.Context, f form.RepoSetting) {
c.Data["Title"] = c.Tr("repo.settings")
c.Data["PageIsSettingsOptions"] = true
repo := ctx.Repo.Repository
repo := c.Repo.Repository
switch ctx.Query("action") {
switch c.Query("action") {
case "update":
if ctx.HasError() {
ctx.HTML(200, SETTINGS_OPTIONS)
if c.HasError() {
c.HTML(200, SETTINGS_OPTIONS)
return
}
@ -56,22 +56,22 @@ func SettingsPost(ctx *context.Context, f form.RepoSetting) {
// Check if repository name has been changed.
if repo.LowerName != strings.ToLower(newRepoName) {
isNameChanged = true
if err := models.ChangeRepositoryName(ctx.Repo.Owner, repo.Name, newRepoName); err != nil {
ctx.Data["Err_RepoName"] = true
if err := models.ChangeRepositoryName(c.Repo.Owner, repo.Name, newRepoName); err != nil {
c.Data["Err_RepoName"] = true
switch {
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):
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):
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:
ctx.Handle(500, "ChangeRepositoryName", err)
c.Handle(500, "ChangeRepositoryName", err)
}
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.
repo.Name = newRepoName
@ -88,52 +88,52 @@ func SettingsPost(ctx *context.Context, f form.RepoSetting) {
visibilityChanged := repo.IsPrivate != f.Private
repo.IsPrivate = f.Private
if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
ctx.Handle(500, "UpdateRepository", err)
c.Handle(500, "UpdateRepository", err)
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 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)
}
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings")
c.Flash.Success(c.Tr("repo.settings.update_settings_success"))
c.Redirect(repo.Link() + "/settings")
case "mirror":
if !repo.IsMirror {
ctx.Handle(404, "", nil)
c.Handle(404, "", nil)
return
}
if f.Interval > 0 {
ctx.Repo.Mirror.EnablePrune = f.EnablePrune
ctx.Repo.Mirror.Interval = f.Interval
ctx.Repo.Mirror.NextUpdate = time.Now().Add(time.Duration(f.Interval) * time.Hour)
if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil {
ctx.Handle(500, "UpdateMirror", err)
c.Repo.Mirror.EnablePrune = f.EnablePrune
c.Repo.Mirror.Interval = f.Interval
c.Repo.Mirror.NextUpdate = time.Now().Add(time.Duration(f.Interval) * time.Hour)
if err := models.UpdateMirror(c.Repo.Mirror); err != nil {
c.Handle(500, "UpdateMirror", err)
return
}
}
if err := ctx.Repo.Mirror.SaveAddress(f.MirrorAddress); err != nil {
ctx.Handle(500, "SaveAddress", err)
if err := c.Repo.Mirror.SaveAddress(f.MirrorAddress); err != nil {
c.Handle(500, "SaveAddress", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
ctx.Redirect(repo.Link() + "/settings")
c.Flash.Success(c.Tr("repo.settings.update_settings_success"))
c.Redirect(repo.Link() + "/settings")
case "mirror-sync":
if !repo.IsMirror {
ctx.Handle(404, "", nil)
c.Handle(404, "", nil)
return
}
go models.MirrorQueue.Add(repo.ID)
ctx.Flash.Info(ctx.Tr("repo.settings.mirror_sync_in_progress"))
ctx.Redirect(repo.Link() + "/settings")
c.Flash.Info(c.Tr("repo.settings.mirror_sync_in_progress"))
c.Redirect(repo.Link() + "/settings")
case "advanced":
repo.EnableWiki = f.EnableWiki
@ -149,290 +149,290 @@ func SettingsPost(ctx *context.Context, f form.RepoSetting) {
repo.EnablePulls = f.EnablePulls
if err := models.UpdateRepository(repo, false); err != nil {
ctx.Handle(500, "UpdateRepository", err)
c.Handle(500, "UpdateRepository", err)
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"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
c.Flash.Success(c.Tr("repo.settings.update_settings_success"))
c.Redirect(c.Repo.RepoLink + "/settings")
case "convert":
if !ctx.Repo.IsOwner() {
ctx.Error(404)
if !c.Repo.IsOwner() {
c.Error(404)
return
}
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
}
if ctx.Repo.Owner.IsOrganization() {
if !ctx.Repo.Owner.IsOwnedBy(ctx.User.ID) {
ctx.Error(404)
if c.Repo.Owner.IsOrganization() {
if !c.Repo.Owner.IsOwnedBy(c.User.ID) {
c.Error(404)
return
}
}
if !repo.IsMirror {
ctx.Error(404)
c.Error(404)
return
}
repo.IsMirror = false
if _, err := models.CleanUpMigrateInfo(repo); err != nil {
ctx.Handle(500, "CleanUpMigrateInfo", err)
c.Handle(500, "CleanUpMigrateInfo", err)
return
} else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil {
ctx.Handle(500, "DeleteMirrorByRepoID", err)
} else if err = models.DeleteMirrorByRepoID(c.Repo.Repository.ID); err != nil {
c.Handle(500, "DeleteMirrorByRepoID", err)
return
}
log.Trace("Repository converted from mirror to regular: %s/%s", ctx.Repo.Owner.Name, repo.Name)
ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed"))
ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name)
log.Trace("Repository converted from mirror to regular: %s/%s", c.Repo.Owner.Name, repo.Name)
c.Flash.Success(c.Tr("repo.settings.convert_succeed"))
c.Redirect(setting.AppSubURL + "/" + c.Repo.Owner.Name + "/" + repo.Name)
case "transfer":
if !ctx.Repo.IsOwner() {
ctx.Error(404)
if !c.Repo.IsOwner() {
c.Error(404)
return
}
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
}
if ctx.Repo.Owner.IsOrganization() && !ctx.User.IsAdmin {
if !ctx.Repo.Owner.IsOwnedBy(ctx.User.ID) {
ctx.Error(404)
if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin {
if !c.Repo.Owner.IsOwnedBy(c.User.ID) {
c.Error(404)
return
}
}
newOwner := ctx.Query("new_owner_name")
newOwner := c.Query("new_owner_name")
isExist, err := models.IsUserExist(0, newOwner)
if err != nil {
ctx.Handle(500, "IsUserExist", err)
c.Handle(500, "IsUserExist", err)
return
} 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
}
if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil {
if err = models.TransferOwnership(c.User, newOwner, repo); err != nil {
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 {
ctx.Handle(500, "TransferOwnership", err)
c.Handle(500, "TransferOwnership", err)
}
return
}
log.Trace("Repository transfered: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner)
ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed"))
ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name)
log.Trace("Repository transfered: %s/%s -> %s", c.Repo.Owner.Name, repo.Name, newOwner)
c.Flash.Success(c.Tr("repo.settings.transfer_succeed"))
c.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name)
case "delete":
if !ctx.Repo.IsOwner() {
ctx.Error(404)
if !c.Repo.IsOwner() {
c.Error(404)
return
}
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
}
if ctx.Repo.Owner.IsOrganization() && !ctx.User.IsAdmin {
if !ctx.Repo.Owner.IsOwnedBy(ctx.User.ID) {
ctx.Error(404)
if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin {
if !c.Repo.Owner.IsOwnedBy(c.User.ID) {
c.Error(404)
return
}
}
if err := models.DeleteRepository(ctx.Repo.Owner.ID, repo.ID); err != nil {
ctx.Handle(500, "DeleteRepository", err)
if err := models.DeleteRepository(c.Repo.Owner.ID, repo.ID); err != nil {
c.Handle(500, "DeleteRepository", err)
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"))
ctx.Redirect(ctx.Repo.Owner.DashboardLink())
c.Flash.Success(c.Tr("repo.settings.deletion_success"))
c.Redirect(c.Repo.Owner.DashboardLink())
case "delete-wiki":
if !ctx.Repo.IsOwner() {
ctx.Error(404)
if !c.Repo.IsOwner() {
c.Error(404)
return
}
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
}
if ctx.Repo.Owner.IsOrganization() && !ctx.User.IsAdmin {
if !ctx.Repo.Owner.IsOwnedBy(ctx.User.ID) {
ctx.Error(404)
if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin {
if !c.Repo.Owner.IsOwnedBy(c.User.ID) {
c.Error(404)
return
}
}
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
if err := models.UpdateRepository(repo, false); err != nil {
ctx.Handle(500, "UpdateRepository", err)
c.Handle(500, "UpdateRepository", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings")
c.Flash.Success(c.Tr("repo.settings.wiki_deletion_success"))
c.Redirect(c.Repo.RepoLink + "/settings")
default:
ctx.Handle(404, "", nil)
c.Handle(404, "", nil)
}
}
func SettingsCollaboration(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsCollaboration"] = true
func SettingsCollaboration(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings")
c.Data["PageIsSettingsCollaboration"] = true
users, err := ctx.Repo.Repository.GetCollaborators()
users, err := c.Repo.Repository.GetCollaborators()
if err != nil {
ctx.Handle(500, "GetCollaborators", err)
c.Handle(500, "GetCollaborators", err)
return
}
ctx.Data["Collaborators"] = users
c.Data["Collaborators"] = users
ctx.HTML(200, SETTINGS_COLLABORATION)
c.HTML(200, SETTINGS_COLLABORATION)
}
func SettingsCollaborationPost(ctx *context.Context) {
name := strings.ToLower(ctx.Query("collaborator"))
if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
func SettingsCollaborationPost(c *context.Context) {
name := strings.ToLower(c.Query("collaborator"))
if len(name) == 0 || c.Repo.Owner.LowerName == name {
c.Redirect(setting.AppSubURL + c.Req.URL.Path)
return
}
u, err := models.GetUserByName(name)
if err != nil {
if errors.IsUserNotExist(err) {
ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
c.Flash.Error(c.Tr("form.user_not_exist"))
c.Redirect(setting.AppSubURL + c.Req.URL.Path)
} else {
ctx.Handle(500, "GetUserByName", err)
c.Handle(500, "GetUserByName", err)
}
return
}
// Organization is not allowed to be added as a collaborator
if u.IsOrganization() {
ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
c.Flash.Error(c.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
c.Redirect(setting.AppSubURL + c.Req.URL.Path)
return
}
if err = ctx.Repo.Repository.AddCollaborator(u); err != nil {
ctx.Handle(500, "AddCollaborator", err)
if err = c.Repo.Repository.AddCollaborator(u); err != nil {
c.Handle(500, "AddCollaborator", err)
return
}
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"))
ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
c.Flash.Success(c.Tr("repo.settings.add_collaborator_success"))
c.Redirect(setting.AppSubURL + c.Req.URL.Path)
}
func ChangeCollaborationAccessMode(ctx *context.Context) {
if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(
ctx.QueryInt64("uid"),
models.AccessMode(ctx.QueryInt("mode"))); err != nil {
func ChangeCollaborationAccessMode(c *context.Context) {
if err := c.Repo.Repository.ChangeCollaborationAccessMode(
c.QueryInt64("uid"),
models.AccessMode(c.QueryInt("mode"))); err != nil {
log.Error(2, "ChangeCollaborationAccessMode: %v", err)
return
}
ctx.Status(204)
c.Status(204)
}
func DeleteCollaboration(ctx *context.Context) {
if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteCollaboration: " + err.Error())
func DeleteCollaboration(c *context.Context) {
if err := c.Repo.Repository.DeleteCollaboration(c.QueryInt64("id")); err != nil {
c.Flash.Error("DeleteCollaboration: " + err.Error())
} 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{}{
"redirect": ctx.Repo.RepoLink + "/settings/collaboration",
c.JSON(200, map[string]interface{}{
"redirect": c.Repo.RepoLink + "/settings/collaboration",
})
}
func SettingsBranches(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.branches")
ctx.Data["PageIsSettingsBranches"] = true
func SettingsBranches(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings.branches")
c.Data["PageIsSettingsBranches"] = true
if ctx.Repo.Repository.IsBare {
ctx.Flash.Info(ctx.Tr("repo.settings.branches_bare"), true)
ctx.HTML(200, SETTINGS_BRANCHES)
if c.Repo.Repository.IsBare {
c.Flash.Info(c.Tr("repo.settings.branches_bare"), true)
c.HTML(200, SETTINGS_BRANCHES)
return
}
protectBranches, err := models.GetProtectBranchesByRepoID(ctx.Repo.Repository.ID)
protectBranches, err := models.GetProtectBranchesByRepoID(c.Repo.Repository.ID)
if err != nil {
ctx.Handle(500, "GetProtectBranchesByRepoID", err)
c.Handle(500, "GetProtectBranchesByRepoID", err)
return
}
// Filter out deleted branches
branches := make([]string, 0, len(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)
}
}
ctx.Data["ProtectBranches"] = branches
c.Data["ProtectBranches"] = branches
ctx.HTML(200, SETTINGS_BRANCHES)
c.HTML(200, SETTINGS_BRANCHES)
}
func UpdateDefaultBranch(ctx *context.Context) {
branch := ctx.Query("branch")
if ctx.Repo.GitRepo.IsBranchExist(branch) &&
ctx.Repo.Repository.DefaultBranch != branch {
ctx.Repo.Repository.DefaultBranch = branch
if err := ctx.Repo.GitRepo.SetDefaultBranch(branch); err != nil {
func UpdateDefaultBranch(c *context.Context) {
branch := c.Query("branch")
if c.Repo.GitRepo.IsBranchExist(branch) &&
c.Repo.Repository.DefaultBranch != branch {
c.Repo.Repository.DefaultBranch = branch
if err := c.Repo.GitRepo.SetDefaultBranch(branch); err != nil {
if !git.IsErrUnsupportedVersion(err) {
ctx.Handle(500, "SetDefaultBranch", err)
c.Handle(500, "SetDefaultBranch", err)
return
}
ctx.Flash.Warning(ctx.Tr("repo.settings.update_default_branch_unsupported"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/branches")
c.Flash.Warning(c.Tr("repo.settings.update_default_branch_unsupported"))
c.Redirect(c.Repo.RepoLink + "/settings/branches")
return
}
}
if err := models.UpdateRepository(ctx.Repo.Repository, false); err != nil {
ctx.Handle(500, "UpdateRepository", err)
if err := models.UpdateRepository(c.Repo.Repository, false); err != nil {
c.Handle(500, "UpdateRepository", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_default_branch_success"))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/branches")
c.Flash.Success(c.Tr("repo.settings.update_default_branch_success"))
c.Redirect(c.Repo.RepoLink + "/settings/branches")
}
func SettingsProtectedBranch(ctx *context.Context) {
branch := ctx.Params("*")
if !ctx.Repo.GitRepo.IsBranchExist(branch) {
ctx.NotFound()
func SettingsProtectedBranch(c *context.Context) {
branch := c.Params("*")
if !c.Repo.GitRepo.IsBranchExist(branch) {
c.NotFound()
return
}
ctx.Data["Title"] = ctx.Tr("repo.settings.protected_branches") + " - " + branch
ctx.Data["PageIsSettingsBranches"] = true
c.Data["Title"] = c.Tr("repo.settings.protected_branches") + " - " + branch
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 !models.IsErrBranchNotExist(err) {
ctx.Handle(500, "GetProtectBranchOfRepoByName", err)
c.Handle(500, "GetProtectBranchOfRepoByName", err)
return
}
@ -442,45 +442,45 @@ func SettingsProtectedBranch(ctx *context.Context) {
}
}
if ctx.Repo.Owner.IsOrganization() {
users, err := ctx.Repo.Repository.GetWriters()
if c.Repo.Owner.IsOrganization() {
users, err := c.Repo.Repository.GetWriters()
if err != nil {
ctx.Handle(500, "Repo.Repository.GetPushers", err)
c.Handle(500, "Repo.Repository.GetPushers", err)
return
}
ctx.Data["Users"] = users
ctx.Data["whitelist_users"] = protectBranch.WhitelistUserIDs
c.Data["Users"] = users
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 {
ctx.Handle(500, "Repo.Owner.TeamsHaveAccessToRepo", err)
c.Handle(500, "Repo.Owner.TeamsHaveAccessToRepo", err)
return
}
ctx.Data["Teams"] = teams
ctx.Data["whitelist_teams"] = protectBranch.WhitelistTeamIDs
c.Data["Teams"] = teams
c.Data["whitelist_teams"] = protectBranch.WhitelistTeamIDs
}
ctx.Data["Branch"] = protectBranch
ctx.HTML(200, SETTINGS_PROTECTED_BRANCH)
c.Data["Branch"] = protectBranch
c.HTML(200, SETTINGS_PROTECTED_BRANCH)
}
func SettingsProtectedBranchPost(ctx *context.Context, f form.ProtectBranch) {
branch := ctx.Params("*")
if !ctx.Repo.GitRepo.IsBranchExist(branch) {
ctx.NotFound()
func SettingsProtectedBranchPost(c *context.Context, f form.ProtectBranch) {
branch := c.Params("*")
if !c.Repo.GitRepo.IsBranchExist(branch) {
c.NotFound()
return
}
protectBranch, err := models.GetProtectBranchOfRepoByName(ctx.Repo.Repository.ID, branch)
protectBranch, err := models.GetProtectBranchOfRepoByName(c.Repo.Repository.ID, branch)
if err != nil {
if !models.IsErrBranchNotExist(err) {
ctx.Handle(500, "GetProtectBranchOfRepoByName", err)
c.Handle(500, "GetProtectBranchOfRepoByName", err)
return
}
// No options found, create defaults.
protectBranch = &models.ProtectBranch{
RepoID: ctx.Repo.Repository.ID,
RepoID: c.Repo.Repository.ID,
Name: branch,
}
}
@ -488,144 +488,144 @@ func SettingsProtectedBranchPost(ctx *context.Context, f form.ProtectBranch) {
protectBranch.Protected = f.Protected
protectBranch.RequirePullRequest = f.RequirePullRequest
protectBranch.EnableWhitelist = f.EnableWhitelist
if ctx.Repo.Owner.IsOrganization() {
err = models.UpdateOrgProtectBranch(ctx.Repo.Repository, protectBranch, f.WhitelistUsers, f.WhitelistTeams)
if c.Repo.Owner.IsOrganization() {
err = models.UpdateOrgProtectBranch(c.Repo.Repository, protectBranch, f.WhitelistUsers, f.WhitelistTeams)
} else {
err = models.UpdateProtectBranch(protectBranch)
}
if err != nil {
ctx.Handle(500, "UpdateOrgProtectBranch/UpdateProtectBranch", err)
c.Handle(500, "UpdateOrgProtectBranch/UpdateProtectBranch", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_protect_branch_success"))
ctx.Redirect(fmt.Sprintf("%s/settings/branches/%s", ctx.Repo.RepoLink, branch))
c.Flash.Success(c.Tr("repo.settings.update_protect_branch_success"))
c.Redirect(fmt.Sprintf("%s/settings/branches/%s", c.Repo.RepoLink, branch))
}
func SettingsGitHooks(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
ctx.Data["PageIsSettingsGitHooks"] = true
func SettingsGitHooks(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings.githooks")
c.Data["PageIsSettingsGitHooks"] = true
hooks, err := ctx.Repo.GitRepo.Hooks()
hooks, err := c.Repo.GitRepo.Hooks()
if err != nil {
ctx.Handle(500, "Hooks", err)
c.Handle(500, "Hooks", err)
return
}
ctx.Data["Hooks"] = hooks
c.Data["Hooks"] = hooks
ctx.HTML(200, SETTINGS_GITHOOKS)
c.HTML(200, SETTINGS_GITHOOKS)
}
func SettingsGitHooksEdit(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
ctx.Data["PageIsSettingsGitHooks"] = true
ctx.Data["RequireSimpleMDE"] = true
func SettingsGitHooksEdit(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings.githooks")
c.Data["PageIsSettingsGitHooks"] = true
c.Data["RequireSimpleMDE"] = true
name := ctx.Params(":name")
hook, err := ctx.Repo.GitRepo.GetHook(name)
name := c.Params(":name")
hook, err := c.Repo.GitRepo.GetHook(name)
if err != nil {
if err == git.ErrNotValidHook {
ctx.Handle(404, "GetHook", err)
c.Handle(404, "GetHook", err)
} else {
ctx.Handle(500, "GetHook", err)
c.Handle(500, "GetHook", err)
}
return
}
ctx.Data["Hook"] = hook
ctx.HTML(200, SETTINGS_GITHOOK_EDIT)
c.Data["Hook"] = hook
c.HTML(200, SETTINGS_GITHOOK_EDIT)
}
func SettingsGitHooksEditPost(ctx *context.Context) {
name := ctx.Params(":name")
hook, err := ctx.Repo.GitRepo.GetHook(name)
func SettingsGitHooksEditPost(c *context.Context) {
name := c.Params(":name")
hook, err := c.Repo.GitRepo.GetHook(name)
if err != nil {
if err == git.ErrNotValidHook {
ctx.Handle(404, "GetHook", err)
c.Handle(404, "GetHook", err)
} else {
ctx.Handle(500, "GetHook", err)
c.Handle(500, "GetHook", err)
}
return
}
hook.Content = ctx.Query("content")
hook.Content = c.Query("content")
if err = hook.Update(); err != nil {
ctx.Handle(500, "hook.Update", err)
c.Handle(500, "hook.Update", err)
return
}
ctx.Redirect(ctx.Data["Link"].(string))
c.Redirect(c.Data["Link"].(string))
}
func SettingsDeployKeys(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
ctx.Data["PageIsSettingsKeys"] = true
func SettingsDeployKeys(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings.deploy_keys")
c.Data["PageIsSettingsKeys"] = true
keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
keys, err := models.ListDeployKeys(c.Repo.Repository.ID)
if err != nil {
ctx.Handle(500, "ListDeployKeys", err)
c.Handle(500, "ListDeployKeys", err)
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) {
ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
ctx.Data["PageIsSettingsKeys"] = true
func SettingsDeployKeysPost(c *context.Context, f form.AddSSHKey) {
c.Data["Title"] = c.Tr("repo.settings.deploy_keys")
c.Data["PageIsSettingsKeys"] = true
keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
keys, err := models.ListDeployKeys(c.Repo.Repository.ID)
if err != nil {
ctx.Handle(500, "ListDeployKeys", err)
c.Handle(500, "ListDeployKeys", err)
return
}
ctx.Data["Deploykeys"] = keys
c.Data["Deploykeys"] = keys
if ctx.HasError() {
ctx.HTML(200, SETTINGS_DEPLOY_KEYS)
if c.HasError() {
c.HTML(200, SETTINGS_DEPLOY_KEYS)
return
}
content, err := models.CheckPublicKeyString(f.Content)
if err != nil {
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 {
ctx.Data["HasError"] = true
ctx.Data["Err_Content"] = true
ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
c.Data["HasError"] = true
c.Data["Err_Content"] = true
c.Flash.Error(c.Tr("form.invalid_ssh_key", err.Error()))
c.Redirect(c.Repo.RepoLink + "/settings/keys")
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 {
ctx.Data["HasError"] = true
c.Data["HasError"] = true
switch {
case models.IsErrKeyAlreadyExist(err):
ctx.Data["Err_Content"] = true
ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), SETTINGS_DEPLOY_KEYS, &f)
c.Data["Err_Content"] = true
c.RenderWithErr(c.Tr("repo.settings.key_been_used"), SETTINGS_DEPLOY_KEYS, &f)
case models.IsErrKeyNameAlreadyUsed(err):
ctx.Data["Err_Title"] = true
ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), SETTINGS_DEPLOY_KEYS, &f)
c.Data["Err_Title"] = true
c.RenderWithErr(c.Tr("repo.settings.key_name_used"), SETTINGS_DEPLOY_KEYS, &f)
default:
ctx.Handle(500, "AddDeployKey", err)
c.Handle(500, "AddDeployKey", err)
}
return
}
log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
log.Trace("Deploy key added: %d", c.Repo.Repository.ID)
c.Flash.Success(c.Tr("repo.settings.add_key_success", key.Name))
c.Redirect(c.Repo.RepoLink + "/settings/keys")
}
func DeleteDeployKey(ctx *context.Context) {
if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteDeployKey: " + err.Error())
func DeleteDeployKey(c *context.Context) {
if err := models.DeleteDeployKey(c.User, c.QueryInt64("id")); err != nil {
c.Flash.Error("DeleteDeployKey: " + err.Error())
} 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{}{
"redirect": ctx.Repo.RepoLink + "/settings/keys",
c.JSON(200, map[string]interface{}{
"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) {
ctx.Data["IsViewFile"] = true
func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
c.Data["IsViewFile"] = true
blob := entry.Blob()
dataRc, err := blob.Data()
if err != nil {
ctx.Handle(500, "Data", err)
c.Handle(500, "Data", err)
return
}
ctx.Data["FileSize"] = blob.Size()
ctx.Data["FileName"] = blob.Name()
ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
c.Data["FileSize"] = blob.Size()
c.Data["FileName"] = blob.Name()
c.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
c.Data["RawFileLink"] = rawLink + "/" + c.Repo.TreePath
buf := make([]byte, 1024)
n, _ := dataRc.Read(buf)
buf = buf[:n]
isTextFile := tool.IsTextFile(buf)
ctx.Data["IsTextFile"] = isTextFile
c.Data["IsTextFile"] = isTextFile
// Assume file is not editable first.
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 {
case isTextFile:
if blob.Size() >= setting.UI.MaxDisplayFileSize {
ctx.Data["IsFileTooLarge"] = true
c.Data["IsFileTooLarge"] = true
break
}
ctx.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name())
c.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name())
d, _ := ioutil.ReadAll(dataRc)
buf = append(buf, d...)
switch markup.Detect(blob.Name()) {
case markup.MARKDOWN:
ctx.Data["IsMarkdown"] = true
ctx.Data["FileContent"] = string(markup.Markdown(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
c.Data["IsMarkdown"] = true
c.Data["FileContent"] = string(markup.Markdown(buf, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
case markup.ORG_MODE:
ctx.Data["IsMarkdown"] = true
ctx.Data["FileContent"] = string(markup.OrgMode(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
c.Data["IsMarkdown"] = true
c.Data["FileContent"] = string(markup.OrgMode(buf, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
case markup.IPYTHON_NOTEBOOK:
ctx.Data["IsIPythonNotebook"] = true
c.Data["IsIPythonNotebook"] = true
default:
// Building code view blocks with line number on server side.
var fileContent string
@ -188,180 +188,180 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
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")
}
ctx.Data["FileContent"] = gotemplate.HTML(output.String())
c.Data["FileContent"] = gotemplate.HTML(output.String())
output.Reset()
for i := 0; i < len(lines); i++ {
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 {
ctx.Data["CanEditFile"] = true
ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
} else if !ctx.Repo.IsViewBranch {
ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
} else if !ctx.Repo.IsWriter() {
ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
c.Data["CanEditFile"] = true
c.Data["EditFileTooltip"] = c.Tr("repo.editor.edit_this_file")
} else if !c.Repo.IsViewBranch {
c.Data["EditFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
} else if !c.Repo.IsWriter() {
c.Data["EditFileTooltip"] = c.Tr("repo.editor.fork_before_edit")
}
case tool.IsPDFFile(buf):
ctx.Data["IsPDFFile"] = true
c.Data["IsPDFFile"] = true
case tool.IsVideoFile(buf):
ctx.Data["IsVideoFile"] = true
c.Data["IsVideoFile"] = true
case tool.IsImageFile(buf):
ctx.Data["IsImageFile"] = true
c.Data["IsImageFile"] = true
}
if canEnableEditor {
ctx.Data["CanDeleteFile"] = true
ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
} else if !ctx.Repo.IsViewBranch {
ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
} else if !ctx.Repo.IsWriter() {
ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
c.Data["CanDeleteFile"] = true
c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.delete_this_file")
} else if !c.Repo.IsViewBranch {
c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
} else if !c.Repo.IsWriter() {
c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_have_write_access")
}
}
func setEditorconfigIfExists(ctx *context.Context) {
ec, err := ctx.Repo.GetEditorconfig()
func setEditorconfigIfExists(c *context.Context) {
ec, err := c.Repo.GetEditorconfig()
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
}
ctx.Data["Editorconfig"] = ec
c.Data["Editorconfig"] = ec
}
func Home(ctx *context.Context) {
ctx.Data["PageIsViewFiles"] = true
func Home(c *context.Context) {
c.Data["PageIsViewFiles"] = true
if ctx.Repo.Repository.IsBare {
ctx.HTML(200, BARE)
if c.Repo.Repository.IsBare {
c.HTML(200, BARE)
return
}
title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
if len(ctx.Repo.Repository.Description) > 0 {
title += ": " + ctx.Repo.Repository.Description
title := c.Repo.Repository.Owner.Name + "/" + c.Repo.Repository.Name
if len(c.Repo.Repository.Description) > 0 {
title += ": " + c.Repo.Repository.Description
}
ctx.Data["Title"] = title
if ctx.Repo.BranchName != ctx.Repo.Repository.DefaultBranch {
ctx.Data["Title"] = title + " @ " + ctx.Repo.BranchName
c.Data["Title"] = title
if c.Repo.BranchName != c.Repo.Repository.DefaultBranch {
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
rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
rawLink := c.Repo.RepoLink + "/raw/" + c.Repo.BranchName
isRootDir := false
if len(ctx.Repo.TreePath) > 0 {
treeLink += "/" + ctx.Repo.TreePath
if len(c.Repo.TreePath) > 0 {
treeLink += "/" + c.Repo.TreePath
} else {
isRootDir = true
// Only show Git stats panel when view root directory
var err error
ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
c.Repo.CommitsCount, err = c.Repo.Commit.CommitsCount()
if err != nil {
ctx.Handle(500, "CommitsCount", err)
c.Handle(500, "CommitsCount", err)
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.
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
entry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath)
if err != nil {
ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
c.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
return
}
if entry.IsDir() {
renderDirectory(ctx, treeLink)
renderDirectory(c, treeLink)
} else {
renderFile(ctx, entry, treeLink, rawLink)
renderFile(c, entry, treeLink, rawLink)
}
if ctx.Written() {
if c.Written() {
return
}
setEditorconfigIfExists(ctx)
if ctx.Written() {
setEditorconfigIfExists(c)
if c.Written() {
return
}
var treeNames []string
paths := make([]string, 0, 5)
if len(ctx.Repo.TreePath) > 0 {
treeNames = strings.Split(ctx.Repo.TreePath, "/")
if len(c.Repo.TreePath) > 0 {
treeNames = strings.Split(c.Repo.TreePath, "/")
for i := range treeNames {
paths = append(paths, strings.Join(treeNames[:i+1], "/"))
}
ctx.Data["HasParentPath"] = true
c.Data["HasParentPath"] = true
if len(paths)-2 >= 0 {
ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
c.Data["ParentPath"] = "/" + paths[len(paths)-2]
}
}
ctx.Data["Paths"] = paths
ctx.Data["TreeLink"] = treeLink
ctx.Data["TreeNames"] = treeNames
ctx.Data["BranchLink"] = branchLink
ctx.HTML(200, HOME)
c.Data["Paths"] = paths
c.Data["TreeLink"] = treeLink
c.Data["TreeNames"] = treeNames
c.Data["BranchLink"] = branchLink
c.HTML(200, HOME)
}
func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl string) {
page := ctx.QueryInt("page")
func RenderUserCards(c *context.Context, total int, getter func(page int) ([]*models.User, error), tpl string) {
page := c.QueryInt("page")
if page <= 0 {
page = 1
}
pager := paginater.New(total, models.ItemsPerPage, page, 5)
ctx.Data["Page"] = pager
c.Data["Page"] = pager
items, err := getter(pager.Current())
if err != nil {
ctx.Handle(500, "getter", err)
c.Handle(500, "getter", err)
return
}
ctx.Data["Cards"] = items
c.Data["Cards"] = items
ctx.HTML(200, tpl)
c.HTML(200, tpl)
}
func Watchers(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.watchers")
ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
ctx.Data["PageIsWatchers"] = true
RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, WATCHERS)
func Watchers(c *context.Context) {
c.Data["Title"] = c.Tr("repo.watchers")
c.Data["CardsTitle"] = c.Tr("repo.watchers")
c.Data["PageIsWatchers"] = true
RenderUserCards(c, c.Repo.Repository.NumWatches, c.Repo.Repository.GetWatchers, WATCHERS)
}
func Stars(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.stargazers")
ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
ctx.Data["PageIsStargazers"] = true
RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, WATCHERS)
func Stars(c *context.Context) {
c.Data["Title"] = c.Tr("repo.stargazers")
c.Data["CardsTitle"] = c.Tr("repo.stargazers")
c.Data["PageIsStargazers"] = true
RenderUserCards(c, c.Repo.Repository.NumStars, c.Repo.Repository.GetStargazers, WATCHERS)
}
func Forks(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repos.forks")
func Forks(c *context.Context) {
c.Data["Title"] = c.Tr("repos.forks")
forks, err := ctx.Repo.Repository.GetForks()
forks, err := c.Repo.Repository.GetForks()
if err != nil {
ctx.Handle(500, "GetForks", err)
c.Handle(500, "GetForks", err)
return
}
for _, fork := range forks {
if err = fork.GetOwner(); err != nil {
ctx.Handle(500, "GetOwner", err)
c.Handle(500, "GetOwner", err)
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"
)
func Webhooks(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.hooks")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["BaseLink"] = ctx.Repo.RepoLink
ctx.Data["Description"] = ctx.Tr("repo.settings.hooks_desc", "https://github.com/gogits/go-gogs-client/wiki/Repositories-Webhooks")
ctx.Data["Types"] = setting.Webhook.Types
ws, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID)
func Webhooks(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings.hooks")
c.Data["PageIsSettingsHooks"] = true
c.Data["BaseLink"] = c.Repo.RepoLink
c.Data["Description"] = c.Tr("repo.settings.hooks_desc", "https://github.com/gogits/go-gogs-client/wiki/Repositories-Webhooks")
c.Data["Types"] = setting.Webhook.Types
ws, err := models.GetWebhooksByRepoID(c.Repo.Repository.ID)
if err != nil {
ctx.Handle(500, "GetWebhooksByRepoID", err)
c.Handle(500, "GetWebhooksByRepoID", err)
return
}
ctx.Data["Webhooks"] = ws
c.Data["Webhooks"] = ws
ctx.HTML(200, WEBHOOKS)
c.HTML(200, WEBHOOKS)
}
type OrgRepoCtx struct {
@ -52,21 +52,21 @@ type OrgRepoCtx struct {
}
// getOrgRepoCtx determines whether this is a repo context or organization context.
func getOrgRepoCtx(ctx *context.Context) (*OrgRepoCtx, error) {
if len(ctx.Repo.RepoLink) > 0 {
ctx.Data["PageIsRepositoryContext"] = true
func getOrgRepoCtx(c *context.Context) (*OrgRepoCtx, error) {
if len(c.Repo.RepoLink) > 0 {
c.Data["PageIsRepositoryContext"] = true
return &OrgRepoCtx{
RepoID: ctx.Repo.Repository.ID,
Link: ctx.Repo.RepoLink,
RepoID: c.Repo.Repository.ID,
Link: c.Repo.RepoLink,
NewTemplate: WEBHOOK_NEW,
}, nil
}
if len(ctx.Org.OrgLink) > 0 {
ctx.Data["PageIsOrganizationContext"] = true
if len(c.Org.OrgLink) > 0 {
c.Data["PageIsOrganizationContext"] = true
return &OrgRepoCtx{
OrgID: ctx.Org.Organization.ID,
Link: ctx.Org.OrgLink,
OrgID: c.Org.Organization.ID,
Link: c.Org.OrgLink,
NewTemplate: ORG_WEBHOOK_NEW,
}, nil
}
@ -74,34 +74,34 @@ func getOrgRepoCtx(ctx *context.Context) (*OrgRepoCtx, error) {
return nil, errors.New("Unable to set OrgRepo context")
}
func checkHookType(ctx *context.Context) string {
hookType := strings.ToLower(ctx.Params(":type"))
func checkHookType(c *context.Context) string {
hookType := strings.ToLower(c.Params(":type"))
if !com.IsSliceContainsStr(setting.Webhook.Types, hookType) {
ctx.Handle(404, "checkHookType", nil)
c.Handle(404, "checkHookType", nil)
return ""
}
return hookType
}
func WebhooksNew(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
func WebhooksNew(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings.add_webhook")
c.Data["PageIsSettingsHooks"] = true
c.Data["PageIsSettingsHooksNew"] = true
c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
orCtx, err := getOrgRepoCtx(ctx)
orCtx, err := getOrgRepoCtx(c)
if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err)
c.Handle(500, "getOrgRepoCtx", err)
return
}
ctx.Data["HookType"] = checkHookType(ctx)
if ctx.Written() {
c.Data["HookType"] = checkHookType(c)
if c.Written() {
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 {
@ -122,22 +122,22 @@ func ParseHookEvent(f form.Webhook) *models.HookEvent {
}
}
func WebHooksNewPost(ctx *context.Context, f form.NewWebhook) {
ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
ctx.Data["HookType"] = "gogs"
func WebHooksNewPost(c *context.Context, f form.NewWebhook) {
c.Data["Title"] = c.Tr("repo.settings.add_webhook")
c.Data["PageIsSettingsHooks"] = true
c.Data["PageIsSettingsHooksNew"] = true
c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
c.Data["HookType"] = "gogs"
orCtx, err := getOrgRepoCtx(ctx)
orCtx, err := getOrgRepoCtx(c)
if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err)
c.Handle(500, "getOrgRepoCtx", err)
return
}
ctx.Data["BaseLink"] = orCtx.Link
c.Data["BaseLink"] = orCtx.Link
if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
if c.HasError() {
c.HTML(200, orCtx.NewTemplate)
return
}
@ -157,31 +157,31 @@ func WebHooksNewPost(ctx *context.Context, f form.NewWebhook) {
OrgID: orCtx.OrgID,
}
if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err)
c.Handle(500, "UpdateEvent", err)
return
} else if err := models.CreateWebhook(w); err != nil {
ctx.Handle(500, "CreateWebhook", err)
c.Handle(500, "CreateWebhook", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
ctx.Redirect(orCtx.Link + "/settings/hooks")
c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
c.Redirect(orCtx.Link + "/settings/hooks")
}
func SlackHooksNewPost(ctx *context.Context, f form.NewSlackHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
func SlackHooksNewPost(c *context.Context, f form.NewSlackHook) {
c.Data["Title"] = c.Tr("repo.settings")
c.Data["PageIsSettingsHooks"] = true
c.Data["PageIsSettingsHooksNew"] = true
c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
orCtx, err := getOrgRepoCtx(ctx)
orCtx, err := getOrgRepoCtx(c)
if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err)
c.Handle(500, "getOrgRepoCtx", err)
return
}
if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
if c.HasError() {
c.HTML(200, orCtx.NewTemplate)
return
}
@ -192,7 +192,7 @@ func SlackHooksNewPost(ctx *context.Context, f form.NewSlackHook) {
Color: f.Color,
})
if err != nil {
ctx.Handle(500, "Marshal", err)
c.Handle(500, "Marshal", err)
return
}
@ -207,32 +207,32 @@ func SlackHooksNewPost(ctx *context.Context, f form.NewSlackHook) {
OrgID: orCtx.OrgID,
}
if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err)
c.Handle(500, "UpdateEvent", err)
return
} else if err := models.CreateWebhook(w); err != nil {
ctx.Handle(500, "CreateWebhook", err)
c.Handle(500, "CreateWebhook", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
ctx.Redirect(orCtx.Link + "/settings/hooks")
c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
c.Redirect(orCtx.Link + "/settings/hooks")
}
// FIXME: merge logic to Slack
func DiscordHooksNewPost(ctx *context.Context, f form.NewDiscordHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksNew"] = true
ctx.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
func DiscordHooksNewPost(c *context.Context, f form.NewDiscordHook) {
c.Data["Title"] = c.Tr("repo.settings")
c.Data["PageIsSettingsHooks"] = true
c.Data["PageIsSettingsHooksNew"] = true
c.Data["Webhook"] = models.Webhook{HookEvent: &models.HookEvent{}}
orCtx, err := getOrgRepoCtx(ctx)
orCtx, err := getOrgRepoCtx(c)
if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err)
c.Handle(500, "getOrgRepoCtx", err)
return
}
if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
if c.HasError() {
c.HTML(200, orCtx.NewTemplate)
return
}
@ -242,7 +242,7 @@ func DiscordHooksNewPost(ctx *context.Context, f form.NewDiscordHook) {
Color: f.Color,
})
if err != nil {
ctx.Handle(500, "Marshal", err)
c.Handle(500, "Marshal", err)
return
}
@ -257,83 +257,83 @@ func DiscordHooksNewPost(ctx *context.Context, f form.NewDiscordHook) {
OrgID: orCtx.OrgID,
}
if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err)
c.Handle(500, "UpdateEvent", err)
return
} else if err := models.CreateWebhook(w); err != nil {
ctx.Handle(500, "CreateWebhook", err)
c.Handle(500, "CreateWebhook", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
ctx.Redirect(orCtx.Link + "/settings/hooks")
c.Flash.Success(c.Tr("repo.settings.add_hook_success"))
c.Redirect(orCtx.Link + "/settings/hooks")
}
func checkWebhook(ctx *context.Context) (*OrgRepoCtx, *models.Webhook) {
ctx.Data["RequireHighlightJS"] = true
func checkWebhook(c *context.Context) (*OrgRepoCtx, *models.Webhook) {
c.Data["RequireHighlightJS"] = true
orCtx, err := getOrgRepoCtx(ctx)
orCtx, err := getOrgRepoCtx(c)
if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err)
c.Handle(500, "getOrgRepoCtx", err)
return nil, nil
}
ctx.Data["BaseLink"] = orCtx.Link
c.Data["BaseLink"] = orCtx.Link
var w *models.Webhook
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 {
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 {
ctx.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
c.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
return nil, nil
}
switch w.HookTaskType {
case models.SLACK:
ctx.Data["SlackHook"] = w.GetSlackHook()
ctx.Data["HookType"] = "slack"
c.Data["SlackHook"] = w.GetSlackHook()
c.Data["HookType"] = "slack"
case models.DISCORD:
ctx.Data["SlackHook"] = w.GetSlackHook()
ctx.Data["HookType"] = "discord"
c.Data["SlackHook"] = w.GetSlackHook()
c.Data["HookType"] = "discord"
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 {
ctx.Handle(500, "History", err)
c.Handle(500, "History", err)
}
return orCtx, w
}
func WebHooksEdit(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true
func WebHooksEdit(c *context.Context) {
c.Data["Title"] = c.Tr("repo.settings.update_webhook")
c.Data["PageIsSettingsHooks"] = true
c.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx)
if ctx.Written() {
orCtx, w := checkWebhook(c)
if c.Written() {
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) {
ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true
func WebHooksEditPost(c *context.Context, f form.NewWebhook) {
c.Data["Title"] = c.Tr("repo.settings.update_webhook")
c.Data["PageIsSettingsHooks"] = true
c.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx)
if ctx.Written() {
orCtx, w := checkWebhook(c)
if c.Written() {
return
}
ctx.Data["Webhook"] = w
c.Data["Webhook"] = w
if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
if c.HasError() {
c.HTML(200, orCtx.NewTemplate)
return
}
@ -348,30 +348,30 @@ func WebHooksEditPost(ctx *context.Context, f form.NewWebhook) {
w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err)
c.Handle(500, "UpdateEvent", err)
return
} else if err := models.UpdateWebhook(w); err != nil {
ctx.Handle(500, "WebHooksEditPost", err)
c.Handle(500, "WebHooksEditPost", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
}
func SlackHooksEditPost(ctx *context.Context, f form.NewSlackHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true
func SlackHooksEditPost(c *context.Context, f form.NewSlackHook) {
c.Data["Title"] = c.Tr("repo.settings")
c.Data["PageIsSettingsHooks"] = true
c.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx)
if ctx.Written() {
orCtx, w := checkWebhook(c)
if c.Written() {
return
}
ctx.Data["Webhook"] = w
c.Data["Webhook"] = w
if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
if c.HasError() {
c.HTML(200, orCtx.NewTemplate)
return
}
@ -382,7 +382,7 @@ func SlackHooksEditPost(ctx *context.Context, f form.NewSlackHook) {
Color: f.Color,
})
if err != nil {
ctx.Handle(500, "Marshal", err)
c.Handle(500, "Marshal", err)
return
}
@ -391,31 +391,31 @@ func SlackHooksEditPost(ctx *context.Context, f form.NewSlackHook) {
w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err)
c.Handle(500, "UpdateEvent", err)
return
} else if err := models.UpdateWebhook(w); err != nil {
ctx.Handle(500, "UpdateWebhook", err)
c.Handle(500, "UpdateWebhook", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
}
// FIXME: merge logic to Slack
func DiscordHooksEditPost(ctx *context.Context, f form.NewDiscordHook) {
ctx.Data["Title"] = ctx.Tr("repo.settings")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true
func DiscordHooksEditPost(c *context.Context, f form.NewDiscordHook) {
c.Data["Title"] = c.Tr("repo.settings")
c.Data["PageIsSettingsHooks"] = true
c.Data["PageIsSettingsHooksEdit"] = true
orCtx, w := checkWebhook(ctx)
if ctx.Written() {
orCtx, w := checkWebhook(c)
if c.Written() {
return
}
ctx.Data["Webhook"] = w
c.Data["Webhook"] = w
if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate)
if c.HasError() {
c.HTML(200, orCtx.NewTemplate)
return
}
@ -425,7 +425,7 @@ func DiscordHooksEditPost(ctx *context.Context, f form.NewDiscordHook) {
Color: f.Color,
})
if err != nil {
ctx.Handle(500, "Marshal", err)
c.Handle(500, "Marshal", err)
return
}
@ -434,22 +434,22 @@ func DiscordHooksEditPost(ctx *context.Context, f form.NewDiscordHook) {
w.HookEvent = ParseHookEvent(f.Webhook)
w.IsActive = f.Active
if err := w.UpdateEvent(); err != nil {
ctx.Handle(500, "UpdateEvent", err)
c.Handle(500, "UpdateEvent", err)
return
} else if err := models.UpdateWebhook(w); err != nil {
ctx.Handle(500, "UpdateWebhook", err)
c.Handle(500, "UpdateWebhook", err)
return
}
ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID))
c.Flash.Success(c.Tr("repo.settings.update_hook_success"))
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
// Grab latest commit or fake one if it's empty repository.
commit := ctx.Repo.Commit
commit := c.Repo.Commit
if commit == nil {
ghost := models.NewGhostUser()
commit = &git.Commit{
@ -466,7 +466,7 @@ func TestWebhook(ctx *context.Context) {
if err == nil {
authorUsername = author.Name
} else if !errors.IsUserNotExist(err) {
ctx.Handle(500, "GetUserByEmail.(author)", err)
c.Handle(500, "GetUserByEmail.(author)", err)
return
}
@ -474,27 +474,27 @@ func TestWebhook(ctx *context.Context) {
if err == nil {
committerUsername = committer.Name
} else if !errors.IsUserNotExist(err) {
ctx.Handle(500, "GetUserByEmail.(committer)", err)
c.Handle(500, "GetUserByEmail.(committer)", err)
return
}
}
fileStatus, err := commit.FileStatus()
if err != nil {
ctx.Handle(500, "FileStatus", err)
c.Handle(500, "FileStatus", err)
return
}
apiUser := ctx.User.APIFormat()
apiUser := c.User.APIFormat()
p := &api.PushPayload{
Ref: git.BRANCH_PREFIX + ctx.Repo.Repository.DefaultBranch,
Ref: git.BRANCH_PREFIX + c.Repo.Repository.DefaultBranch,
Before: commit.ID.String(),
After: commit.ID.String(),
Commits: []*api.PayloadCommit{
{
ID: commit.ID.String(),
Message: commit.Message(),
URL: ctx.Repo.Repository.HTMLURL() + "/commit/" + commit.ID.String(),
URL: c.Repo.Repository.HTMLURL() + "/commit/" + commit.ID.String(),
Author: &api.PayloadUser{
Name: commit.Author.Name,
Email: commit.Author.Email,
@ -510,49 +510,49 @@ func TestWebhook(ctx *context.Context) {
Modified: fileStatus.Modified,
},
},
Repo: ctx.Repo.Repository.APIFormat(nil),
Repo: c.Repo.Repository.APIFormat(nil),
Pusher: apiUser,
Sender: apiUser,
}
if err := models.TestWebhook(ctx.Repo.Repository, models.HOOK_EVENT_PUSH, p, ctx.ParamsInt64("id")); err != nil {
ctx.Handle(500, "TestWebhook", err)
if err := models.TestWebhook(c.Repo.Repository, models.HOOK_EVENT_PUSH, p, c.ParamsInt64("id")); err != nil {
c.Handle(500, "TestWebhook", err)
} else {
ctx.Flash.Info(ctx.Tr("repo.settings.webhook.test_delivery_success"))
ctx.Status(200)
c.Flash.Info(c.Tr("repo.settings.webhook.test_delivery_success"))
c.Status(200)
}
}
func RedeliveryWebhook(ctx *context.Context) {
webhook, err := models.GetWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
func RedeliveryWebhook(c *context.Context) {
webhook, err := models.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
if err != nil {
ctx.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
c.NotFoundOrServerError("GetWebhookOfRepoByID/GetWebhookByOrgID", errors.IsWebhookNotExist, err)
return
}
hookTask, err := models.GetHookTaskOfWebhookByUUID(webhook.ID, ctx.Query("uuid"))
hookTask, err := models.GetHookTaskOfWebhookByUUID(webhook.ID, c.Query("uuid"))
if err != nil {
ctx.NotFoundOrServerError("GetHookTaskOfWebhookByUUID/GetWebhookByOrgID", errors.IsHookTaskNotExist, err)
c.NotFoundOrServerError("GetHookTaskOfWebhookByUUID/GetWebhookByOrgID", errors.IsHookTaskNotExist, err)
return
}
hookTask.IsDelivered = false
if err = models.UpdateHookTask(hookTask); err != nil {
ctx.Handle(500, "UpdateHookTask", err)
c.Handle(500, "UpdateHookTask", err)
} else {
go models.HookQueue.Add(ctx.Repo.Repository.ID)
ctx.Flash.Info(ctx.Tr("repo.settings.webhook.redelivery_success", hookTask.UUID))
ctx.Status(200)
go models.HookQueue.Add(c.Repo.Repository.ID)
c.Flash.Info(c.Tr("repo.settings.webhook.redelivery_success", hookTask.UUID))
c.Status(200)
}
}
func DeleteWebhook(ctx *context.Context) {
if err := models.DeleteWebhookOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
func DeleteWebhook(c *context.Context) {
if err := models.DeleteWebhookOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
c.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
} else {
ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
c.Flash.Success(c.Tr("repo.settings.webhook_deletion_success"))
}
ctx.JSON(200, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/settings/hooks",
c.JSON(200, map[string]interface{}{
"redirect": c.Repo.RepoLink + "/settings/hooks",
})
}

178
routers/repo/wiki.go

@ -24,14 +24,14 @@ const (
WIKI_PAGES = "repo/wiki/pages"
)
func MustEnableWiki(ctx *context.Context) {
if !ctx.Repo.Repository.EnableWiki {
ctx.Handle(404, "MustEnableWiki", nil)
func MustEnableWiki(c *context.Context) {
if !c.Repo.Repository.EnableWiki {
c.Handle(404, "MustEnableWiki", nil)
return
}
if ctx.Repo.Repository.EnableExternalWiki {
ctx.Redirect(ctx.Repo.Repository.ExternalWikiURL)
if c.Repo.Repository.EnableExternalWiki {
c.Redirect(c.Repo.Repository.ExternalWikiURL)
return
}
}
@ -42,15 +42,15 @@ type PageMeta struct {
Updated time.Time
}
func renderWikiPage(ctx *context.Context, isViewPage bool) (*git.Repository, string) {
wikiRepo, err := git.OpenRepository(ctx.Repo.Repository.WikiPath())
func renderWikiPage(c *context.Context, isViewPage bool) (*git.Repository, string) {
wikiRepo, err := git.OpenRepository(c.Repo.Repository.WikiPath())
if err != nil {
ctx.Handle(500, "OpenRepository", err)
c.Handle(500, "OpenRepository", err)
return nil, ""
}
commit, err := wikiRepo.GetBranchCommit("master")
if err != nil {
ctx.Handle(500, "GetBranchCommit", err)
c.Handle(500, "GetBranchCommit", err)
return nil, ""
}
@ -58,7 +58,7 @@ func renderWikiPage(ctx *context.Context, isViewPage bool) (*git.Repository, str
if isViewPage {
entries, err := commit.ListEntries()
if err != nil {
ctx.Handle(500, "ListEntries", err)
c.Handle(500, "ListEntries", err)
return nil, ""
}
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 {
pageURL = "Home"
}
ctx.Data["PageURL"] = pageURL
c.Data["PageURL"] = pageURL
pageName := models.ToWikiPageName(pageURL)
ctx.Data["old_title"] = pageName
ctx.Data["Title"] = pageName
ctx.Data["title"] = pageName
ctx.Data["RequireHighlightJS"] = true
c.Data["old_title"] = pageName
c.Data["Title"] = pageName
c.Data["title"] = pageName
c.Data["RequireHighlightJS"] = true
blob, err := commit.GetBlobByPath(pageName + ".md")
if err != nil {
if git.IsErrNotExist(err) {
ctx.Redirect(ctx.Repo.RepoLink + "/wiki/_pages")
c.Redirect(c.Repo.RepoLink + "/wiki/_pages")
} else {
ctx.Handle(500, "GetBlobByPath", err)
c.Handle(500, "GetBlobByPath", err)
}
return nil, ""
}
r, err := blob.Data()
if err != nil {
ctx.Handle(500, "Data", err)
c.Handle(500, "Data", err)
return nil, ""
}
data, err := ioutil.ReadAll(r)
if err != nil {
ctx.Handle(500, "ReadAll", err)
c.Handle(500, "ReadAll", err)
return nil, ""
}
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 {
ctx.Data["content"] = string(data)
c.Data["content"] = string(data)
}
return wikiRepo, pageName
}
func Wiki(ctx *context.Context) {
ctx.Data["PageIsWiki"] = true
func Wiki(c *context.Context) {
c.Data["PageIsWiki"] = true
if !ctx.Repo.Repository.HasWiki() {
ctx.Data["Title"] = ctx.Tr("repo.wiki")
ctx.HTML(200, WIKI_START)
if !c.Repo.Repository.HasWiki() {
c.Data["Title"] = c.Tr("repo.wiki")
c.HTML(200, WIKI_START)
return
}
wikiRepo, pageName := renderWikiPage(ctx, true)
if ctx.Written() {
wikiRepo, pageName := renderWikiPage(c, true)
if c.Written() {
return
}
// Get last change information.
lastCommit, err := wikiRepo.GetCommitByPath(pageName + ".md")
if err != nil {
ctx.Handle(500, "GetCommitByPath", err)
c.Handle(500, "GetCommitByPath", err)
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) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.pages")
ctx.Data["PageIsWiki"] = true
func WikiPages(c *context.Context) {
c.Data["Title"] = c.Tr("repo.wiki.pages")
c.Data["PageIsWiki"] = true
if !ctx.Repo.Repository.HasWiki() {
ctx.Redirect(ctx.Repo.RepoLink + "/wiki")
if !c.Repo.Repository.HasWiki() {
c.Redirect(c.Repo.RepoLink + "/wiki")
return
}
wikiRepo, err := git.OpenRepository(ctx.Repo.Repository.WikiPath())
wikiRepo, err := git.OpenRepository(c.Repo.Repository.WikiPath())
if err != nil {
ctx.Handle(500, "OpenRepository", err)
c.Handle(500, "OpenRepository", err)
return
}
commit, err := wikiRepo.GetBranchCommit("master")
if err != nil {
ctx.Handle(500, "GetBranchCommit", err)
c.Handle(500, "GetBranchCommit", err)
return
}
entries, err := commit.ListEntries()
if err != nil {
ctx.Handle(500, "ListEntries", err)
c.Handle(500, "ListEntries", err)
return
}
pages := make([]PageMeta, 0, len(entries))
for i := range entries {
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 {
ctx.Handle(500, "GetCommit", err)
c.ServerError("GetCommitByPath", err)
return
}
name := strings.TrimSuffix(entries[i].Name(), ".md")
pages = append(pages, PageMeta{
Name: 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) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page")
ctx.Data["PageIsWiki"] = true
ctx.Data["RequireSimpleMDE"] = true
func NewWiki(c *context.Context) {
c.Data["Title"] = c.Tr("repo.wiki.new_page")
c.Data["PageIsWiki"] = true
c.Data["RequireSimpleMDE"] = true
if !ctx.Repo.Repository.HasWiki() {
ctx.Data["title"] = "Home"
if !c.Repo.Repository.HasWiki() {
c.Data["title"] = "Home"
}
ctx.HTML(200, WIKI_NEW)
c.HTML(200, WIKI_NEW)
}
func NewWikiPost(ctx *context.Context, f form.NewWiki) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page")
ctx.Data["PageIsWiki"] = true
ctx.Data["RequireSimpleMDE"] = true
func NewWikiPost(c *context.Context, f form.NewWiki) {
c.Data["Title"] = c.Tr("repo.wiki.new_page")
c.Data["PageIsWiki"] = true
c.Data["RequireSimpleMDE"] = true
if ctx.HasError() {
ctx.HTML(200, WIKI_NEW)
if c.HasError() {
c.HTML(200, WIKI_NEW)
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) {
ctx.Data["Err_Title"] = true
ctx.RenderWithErr(ctx.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &f)
c.Data["Err_Title"] = true
c.RenderWithErr(c.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &f)
} else {
ctx.Handle(500, "AddWikiPage", err)
c.Handle(500, "AddWikiPage", err)
}
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) {
ctx.Data["PageIsWiki"] = true
ctx.Data["PageIsWikiEdit"] = true
ctx.Data["RequireSimpleMDE"] = true
func EditWiki(c *context.Context) {
c.Data["PageIsWiki"] = true
c.Data["PageIsWikiEdit"] = true
c.Data["RequireSimpleMDE"] = true
if !ctx.Repo.Repository.HasWiki() {
ctx.Redirect(ctx.Repo.RepoLink + "/wiki")
if !c.Repo.Repository.HasWiki() {
c.Redirect(c.Repo.RepoLink + "/wiki")
return
}
renderWikiPage(ctx, false)
if ctx.Written() {
renderWikiPage(c, false)
if c.Written() {
return
}
ctx.HTML(200, WIKI_NEW)
c.HTML(200, WIKI_NEW)
}
func EditWikiPost(ctx *context.Context, f form.NewWiki) {
ctx.Data["Title"] = ctx.Tr("repo.wiki.new_page")
ctx.Data["PageIsWiki"] = true
ctx.Data["RequireSimpleMDE"] = true
func EditWikiPost(c *context.Context, f form.NewWiki) {
c.Data["Title"] = c.Tr("repo.wiki.new_page")
c.Data["PageIsWiki"] = true
c.Data["RequireSimpleMDE"] = true
if ctx.HasError() {
ctx.HTML(200, WIKI_NEW)
if c.HasError() {
c.HTML(200, WIKI_NEW)
return
}
if err := ctx.Repo.Repository.EditWikiPage(ctx.User, f.OldTitle, f.Title, f.Content, f.Message); err != nil {
ctx.Handle(500, "EditWikiPage", err)
if err := c.Repo.Repository.EditWikiPage(c.User, f.OldTitle, f.Title, f.Content, f.Message); err != nil {
c.Handle(500, "EditWikiPage", err)
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) {
pageURL := ctx.Params(":page")
func DeleteWikiPagePost(c *context.Context) {
pageURL := c.Params(":page")
if len(pageURL) == 0 {
pageURL = "Home"
}
pageName := models.ToWikiPageName(pageURL)
if err := ctx.Repo.Repository.DeleteWikiPage(ctx.User, pageName); err != nil {
ctx.Handle(500, "DeleteWikiPage", err)
if err := c.Repo.Repository.DeleteWikiPage(c.User, pageName); err != nil {
c.Handle(500, "DeleteWikiPage", err)
return
}
ctx.JSON(200, map[string]interface{}{
"redirect": ctx.Repo.RepoLink + "/wiki/",
c.JSON(200, map[string]interface{}{
"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))
}
func SignOut(ctx *context.Context) {
ctx.Session.Delete("uid")
ctx.Session.Delete("uname")
ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
ctx.Redirect(setting.AppSubURL + "/")
func SignOut(c *context.Context) {
c.Session.Delete("uid")
c.Session.Delete("uname")
c.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
c.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
c.Redirect(setting.AppSubURL + "/")
}
func SignUp(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("sign_up")
func SignUp(c *context.Context) {
c.Data["Title"] = c.Tr("sign_up")
ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
if setting.Service.DisableRegistration {
ctx.Data["DisableRegistration"] = true
ctx.HTML(200, SIGNUP)
c.Data["DisableRegistration"] = true
c.HTML(200, SIGNUP)
return
}
ctx.HTML(200, SIGNUP)
c.HTML(200, SIGNUP)
}
func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) {
ctx.Data["Title"] = ctx.Tr("sign_up")
func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
c.Data["Title"] = c.Tr("sign_up")
ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
if setting.Service.DisableRegistration {
ctx.Error(403)
c.Error(403)
return
}
if ctx.HasError() {
ctx.HTML(200, SIGNUP)
if c.HasError() {
c.HTML(200, SIGNUP)
return
}
if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
ctx.Data["Err_Captcha"] = true
ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), SIGNUP, &f)
if setting.Service.EnableCaptcha && !cpt.VerifyReq(c.Req) {
c.Data["Err_Captcha"] = true
c.RenderWithErr(c.Tr("form.captcha_incorrect"), SIGNUP, &f)
return
}
if f.Password != f.Retype {
ctx.Data["Err_Password"] = true
ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &f)
c.Data["Err_Password"] = true
c.RenderWithErr(c.Tr("form.password_not_match"), SIGNUP, &f)
return
}
@ -299,19 +299,19 @@ func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) {
if err := models.CreateUser(u); err != nil {
switch {
case models.IsErrUserAlreadyExist(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SIGNUP, &f)
c.Data["Err_UserName"] = true
c.RenderWithErr(c.Tr("form.username_been_taken"), SIGNUP, &f)
case models.IsErrEmailAlreadyUsed(err):
ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &f)
c.Data["Err_Email"] = true
c.RenderWithErr(c.Tr("form.email_been_used"), SIGNUP, &f)
case models.IsErrNameReserved(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f)
c.Data["Err_UserName"] = true
c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f)
case models.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f)
c.Data["Err_UserName"] = true
c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f)
default:
ctx.Handle(500, "CreateUser", err)
c.Handle(500, "CreateUser", err)
}
return
}
@ -322,53 +322,53 @@ func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) {
u.IsAdmin = true
u.IsActive = true
if err := models.UpdateUser(u); err != nil {
ctx.Handle(500, "UpdateUser", err)
c.Handle(500, "UpdateUser", err)
return
}
}
// Send confirmation email, no need for social account.
if setting.Service.RegisterEmailConfirm && u.ID > 1 {
mailer.SendActivateAccountMail(ctx.Context, models.NewMailerUser(u))
ctx.Data["IsSendRegisterMail"] = true
ctx.Data["Email"] = u.Email
ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
ctx.HTML(200, ACTIVATE)
mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(u))
c.Data["IsSendRegisterMail"] = true
c.Data["Email"] = u.Email
c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
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)
}
return
}
ctx.Redirect(setting.AppSubURL + "/user/login")
c.Redirect(setting.AppSubURL + "/user/login")
}
func Activate(ctx *context.Context) {
code := ctx.Query("code")
func Activate(c *context.Context) {
code := c.Query("code")
if len(code) == 0 {
ctx.Data["IsActivatePage"] = true
if ctx.User.IsActive {
ctx.Error(404)
c.Data["IsActivatePage"] = true
if c.User.IsActive {
c.Error(404)
return
}
// Resend confirmation email.
if setting.Service.RegisterEmailConfirm {
if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
ctx.Data["ResendLimited"] = true
if c.Cache.IsExist("MailResendLimit_" + c.User.LowerName) {
c.Data["ResendLimited"] = true
} else {
ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
mailer.SendActivateAccountMail(ctx.Context, models.NewMailerUser(ctx.User))
c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(c.User))
keyName := "MailResendLimit_" + ctx.User.LowerName
if err := ctx.Cache.Put(keyName, ctx.User.LowerName, 180); err != nil {
keyName := "MailResendLimit_" + c.User.LowerName
if err := c.Cache.Put(keyName, c.User.LowerName, 180); err != nil {
log.Error(2, "Set cache '%s' fail: %v", keyName, err)
}
}
} else {
ctx.Data["ServiceNotEnabled"] = true
c.Data["ServiceNotEnabled"] = true
}
ctx.HTML(200, ACTIVATE)
c.HTML(200, ACTIVATE)
return
}
@ -377,158 +377,158 @@ func Activate(ctx *context.Context) {
user.IsActive = true
var err error
if user.Rands, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err)
c.Handle(500, "UpdateUser", err)
return
}
if err := models.UpdateUser(user); err != nil {
ctx.Handle(500, "UpdateUser", err)
c.Handle(500, "UpdateUser", err)
return
}
log.Trace("User activated: %s", user.Name)
ctx.Session.Set("uid", user.ID)
ctx.Session.Set("uname", user.Name)
ctx.Redirect(setting.AppSubURL + "/")
c.Session.Set("uid", user.ID)
c.Session.Set("uname", user.Name)
c.Redirect(setting.AppSubURL + "/")
return
}
ctx.Data["IsActivateFailed"] = true
ctx.HTML(200, ACTIVATE)
c.Data["IsActivateFailed"] = true
c.HTML(200, ACTIVATE)
}
func ActivateEmail(ctx *context.Context) {
code := ctx.Query("code")
email_string := ctx.Query("email")
func ActivateEmail(c *context.Context) {
code := c.Query("code")
email_string := c.Query("email")
// Verify code.
if email := models.VerifyActiveEmailCode(code, email_string); email != nil {
if err := email.Activate(); err != nil {
ctx.Handle(500, "ActivateEmail", err)
c.Handle(500, "ActivateEmail", err)
}
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
}
func ForgotPasswd(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
func ForgotPasswd(c *context.Context) {
c.Data["Title"] = c.Tr("auth.forgot_password")
if setting.MailService == nil {
ctx.Data["IsResetDisable"] = true
ctx.HTML(200, FORGOT_PASSWORD)
c.Data["IsResetDisable"] = true
c.HTML(200, FORGOT_PASSWORD)
return
}
ctx.Data["IsResetRequest"] = true
ctx.HTML(200, FORGOT_PASSWORD)
c.Data["IsResetRequest"] = true
c.HTML(200, FORGOT_PASSWORD)
}
func ForgotPasswdPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
func ForgotPasswdPost(c *context.Context) {
c.Data["Title"] = c.Tr("auth.forgot_password")
if setting.MailService == nil {
ctx.Handle(403, "ForgotPasswdPost", nil)
c.Handle(403, "ForgotPasswdPost", nil)
return
}
ctx.Data["IsResetRequest"] = true
c.Data["IsResetRequest"] = true
email := ctx.Query("email")
ctx.Data["Email"] = email
email := c.Query("email")
c.Data["Email"] = email
u, err := models.GetUserByEmail(email)
if err != nil {
if errors.IsUserNotExist(err) {
ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
ctx.Data["IsResetSent"] = true
ctx.HTML(200, FORGOT_PASSWORD)
c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
c.Data["IsResetSent"] = true
c.HTML(200, FORGOT_PASSWORD)
return
} else {
ctx.Handle(500, "user.ResetPasswd(check existence)", err)
c.Handle(500, "user.ResetPasswd(check existence)", err)
}
return
}
if !u.IsLocal() {
ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
c.Data["Err_Email"] = true
c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
return
}
if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
ctx.Data["ResendLimited"] = true
ctx.HTML(200, FORGOT_PASSWORD)
if c.Cache.IsExist("MailResendLimit_" + u.LowerName) {
c.Data["ResendLimited"] = true
c.HTML(200, FORGOT_PASSWORD)
return
}
mailer.SendResetPasswordMail(ctx.Context, models.NewMailerUser(u))
if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
mailer.SendResetPasswordMail(c.Context, models.NewMailerUser(u))
if err = c.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
}
ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
ctx.Data["IsResetSent"] = true
ctx.HTML(200, FORGOT_PASSWORD)
c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
c.Data["IsResetSent"] = true
c.HTML(200, FORGOT_PASSWORD)
}
func ResetPasswd(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("auth.reset_password")
func ResetPasswd(c *context.Context) {
c.Data["Title"] = c.Tr("auth.reset_password")
code := ctx.Query("code")
code := c.Query("code")
if len(code) == 0 {
ctx.Error(404)
c.Error(404)
return
}
ctx.Data["Code"] = code
ctx.Data["IsResetForm"] = true
ctx.HTML(200, RESET_PASSWORD)
c.Data["Code"] = code
c.Data["IsResetForm"] = true
c.HTML(200, RESET_PASSWORD)
}
func ResetPasswdPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("auth.reset_password")
func ResetPasswdPost(c *context.Context) {
c.Data["Title"] = c.Tr("auth.reset_password")
code := ctx.Query("code")
code := c.Query("code")
if len(code) == 0 {
ctx.Error(404)
c.Error(404)
return
}
ctx.Data["Code"] = code
c.Data["Code"] = code
if u := models.VerifyUserActiveCode(code); u != nil {
// Validate password length.
passwd := ctx.Query("password")
passwd := c.Query("password")
if len(passwd) < 6 {
ctx.Data["IsResetForm"] = true
ctx.Data["Err_Password"] = true
ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
c.Data["IsResetForm"] = true
c.Data["Err_Password"] = true
c.RenderWithErr(c.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
return
}
u.Passwd = passwd
var err error
if u.Rands, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err)
c.Handle(500, "UpdateUser", err)
return
}
if u.Salt, err = models.GetUserSalt(); err != nil {
ctx.Handle(500, "UpdateUser", err)
c.Handle(500, "UpdateUser", err)
return
}
u.EncodePasswd()
if err := models.UpdateUser(u); err != nil {
ctx.Handle(500, "UpdateUser", err)
c.Handle(500, "UpdateUser", err)
return
}
log.Trace("User password reset: %s", u.Name)
ctx.Redirect(setting.AppSubURL + "/user/login")
c.Redirect(setting.AppSubURL + "/user/login")
return
}
ctx.Data["IsResetFailed"] = true
ctx.HTML(200, RESET_PASSWORD)
c.Data["IsResetFailed"] = true
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.
func getDashboardContextUser(ctx *context.Context) *models.User {
ctxUser := ctx.User
orgName := ctx.Params(":org")
func getDashboardContextUser(c *context.Context) *models.User {
ctxUser := c.User
orgName := c.Params(":org")
if len(orgName) > 0 {
// Organization.
org, err := models.GetUserByName(orgName)
if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return nil
}
ctxUser = org
}
ctx.Data["ContextUser"] = ctxUser
c.Data["ContextUser"] = ctxUser
if err := ctx.User.GetOrganizations(true); err != nil {
ctx.Handle(500, "GetOrganizations", err)
if err := c.User.GetOrganizations(true); err != nil {
c.Handle(500, "GetOrganizations", err)
return nil
}
ctx.Data["Orgs"] = ctx.User.Orgs
c.Data["Orgs"] = c.User.Orgs
return ctxUser
}
@ -52,10 +52,10 @@ func getDashboardContextUser(ctx *context.Context) *models.User {
// retrieveFeeds loads feeds from database by given context 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.
func retrieveFeeds(ctx *context.Context, ctxUser *models.User, userID int64, isProfile bool) {
actions, err := models.GetFeeds(ctxUser, userID, ctx.QueryInt64("after_id"), isProfile)
func retrieveFeeds(c *context.Context, ctxUser *models.User, userID int64, isProfile bool) {
actions, err := models.GetFeeds(ctxUser, userID, c.QueryInt64("after_id"), isProfile)
if err != nil {
ctx.Handle(500, "GetFeeds", err)
c.Handle(500, "GetFeeds", err)
return
}
@ -71,7 +71,7 @@ func retrieveFeeds(ctx *context.Context, ctxUser *models.User, userID int64, isP
if errors.IsUserNotExist(err) {
continue
}
ctx.Handle(500, "GetUserByName", err)
c.Handle(500, "GetUserByName", err)
return
}
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]
feeds = append(feeds, act)
}
ctx.Data["Feeds"] = feeds
c.Data["Feeds"] = feeds
if len(feeds) > 0 {
afterID := feeds[len(feeds)-1].ID
ctx.Data["AfterID"] = afterID
ctx.Header().Set("X-AJAX-URL", fmt.Sprintf("%s?after_id=%d", ctx.Data["Link"], afterID))
c.Data["AfterID"] = afterID
c.Header().Set("X-AJAX-URL", fmt.Sprintf("%s?after_id=%d", c.Data["Link"], afterID))
}
}
func Dashboard(ctx *context.Context) {
ctxUser := getDashboardContextUser(ctx)
if ctx.Written() {
func Dashboard(c *context.Context) {
ctxUser := getDashboardContextUser(c)
if c.Written() {
return
}
retrieveFeeds(ctx, ctxUser, ctx.User.ID, false)
if ctx.Written() {
retrieveFeeds(c, ctxUser, c.User.ID, false)
if c.Written() {
return
}
if ctx.Req.Header.Get("X-AJAX") == "true" {
ctx.HTML(200, NEWS_FEED)
if c.Req.Header.Get("X-AJAX") == "true" {
c.HTML(200, NEWS_FEED)
return
}
ctx.Data["Title"] = ctxUser.DisplayName() + " - " + ctx.Tr("dashboard")
ctx.Data["PageIsDashboard"] = true
ctx.Data["PageIsNews"] = true
c.Data["Title"] = ctxUser.DisplayName() + " - " + c.Tr("dashboard")
c.Data["PageIsDashboard"] = true
c.Data["PageIsNews"] = true
// Only user can have collaborative repositories.
if !ctxUser.IsOrganization() {
collaborateRepos, err := ctx.User.GetAccessibleRepositories(setting.UI.User.RepoPagingNum)
collaborateRepos, err := c.User.GetAccessibleRepositories(setting.UI.User.RepoPagingNum)
if err != nil {
ctx.Handle(500, "GetAccessibleRepositories", err)
c.Handle(500, "GetAccessibleRepositories", err)
return
} else if err = models.RepositoryList(collaborateRepos).LoadAttributes(); err != nil {
ctx.Handle(500, "RepositoryList.LoadAttributes", err)
c.Handle(500, "RepositoryList.LoadAttributes", err)
return
}
ctx.Data["CollaborativeRepos"] = collaborateRepos
c.Data["CollaborativeRepos"] = collaborateRepos
}
var err error
var repos, mirrors []*models.Repository
var repoCount int64
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 {
ctx.Handle(500, "GetUserRepositories", err)
c.Handle(500, "GetUserRepositories", err)
return
}
mirrors, err = ctxUser.GetUserMirrorRepositories(ctx.User.ID)
mirrors, err = ctxUser.GetUserMirrorRepositories(c.User.ID)
if err != nil {
ctx.Handle(500, "GetUserMirrorRepositories", err)
c.Handle(500, "GetUserMirrorRepositories", err)
return
}
} else {
if err = ctxUser.GetRepositories(1, setting.UI.User.RepoPagingNum); err != nil {
ctx.Handle(500, "GetRepositories", err)
c.Handle(500, "GetRepositories", err)
return
}
repos = ctxUser.Repos
@ -146,47 +146,47 @@ func Dashboard(ctx *context.Context) {
mirrors, err = ctxUser.GetMirrorRepositories()
if err != nil {
ctx.Handle(500, "GetMirrorRepositories", err)
c.Handle(500, "GetMirrorRepositories", err)
return
}
}
ctx.Data["Repos"] = repos
ctx.Data["RepoCount"] = repoCount
ctx.Data["MaxShowRepoNum"] = setting.UI.User.RepoPagingNum
c.Data["Repos"] = repos
c.Data["RepoCount"] = repoCount
c.Data["MaxShowRepoNum"] = setting.UI.User.RepoPagingNum
if err := models.MirrorRepositoryList(mirrors).LoadAttributes(); err != nil {
ctx.Handle(500, "MirrorRepositoryList.LoadAttributes", err)
c.Handle(500, "MirrorRepositoryList.LoadAttributes", err)
return
}
ctx.Data["MirrorCount"] = len(mirrors)
ctx.Data["Mirrors"] = mirrors
c.Data["MirrorCount"] = len(mirrors)
c.Data["Mirrors"] = mirrors
ctx.HTML(200, DASHBOARD)
c.HTML(200, DASHBOARD)
}
func Issues(ctx *context.Context) {
isPullList := ctx.Params(":type") == "pulls"
func Issues(c *context.Context) {
isPullList := c.Params(":type") == "pulls"
if isPullList {
ctx.Data["Title"] = ctx.Tr("pull_requests")
ctx.Data["PageIsPulls"] = true
c.Data["Title"] = c.Tr("pull_requests")
c.Data["PageIsPulls"] = true
} else {
ctx.Data["Title"] = ctx.Tr("issues")
ctx.Data["PageIsIssues"] = true
c.Data["Title"] = c.Tr("issues")
c.Data["PageIsIssues"] = true
}
ctxUser := getDashboardContextUser(ctx)
if ctx.Written() {
ctxUser := getDashboardContextUser(c)
if c.Written() {
return
}
var (
sortType = ctx.Query("sort")
sortType = c.Query("sort")
filterMode = models.FILTER_MODE_YOUR_REPOS
)
// Note: Organization does not have view type and filter mode.
if !ctxUser.IsOrganization() {
viewType := ctx.Query("type")
viewType := c.Query("type")
types := []string{
string(models.FILTER_MODE_YOUR_REPOS),
string(models.FILTER_MODE_ASSIGN),
@ -198,13 +198,13 @@ func Issues(ctx *context.Context) {
filterMode = models.FilterMode(viewType)
}
page := ctx.QueryInt("page")
page := c.QueryInt("page")
if page <= 1 {
page = 1
}
repoID := ctx.QueryInt64("repo")
isShowClosed := ctx.Query("state") == "closed"
repoID := c.QueryInt64("repo")
isShowClosed := c.Query("state") == "closed"
// Get repositories.
var (
@ -214,14 +214,14 @@ func Issues(ctx *context.Context) {
showRepos = make([]*models.Repository, 0, 10)
)
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 {
ctx.Handle(500, "GetRepositories", err)
c.Handle(500, "GetRepositories", err)
return
}
} else {
if err := ctxUser.GetRepositories(1, ctx.User.NumRepos); err != nil {
ctx.Handle(500, "GetRepositories", err)
if err := ctxUser.GetRepositories(1, c.User.NumRepos); err != nil {
c.Handle(500, "GetRepositories", err)
return
}
repos = ctxUser.Repos
@ -255,7 +255,7 @@ func Issues(ctx *context.Context) {
if !isPullList {
userRepoIDs, err = models.FilterRepositoryWithIssues(userRepoIDs)
if err != nil {
ctx.Handle(500, "FilterRepositoryWithIssues", err)
c.Handle(500, "FilterRepositoryWithIssues", err)
return
}
}
@ -287,32 +287,32 @@ func Issues(ctx *context.Context) {
issues, err := models.Issues(issueOptions)
if err != nil {
ctx.Handle(500, "Issues", err)
c.Handle(500, "Issues", err)
return
}
if repoID > 0 {
repo, err := models.GetRepositoryByID(repoID)
if err != nil {
ctx.Handle(500, "GetRepositoryByID", fmt.Errorf("[#%d] %v", repoID, err))
c.Handle(500, "GetRepositoryByID", fmt.Errorf("[#%d] %v", repoID, err))
return
}
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
}
// Check if user has access to given repository.
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
}
}
for _, issue := range issues {
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
}
}
@ -326,28 +326,28 @@ func Issues(ctx *context.Context) {
total = int(issueStats.ClosedCount)
}
ctx.Data["Issues"] = issues
ctx.Data["Repos"] = showRepos
ctx.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5)
ctx.Data["IssueStats"] = issueStats
ctx.Data["ViewType"] = string(filterMode)
ctx.Data["SortType"] = sortType
ctx.Data["RepoID"] = repoID
ctx.Data["IsShowClosed"] = isShowClosed
c.Data["Issues"] = issues
c.Data["Repos"] = showRepos
c.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5)
c.Data["IssueStats"] = issueStats
c.Data["ViewType"] = string(filterMode)
c.Data["SortType"] = sortType
c.Data["RepoID"] = repoID
c.Data["IsShowClosed"] = isShowClosed
if isShowClosed {
ctx.Data["State"] = "closed"
c.Data["State"] = "closed"
} else {
ctx.Data["State"] = "open"
c.Data["State"] = "open"
}
ctx.HTML(200, ISSUES)
c.HTML(200, ISSUES)
}
func ShowSSHKeys(ctx *context.Context, uid int64) {
func ShowSSHKeys(c *context.Context, uid int64) {
keys, err := models.ListPublicKeys(uid)
if err != nil {
ctx.Handle(500, "ListPublicKeys", err)
c.Handle(500, "ListPublicKeys", err)
return
}
@ -356,20 +356,20 @@ func ShowSSHKeys(ctx *context.Context, uid int64) {
buf.WriteString(keys[i].OmitEmail())
buf.WriteString("\n")
}
ctx.PlainText(200, buf.Bytes())
c.PlainText(200, buf.Bytes())
}
func showOrgProfile(ctx *context.Context) {
ctx.SetParams(":org", ctx.Params(":username"))
context.HandleOrgAssignment(ctx)
if ctx.Written() {
func showOrgProfile(c *context.Context) {
c.SetParams(":org", c.Params(":username"))
context.HandleOrgAssignment(c)
if c.Written() {
return
}
org := ctx.Org.Organization
ctx.Data["Title"] = org.FullName
org := c.Org.Organization
c.Data["Title"] = org.FullName
page := ctx.QueryInt("page")
page := c.QueryInt("page")
if page <= 0 {
page = 1
}
@ -379,15 +379,15 @@ func showOrgProfile(ctx *context.Context) {
count int64
err error
)
if ctx.IsLogged && !ctx.User.IsAdmin {
repos, count, err = org.GetUserRepositories(ctx.User.ID, page, setting.UI.User.RepoPagingNum)
if c.IsLogged && !c.User.IsAdmin {
repos, count, err = org.GetUserRepositories(c.User.ID, page, setting.UI.User.RepoPagingNum)
if err != nil {
ctx.Handle(500, "GetUserRepositories", err)
c.Handle(500, "GetUserRepositories", err)
return
}
ctx.Data["Repos"] = repos
c.Data["Repos"] = repos
} else {
showPrivate := ctx.IsLogged && ctx.User.IsAdmin
showPrivate := c.IsLogged && c.User.IsAdmin
repos, err = models.GetUserRepositories(&models.UserRepoOptions{
UserID: org.ID,
Private: showPrivate,
@ -395,30 +395,30 @@ func showOrgProfile(ctx *context.Context) {
PageSize: setting.UI.User.RepoPagingNum,
})
if err != nil {
ctx.Handle(500, "GetRepositories", err)
c.Handle(500, "GetRepositories", err)
return
}
ctx.Data["Repos"] = repos
c.Data["Repos"] = repos
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 {
ctx.Handle(500, "GetMembers", err)
c.Handle(500, "GetMembers", err)
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) {
u, err := models.GetUserByEmail(ctx.Query("email"))
func Email2User(c *context.Context) {
u, err := models.GetUserByEmail(c.Query("email"))
if err != nil {
ctx.NotFoundOrServerError("GetUserByEmail", errors.IsUserNotExist, err)
c.NotFoundOrServerError("GetUserByEmail", errors.IsUserNotExist, err)
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"
)
func GetUserByName(ctx *context.Context, name string) *models.User {
func GetUserByName(c *context.Context, name string) *models.User {
user, err := models.GetUserByName(name)
if err != nil {
ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
return nil
}
return user
}
// GetUserByParams returns user whose name is presented in URL paramenter.
func GetUserByParams(ctx *context.Context) *models.User {
return GetUserByName(ctx, ctx.Params(":username"))
func GetUserByParams(c *context.Context) *models.User {
return GetUserByName(c, c.Params(":username"))
}
func Profile(ctx *context.Context) {
uname := ctx.Params(":username")
func Profile(c *context.Context) {
uname := c.Params(":username")
// Special handle for FireFox requests 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
} else if strings.HasSuffix(uname, ".png") {
ctx.Error(404)
c.Error(404)
return
}
@ -53,117 +53,117 @@ func Profile(ctx *context.Context) {
isShowKeys = true
}
ctxUser := GetUserByName(ctx, strings.TrimSuffix(uname, ".keys"))
if ctx.Written() {
ctxUser := GetUserByName(c, strings.TrimSuffix(uname, ".keys"))
if c.Written() {
return
}
// Show SSH keys.
if isShowKeys {
ShowSSHKeys(ctx, ctxUser.ID)
ShowSSHKeys(c, ctxUser.ID)
return
}
if ctxUser.IsOrganization() {
showOrgProfile(ctx)
showOrgProfile(c)
return
}
ctx.Data["Title"] = ctxUser.DisplayName()
ctx.Data["PageIsUserProfile"] = true
ctx.Data["Owner"] = ctxUser
c.Data["Title"] = ctxUser.DisplayName()
c.Data["PageIsUserProfile"] = true
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 {
ctx.Handle(500, "GetOrgsByUserIDDesc", err)
c.Handle(500, "GetOrgsByUserIDDesc", err)
return
}
ctx.Data["Orgs"] = orgs
c.Data["Orgs"] = orgs
tab := ctx.Query("tab")
ctx.Data["TabName"] = tab
tab := c.Query("tab")
c.Data["TabName"] = tab
switch tab {
case "activity":
retrieveFeeds(ctx, ctxUser, -1, true)
if ctx.Written() {
retrieveFeeds(c, ctxUser, -1, true)
if c.Written() {
return
}
default:
page := ctx.QueryInt("page")
page := c.QueryInt("page")
if page <= 0 {
page = 1
}
showPrivate := ctx.IsLogged && (ctxUser.ID == ctx.User.ID || ctx.User.IsAdmin)
ctx.Data["Repos"], err = models.GetUserRepositories(&models.UserRepoOptions{
showPrivate := c.IsLogged && (ctxUser.ID == c.User.ID || c.User.IsAdmin)
c.Data["Repos"], err = models.GetUserRepositories(&models.UserRepoOptions{
UserID: ctxUser.ID,
Private: showPrivate,
Page: page,
PageSize: setting.UI.User.RepoPagingNum,
})
if err != nil {
ctx.Handle(500, "GetRepositories", err)
c.Handle(500, "GetRepositories", err)
return
}
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) {
u := GetUserByParams(ctx)
if ctx.Written() {
func Followers(c *context.Context) {
u := GetUserByParams(c)
if c.Written() {
return
}
ctx.Data["Title"] = u.DisplayName()
ctx.Data["CardsTitle"] = ctx.Tr("user.followers")
ctx.Data["PageIsFollowers"] = true
ctx.Data["Owner"] = u
repo.RenderUserCards(ctx, u.NumFollowers, u.GetFollowers, FOLLOWERS)
c.Data["Title"] = u.DisplayName()
c.Data["CardsTitle"] = c.Tr("user.followers")
c.Data["PageIsFollowers"] = true
c.Data["Owner"] = u
repo.RenderUserCards(c, u.NumFollowers, u.GetFollowers, FOLLOWERS)
}
func Following(ctx *context.Context) {
u := GetUserByParams(ctx)
if ctx.Written() {
func Following(c *context.Context) {
u := GetUserByParams(c)
if c.Written() {
return
}
ctx.Data["Title"] = u.DisplayName()
ctx.Data["CardsTitle"] = ctx.Tr("user.following")
ctx.Data["PageIsFollowing"] = true
ctx.Data["Owner"] = u
repo.RenderUserCards(ctx, u.NumFollowing, u.GetFollowing, FOLLOWERS)
c.Data["Title"] = u.DisplayName()
c.Data["CardsTitle"] = c.Tr("user.following")
c.Data["PageIsFollowing"] = true
c.Data["Owner"] = u
repo.RenderUserCards(c, u.NumFollowing, u.GetFollowing, FOLLOWERS)
}
func Stars(ctx *context.Context) {
func Stars(c *context.Context) {
}
func Action(ctx *context.Context) {
u := GetUserByParams(ctx)
if ctx.Written() {
func Action(c *context.Context) {
u := GetUserByParams(c)
if c.Written() {
return
}
var err error
switch ctx.Params(":action") {
switch c.Params(":action") {
case "follow":
err = models.FollowUser(ctx.User.ID, u.ID)
err = models.FollowUser(c.User.ID, u.ID)
case "unfollow":
err = models.UnfollowUser(ctx.User.ID, u.ID)
err = models.UnfollowUser(c.User.ID, u.ID)
}
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
}
redirectTo := ctx.Query("redirect_to")
redirectTo := c.Query("redirect_to")
if len(redirectTo) == 0 {
redirectTo = u.HomeLink()
}
ctx.Redirect(redirectTo)
c.Redirect(redirectTo)
}

Loading…
Cancel
Save