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