repo.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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(c *context.Context) {
  25. if c.Repo.Repository.IsBare {
  26. c.Handle(404, "MustBeNotBare", nil)
  27. }
  28. }
  29. func checkContextUser(c *context.Context, uid int64) *models.User {
  30. orgs, err := models.GetOwnedOrgsByUserIDDesc(c.User.ID, "updated_unix")
  31. if err != nil {
  32. c.Handle(500, "GetOwnedOrgsByUserIDDesc", err)
  33. return nil
  34. }
  35. c.Data["Orgs"] = orgs
  36. // Not equal means current user is an organization.
  37. if uid == c.User.ID || uid == 0 {
  38. return c.User
  39. }
  40. org, err := models.GetUserByID(uid)
  41. if errors.IsUserNotExist(err) {
  42. return c.User
  43. }
  44. if err != nil {
  45. c.Handle(500, "GetUserByID", fmt.Errorf("[%d]: %v", uid, err))
  46. return nil
  47. }
  48. // Check ownership of organization.
  49. if !org.IsOrganization() || !(c.User.IsAdmin || org.IsOwnedBy(c.User.ID)) {
  50. c.Error(403)
  51. return nil
  52. }
  53. return org
  54. }
  55. func Create(c *context.Context) {
  56. c.Data["Title"] = c.Tr("new_repo")
  57. // Give default value for template to render.
  58. c.Data["Gitignores"] = models.Gitignores
  59. c.Data["Licenses"] = models.Licenses
  60. c.Data["Readmes"] = models.Readmes
  61. c.Data["readme"] = "Default"
  62. c.Data["private"] = c.User.LastRepoVisibility
  63. c.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  64. ctxUser := checkContextUser(c, c.QueryInt64("org"))
  65. if c.Written() {
  66. return
  67. }
  68. c.Data["ContextUser"] = ctxUser
  69. c.HTML(200, CREATE)
  70. }
  71. func handleCreateError(c *context.Context, owner *models.User, err error, name, tpl string, form interface{}) {
  72. switch {
  73. case errors.IsReachLimitOfRepo(err):
  74. c.RenderWithErr(c.Tr("repo.form.reach_limit_of_creation", owner.RepoCreationNum()), tpl, form)
  75. case models.IsErrRepoAlreadyExist(err):
  76. c.Data["Err_RepoName"] = true
  77. c.RenderWithErr(c.Tr("form.repo_name_been_taken"), tpl, form)
  78. case models.IsErrNameReserved(err):
  79. c.Data["Err_RepoName"] = true
  80. c.RenderWithErr(c.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
  81. case models.IsErrNamePatternNotAllowed(err):
  82. c.Data["Err_RepoName"] = true
  83. c.RenderWithErr(c.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
  84. default:
  85. c.Handle(500, name, err)
  86. }
  87. }
  88. func CreatePost(c *context.Context, f form.CreateRepo) {
  89. c.Data["Title"] = c.Tr("new_repo")
  90. c.Data["Gitignores"] = models.Gitignores
  91. c.Data["Licenses"] = models.Licenses
  92. c.Data["Readmes"] = models.Readmes
  93. ctxUser := checkContextUser(c, f.UserID)
  94. if c.Written() {
  95. return
  96. }
  97. c.Data["ContextUser"] = ctxUser
  98. if c.HasError() {
  99. c.HTML(200, CREATE)
  100. return
  101. }
  102. repo, err := models.CreateRepository(c.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. c.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(c, ctxUser, err, "CreatePost", CREATE, &f)
  122. }
  123. func Migrate(c *context.Context) {
  124. c.Data["Title"] = c.Tr("new_migrate")
  125. c.Data["private"] = c.User.LastRepoVisibility
  126. c.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  127. c.Data["mirror"] = c.Query("mirror") == "1"
  128. ctxUser := checkContextUser(c, c.QueryInt64("org"))
  129. if c.Written() {
  130. return
  131. }
  132. c.Data["ContextUser"] = ctxUser
  133. c.HTML(200, MIGRATE)
  134. }
  135. func MigratePost(c *context.Context, f form.MigrateRepo) {
  136. c.Data["Title"] = c.Tr("new_migrate")
  137. ctxUser := checkContextUser(c, f.Uid)
  138. if c.Written() {
  139. return
  140. }
  141. c.Data["ContextUser"] = ctxUser
  142. if c.HasError() {
  143. c.HTML(200, MIGRATE)
  144. return
  145. }
  146. remoteAddr, err := f.ParseRemoteAddr(c.User)
  147. if err != nil {
  148. if models.IsErrInvalidCloneAddr(err) {
  149. c.Data["Err_CloneAddr"] = true
  150. addrErr := err.(models.ErrInvalidCloneAddr)
  151. switch {
  152. case addrErr.IsURLError:
  153. c.RenderWithErr(c.Tr("form.url_error"), MIGRATE, &f)
  154. case addrErr.IsPermissionDenied:
  155. c.RenderWithErr(c.Tr("repo.migrate.permission_denied"), MIGRATE, &f)
  156. case addrErr.IsInvalidPath:
  157. c.RenderWithErr(c.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f)
  158. default:
  159. c.Handle(500, "Unknown error", err)
  160. }
  161. } else {
  162. c.Handle(500, "ParseRemoteAddr", err)
  163. }
  164. return
  165. }
  166. repo, err := models.MigrateRepository(c.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. c.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. c.Data["Err_Auth"] = true
  186. c.RenderWithErr(c.Tr("form.auth_failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
  187. return
  188. } else if strings.Contains(err.Error(), "fatal:") {
  189. c.Data["Err_CloneAddr"] = true
  190. c.RenderWithErr(c.Tr("repo.migrate.failed", models.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f)
  191. return
  192. }
  193. handleCreateError(c, ctxUser, err, "MigratePost", MIGRATE, &f)
  194. }
  195. func Action(c *context.Context) {
  196. var err error
  197. switch c.Params(":action") {
  198. case "watch":
  199. err = models.WatchRepo(c.User.ID, c.Repo.Repository.ID, true)
  200. case "unwatch":
  201. err = models.WatchRepo(c.User.ID, c.Repo.Repository.ID, false)
  202. case "star":
  203. err = models.StarRepo(c.User.ID, c.Repo.Repository.ID, true)
  204. case "unstar":
  205. err = models.StarRepo(c.User.ID, c.Repo.Repository.ID, false)
  206. case "desc": // FIXME: this is not used
  207. if !c.Repo.IsOwner() {
  208. c.Error(404)
  209. return
  210. }
  211. c.Repo.Repository.Description = c.Query("desc")
  212. c.Repo.Repository.Website = c.Query("site")
  213. err = models.UpdateRepository(c.Repo.Repository, false)
  214. }
  215. if err != nil {
  216. c.Handle(500, fmt.Sprintf("Action (%s)", c.Params(":action")), err)
  217. return
  218. }
  219. redirectTo := c.Query("redirect_to")
  220. if len(redirectTo) == 0 {
  221. redirectTo = c.Repo.RepoLink
  222. }
  223. c.Redirect(redirectTo)
  224. }
  225. func Download(c *context.Context) {
  226. var (
  227. uri = c.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(c.Repo.GitRepo.Path, "archives/zip")
  237. archiveType = git.ZIP
  238. case strings.HasSuffix(uri, ".tar.gz"):
  239. ext = ".tar.gz"
  240. archivePath = path.Join(c.Repo.GitRepo.Path, "archives/targz")
  241. archiveType = git.TARGZ
  242. default:
  243. log.Trace("Unknown format: %s", uri)
  244. c.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. c.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 := c.Repo.GitRepo
  260. if gitRepo.IsBranchExist(refName) {
  261. commit, err = gitRepo.GetBranchCommit(refName)
  262. if err != nil {
  263. c.Handle(500, "GetBranchCommit", err)
  264. return
  265. }
  266. } else if gitRepo.IsTagExist(refName) {
  267. commit, err = gitRepo.GetTagCommit(refName)
  268. if err != nil {
  269. c.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. c.NotFound()
  276. return
  277. }
  278. } else {
  279. c.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. c.Handle(500, "Download -> CreateArchive "+archivePath, err)
  286. return
  287. }
  288. }
  289. c.ServeFile(archivePath, c.Repo.Repository.Name+"-"+refName+ext)
  290. }