repo.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "fmt"
  7. "os"
  8. "path"
  9. "strings"
  10. "github.com/Unknwon/com"
  11. "github.com/gogits/git-module"
  12. "github.com/gogits/gogs/models"
  13. "github.com/gogits/gogs/modules/auth"
  14. "github.com/gogits/gogs/modules/base"
  15. "github.com/gogits/gogs/modules/log"
  16. "github.com/gogits/gogs/modules/middleware"
  17. "github.com/gogits/gogs/modules/setting"
  18. )
  19. const (
  20. CREATE base.TplName = "repo/create"
  21. MIGRATE base.TplName = "repo/migrate"
  22. )
  23. func checkContextUser(ctx *middleware.Context, uid int64) *models.User {
  24. orgs, err := models.GetOwnedOrgsByUserIDDesc(ctx.User.Id, "updated")
  25. if err != nil {
  26. ctx.Handle(500, "GetOwnedOrgsByUserIDDesc", err)
  27. return nil
  28. }
  29. ctx.Data["Orgs"] = orgs
  30. // Not equal means current user is an organization.
  31. if uid == ctx.User.Id || uid == 0 {
  32. return ctx.User
  33. }
  34. org, err := models.GetUserByID(uid)
  35. if models.IsErrUserNotExist(err) {
  36. return ctx.User
  37. }
  38. if err != nil {
  39. ctx.Handle(500, "GetUserByID", fmt.Errorf("[%d]: %v", uid, err))
  40. return nil
  41. }
  42. // Check ownership of organization.
  43. if !org.IsOrganization() || !org.IsOwnedBy(ctx.User.Id) {
  44. ctx.Error(403)
  45. return nil
  46. }
  47. return org
  48. }
  49. func Create(ctx *middleware.Context) {
  50. ctx.Data["Title"] = ctx.Tr("new_repo")
  51. // Give default value for template to render.
  52. ctx.Data["Gitignores"] = models.Gitignores
  53. ctx.Data["Licenses"] = models.Licenses
  54. ctx.Data["Readmes"] = models.Readmes
  55. ctx.Data["readme"] = "Default"
  56. ctx.Data["private"] = ctx.User.LastRepoVisibility
  57. ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  58. ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
  59. if ctx.Written() {
  60. return
  61. }
  62. ctx.Data["ContextUser"] = ctxUser
  63. ctx.HTML(200, CREATE)
  64. }
  65. func handleCreateError(ctx *middleware.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) {
  66. switch {
  67. case models.IsErrReachLimitOfRepo(err):
  68. ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_creation", owner.RepoCreationNum()), tpl, form)
  69. case models.IsErrRepoAlreadyExist(err):
  70. ctx.Data["Err_RepoName"] = true
  71. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form)
  72. case models.IsErrNameReserved(err):
  73. ctx.Data["Err_RepoName"] = true
  74. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
  75. case models.IsErrNamePatternNotAllowed(err):
  76. ctx.Data["Err_RepoName"] = true
  77. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
  78. default:
  79. ctx.Handle(500, name, err)
  80. }
  81. }
  82. func CreatePost(ctx *middleware.Context, form auth.CreateRepoForm) {
  83. ctx.Data["Title"] = ctx.Tr("new_repo")
  84. ctx.Data["Gitignores"] = models.Gitignores
  85. ctx.Data["Licenses"] = models.Licenses
  86. ctx.Data["Readmes"] = models.Readmes
  87. ctxUser := checkContextUser(ctx, form.Uid)
  88. if ctx.Written() {
  89. return
  90. }
  91. ctx.Data["ContextUser"] = ctxUser
  92. if ctx.HasError() {
  93. ctx.HTML(200, CREATE)
  94. return
  95. }
  96. repo, err := models.CreateRepository(ctxUser, models.CreateRepoOptions{
  97. Name: form.RepoName,
  98. Description: form.Description,
  99. Gitignores: form.Gitignores,
  100. License: form.License,
  101. Readme: form.Readme,
  102. IsPrivate: form.Private || setting.Repository.ForcePrivate,
  103. AutoInit: form.AutoInit,
  104. })
  105. if err == nil {
  106. log.Trace("Repository created[%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
  107. ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + repo.Name)
  108. return
  109. }
  110. if repo != nil {
  111. if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil {
  112. log.Error(4, "DeleteRepository: %v", errDelete)
  113. }
  114. }
  115. handleCreateError(ctx, ctxUser, err, "CreatePost", CREATE, &form)
  116. }
  117. func Migrate(ctx *middleware.Context) {
  118. ctx.Data["Title"] = ctx.Tr("new_migrate")
  119. ctx.Data["private"] = ctx.User.LastRepoVisibility
  120. ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  121. ctx.Data["mirror"] = ctx.Query("mirror") == "1"
  122. ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
  123. if ctx.Written() {
  124. return
  125. }
  126. ctx.Data["ContextUser"] = ctxUser
  127. ctx.HTML(200, MIGRATE)
  128. }
  129. func MigratePost(ctx *middleware.Context, form auth.MigrateRepoForm) {
  130. ctx.Data["Title"] = ctx.Tr("new_migrate")
  131. ctxUser := checkContextUser(ctx, form.Uid)
  132. if ctx.Written() {
  133. return
  134. }
  135. ctx.Data["ContextUser"] = ctxUser
  136. if ctx.HasError() {
  137. ctx.HTML(200, MIGRATE)
  138. return
  139. }
  140. remoteAddr, err := form.ParseRemoteAddr(ctx.User)
  141. if err != nil {
  142. if models.IsErrInvalidCloneAddr(err) {
  143. ctx.Data["Err_CloneAddr"] = true
  144. addrErr := err.(models.ErrInvalidCloneAddr)
  145. switch {
  146. case addrErr.IsURLError:
  147. ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &form)
  148. case addrErr.IsPermissionDenied:
  149. ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), MIGRATE, &form)
  150. case addrErr.IsInvalidPath:
  151. ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &form)
  152. default:
  153. ctx.Handle(500, "Unknown error", err)
  154. }
  155. } else {
  156. ctx.Handle(500, "ParseRemoteAddr", err)
  157. }
  158. return
  159. }
  160. repo, err := models.MigrateRepository(ctxUser, models.MigrateRepoOptions{
  161. Name: form.RepoName,
  162. Description: form.Description,
  163. IsPrivate: form.Private || setting.Repository.ForcePrivate,
  164. IsMirror: form.Mirror,
  165. RemoteAddr: remoteAddr,
  166. })
  167. if err == nil {
  168. log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, form.RepoName)
  169. ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + form.RepoName)
  170. return
  171. }
  172. if repo != nil {
  173. if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil {
  174. log.Error(4, "DeleteRepository: %v", errDelete)
  175. }
  176. }
  177. if strings.Contains(err.Error(), "Authentication failed") ||
  178. strings.Contains(err.Error(), "could not read Username") {
  179. ctx.Data["Err_Auth"] = true
  180. ctx.RenderWithErr(ctx.Tr("form.auth_failed", models.HandleCloneUserCredentials(err.Error(), true)), MIGRATE, &form)
  181. return
  182. } else if strings.Contains(err.Error(), "fatal:") {
  183. ctx.Data["Err_CloneAddr"] = true
  184. ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", models.HandleCloneUserCredentials(err.Error(), true)), MIGRATE, &form)
  185. return
  186. }
  187. handleCreateError(ctx, ctxUser, err, "MigratePost", MIGRATE, &form)
  188. }
  189. func Action(ctx *middleware.Context) {
  190. var err error
  191. switch ctx.Params(":action") {
  192. case "watch":
  193. err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.ID, true)
  194. case "unwatch":
  195. err = models.WatchRepo(ctx.User.Id, ctx.Repo.Repository.ID, false)
  196. case "star":
  197. err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.ID, true)
  198. case "unstar":
  199. err = models.StarRepo(ctx.User.Id, ctx.Repo.Repository.ID, false)
  200. case "desc":
  201. if !ctx.Repo.IsOwner() {
  202. ctx.Error(404)
  203. return
  204. }
  205. ctx.Repo.Repository.Description = ctx.Query("desc")
  206. ctx.Repo.Repository.Website = ctx.Query("site")
  207. err = models.UpdateRepository(ctx.Repo.Repository, false)
  208. }
  209. if err != nil {
  210. ctx.Handle(500, fmt.Sprintf("Action (%s)", ctx.Params(":action")), err)
  211. return
  212. }
  213. redirectTo := ctx.Query("redirect_to")
  214. if len(redirectTo) == 0 {
  215. redirectTo = ctx.Repo.RepoLink
  216. }
  217. ctx.Redirect(redirectTo)
  218. }
  219. func Download(ctx *middleware.Context) {
  220. var (
  221. uri = ctx.Params("*")
  222. refName string
  223. ext string
  224. archivePath string
  225. archiveType git.ArchiveType
  226. )
  227. switch {
  228. case strings.HasSuffix(uri, ".zip"):
  229. ext = ".zip"
  230. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/zip")
  231. archiveType = git.ZIP
  232. case strings.HasSuffix(uri, ".tar.gz"):
  233. ext = ".tar.gz"
  234. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/targz")
  235. archiveType = git.TARGZ
  236. default:
  237. log.Trace("Unknown format: %s", uri)
  238. ctx.Error(404)
  239. return
  240. }
  241. refName = strings.TrimSuffix(uri, ext)
  242. if !com.IsDir(archivePath) {
  243. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  244. ctx.Handle(500, "Download -> os.MkdirAll(archivePath)", err)
  245. return
  246. }
  247. }
  248. // Get corresponding commit.
  249. var (
  250. commit *git.Commit
  251. err error
  252. )
  253. gitRepo := ctx.Repo.GitRepo
  254. if gitRepo.IsBranchExist(refName) {
  255. commit, err = gitRepo.GetBranchCommit(refName)
  256. if err != nil {
  257. ctx.Handle(500, "GetBranchCommit", err)
  258. return
  259. }
  260. } else if gitRepo.IsTagExist(refName) {
  261. commit, err = gitRepo.GetTagCommit(refName)
  262. if err != nil {
  263. ctx.Handle(500, "GetTagCommit", err)
  264. return
  265. }
  266. } else if len(refName) == 40 {
  267. commit, err = gitRepo.GetCommit(refName)
  268. if err != nil {
  269. ctx.Handle(404, "GetCommit", nil)
  270. return
  271. }
  272. } else {
  273. ctx.Handle(404, "Download", nil)
  274. return
  275. }
  276. archivePath = path.Join(archivePath, base.ShortSha(commit.ID.String())+ext)
  277. if !com.IsFile(archivePath) {
  278. if err := commit.CreateArchive(archivePath, archiveType); err != nil {
  279. ctx.Handle(500, "Download -> CreateArchive "+archivePath, err)
  280. return
  281. }
  282. }
  283. ctx.ServeFile(archivePath, ctx.Repo.Repository.Name+"-"+base.ShortSha(commit.ID.String())+ext)
  284. }