repo.go 8.8 KB

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