You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

421 lines
11 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
  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. "code.gitea.io/git"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/auth"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/util"
  19. )
  20. const (
  21. tplCreate base.TplName = "repo/create"
  22. tplMigrate base.TplName = "repo/migrate"
  23. )
  24. // MustBeNotEmpty render when a repo is a empty git dir
  25. func MustBeNotEmpty(ctx *context.Context) {
  26. if ctx.Repo.Repository.IsEmpty {
  27. ctx.NotFound("MustBeNotEmpty", nil)
  28. }
  29. }
  30. // MustBeEditable check that repo can be edited
  31. func MustBeEditable(ctx *context.Context) {
  32. if !ctx.Repo.Repository.CanEnableEditor() || ctx.Repo.IsViewCommit {
  33. ctx.NotFound("", nil)
  34. return
  35. }
  36. }
  37. // MustBeAbleToUpload check that repo can be uploaded to
  38. func MustBeAbleToUpload(ctx *context.Context) {
  39. if !setting.Repository.Upload.Enabled {
  40. ctx.NotFound("", nil)
  41. }
  42. }
  43. func checkContextUser(ctx *context.Context, uid int64) *models.User {
  44. orgs, err := models.GetOwnedOrgsByUserIDDesc(ctx.User.ID, "updated_unix")
  45. if err != nil {
  46. ctx.ServerError("GetOwnedOrgsByUserIDDesc", err)
  47. return nil
  48. }
  49. ctx.Data["Orgs"] = orgs
  50. // Not equal means current user is an organization.
  51. if uid == ctx.User.ID || uid == 0 {
  52. return ctx.User
  53. }
  54. org, err := models.GetUserByID(uid)
  55. if models.IsErrUserNotExist(err) {
  56. return ctx.User
  57. }
  58. if err != nil {
  59. ctx.ServerError("GetUserByID", fmt.Errorf("[%d]: %v", uid, err))
  60. return nil
  61. }
  62. // Check ownership of organization.
  63. if !org.IsOrganization() {
  64. ctx.Error(403)
  65. return nil
  66. }
  67. if !ctx.User.IsAdmin {
  68. isOwner, err := org.IsOwnedBy(ctx.User.ID)
  69. if err != nil {
  70. ctx.ServerError("IsOwnedBy", err)
  71. return nil
  72. } else if !isOwner {
  73. ctx.Error(403)
  74. return nil
  75. }
  76. }
  77. return org
  78. }
  79. func getRepoPrivate(ctx *context.Context) bool {
  80. switch strings.ToLower(setting.Repository.DefaultPrivate) {
  81. case setting.RepoCreatingLastUserVisibility:
  82. return ctx.User.LastRepoVisibility
  83. case setting.RepoCreatingPrivate:
  84. return true
  85. case setting.RepoCreatingPublic:
  86. return false
  87. default:
  88. return ctx.User.LastRepoVisibility
  89. }
  90. }
  91. // Create render creating repository page
  92. func Create(ctx *context.Context) {
  93. if !ctx.User.CanCreateRepo() {
  94. ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_creation", ctx.User.MaxCreationLimit()), tplCreate, nil)
  95. }
  96. ctx.Data["Title"] = ctx.Tr("new_repo")
  97. // Give default value for template to render.
  98. ctx.Data["Gitignores"] = models.Gitignores
  99. ctx.Data["Licenses"] = models.Licenses
  100. ctx.Data["Readmes"] = models.Readmes
  101. ctx.Data["readme"] = "Default"
  102. ctx.Data["private"] = getRepoPrivate(ctx)
  103. ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  104. ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
  105. if ctx.Written() {
  106. return
  107. }
  108. ctx.Data["ContextUser"] = ctxUser
  109. ctx.HTML(200, tplCreate)
  110. }
  111. func handleCreateError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) {
  112. switch {
  113. case models.IsErrReachLimitOfRepo(err):
  114. ctx.RenderWithErr(ctx.Tr("repo.form.reach_limit_of_creation", owner.MaxCreationLimit()), tpl, form)
  115. case models.IsErrRepoAlreadyExist(err):
  116. ctx.Data["Err_RepoName"] = true
  117. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tpl, form)
  118. case models.IsErrNameReserved(err):
  119. ctx.Data["Err_RepoName"] = true
  120. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tpl, form)
  121. case models.IsErrNamePatternNotAllowed(err):
  122. ctx.Data["Err_RepoName"] = true
  123. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tpl, form)
  124. default:
  125. ctx.ServerError(name, err)
  126. }
  127. }
  128. // CreatePost response for creating repository
  129. func CreatePost(ctx *context.Context, form auth.CreateRepoForm) {
  130. ctx.Data["Title"] = ctx.Tr("new_repo")
  131. ctx.Data["Gitignores"] = models.Gitignores
  132. ctx.Data["Licenses"] = models.Licenses
  133. ctx.Data["Readmes"] = models.Readmes
  134. ctxUser := checkContextUser(ctx, form.UID)
  135. if ctx.Written() {
  136. return
  137. }
  138. ctx.Data["ContextUser"] = ctxUser
  139. if ctx.HasError() {
  140. ctx.HTML(200, tplCreate)
  141. return
  142. }
  143. repo, err := models.CreateRepository(ctx.User, ctxUser, models.CreateRepoOptions{
  144. Name: form.RepoName,
  145. Description: form.Description,
  146. Gitignores: form.Gitignores,
  147. License: form.License,
  148. Readme: form.Readme,
  149. IsPrivate: form.Private || setting.Repository.ForcePrivate,
  150. AutoInit: form.AutoInit,
  151. })
  152. if err == nil {
  153. log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name)
  154. ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
  155. return
  156. }
  157. if repo != nil {
  158. if errDelete := models.DeleteRepository(ctx.User, ctxUser.ID, repo.ID); errDelete != nil {
  159. log.Error(4, "DeleteRepository: %v", errDelete)
  160. }
  161. }
  162. handleCreateError(ctx, ctxUser, err, "CreatePost", tplCreate, &form)
  163. }
  164. // Migrate render migration of repository page
  165. func Migrate(ctx *context.Context) {
  166. ctx.Data["Title"] = ctx.Tr("new_migrate")
  167. ctx.Data["private"] = getRepoPrivate(ctx)
  168. ctx.Data["IsForcedPrivate"] = setting.Repository.ForcePrivate
  169. ctx.Data["mirror"] = ctx.Query("mirror") == "1"
  170. ctx.Data["LFSActive"] = setting.LFS.StartServer
  171. ctxUser := checkContextUser(ctx, ctx.QueryInt64("org"))
  172. if ctx.Written() {
  173. return
  174. }
  175. ctx.Data["ContextUser"] = ctxUser
  176. ctx.HTML(200, tplMigrate)
  177. }
  178. // MigratePost response for migrating from external git repository
  179. func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) {
  180. ctx.Data["Title"] = ctx.Tr("new_migrate")
  181. ctxUser := checkContextUser(ctx, form.UID)
  182. if ctx.Written() {
  183. return
  184. }
  185. ctx.Data["ContextUser"] = ctxUser
  186. if ctx.HasError() {
  187. ctx.HTML(200, tplMigrate)
  188. return
  189. }
  190. remoteAddr, err := form.ParseRemoteAddr(ctx.User)
  191. if err != nil {
  192. if models.IsErrInvalidCloneAddr(err) {
  193. ctx.Data["Err_CloneAddr"] = true
  194. addrErr := err.(models.ErrInvalidCloneAddr)
  195. switch {
  196. case addrErr.IsURLError:
  197. ctx.RenderWithErr(ctx.Tr("form.url_error"), tplMigrate, &form)
  198. case addrErr.IsPermissionDenied:
  199. ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), tplMigrate, &form)
  200. case addrErr.IsInvalidPath:
  201. ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), tplMigrate, &form)
  202. default:
  203. ctx.ServerError("Unknown error", err)
  204. }
  205. } else {
  206. ctx.ServerError("ParseRemoteAddr", err)
  207. }
  208. return
  209. }
  210. repo, err := models.MigrateRepository(ctx.User, ctxUser, models.MigrateRepoOptions{
  211. Name: form.RepoName,
  212. Description: form.Description,
  213. IsPrivate: form.Private || setting.Repository.ForcePrivate,
  214. IsMirror: form.Mirror,
  215. RemoteAddr: remoteAddr,
  216. })
  217. if err == nil {
  218. log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, form.RepoName)
  219. ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + form.RepoName)
  220. return
  221. }
  222. if models.IsErrRepoAlreadyExist(err) {
  223. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tplMigrate, &form)
  224. return
  225. }
  226. // remoteAddr may contain credentials, so we sanitize it
  227. err = util.URLSanitizedError(err, remoteAddr)
  228. if repo != nil {
  229. if errDelete := models.DeleteRepository(ctx.User, ctxUser.ID, repo.ID); errDelete != nil {
  230. log.Error(4, "DeleteRepository: %v", errDelete)
  231. }
  232. }
  233. if strings.Contains(err.Error(), "Authentication failed") ||
  234. strings.Contains(err.Error(), "could not read Username") {
  235. ctx.Data["Err_Auth"] = true
  236. ctx.RenderWithErr(ctx.Tr("form.auth_failed", err.Error()), tplMigrate, &form)
  237. return
  238. } else if strings.Contains(err.Error(), "fatal:") {
  239. ctx.Data["Err_CloneAddr"] = true
  240. ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", err.Error()), tplMigrate, &form)
  241. return
  242. }
  243. handleCreateError(ctx, ctxUser, err, "MigratePost", tplMigrate, &form)
  244. }
  245. // Action response for actions to a repository
  246. func Action(ctx *context.Context) {
  247. var err error
  248. switch ctx.Params(":action") {
  249. case "watch":
  250. err = models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, true)
  251. case "unwatch":
  252. err = models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, false)
  253. case "star":
  254. err = models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, true)
  255. case "unstar":
  256. err = models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, false)
  257. case "desc": // FIXME: this is not used
  258. if !ctx.Repo.IsOwner() {
  259. ctx.Error(404)
  260. return
  261. }
  262. ctx.Repo.Repository.Description = ctx.Query("desc")
  263. ctx.Repo.Repository.Website = ctx.Query("site")
  264. err = models.UpdateRepository(ctx.Repo.Repository, false)
  265. }
  266. if err != nil {
  267. ctx.ServerError(fmt.Sprintf("Action (%s)", ctx.Params(":action")), err)
  268. return
  269. }
  270. ctx.RedirectToFirst(ctx.Query("redirect_to"), ctx.Repo.RepoLink)
  271. }
  272. // RedirectDownload return a file based on the following infos:
  273. func RedirectDownload(ctx *context.Context) {
  274. var (
  275. vTag = ctx.Params("vTag")
  276. fileName = ctx.Params("fileName")
  277. )
  278. tagNames := []string{vTag}
  279. curRepo := ctx.Repo.Repository
  280. releases, err := models.GetReleasesByRepoIDAndNames(curRepo.ID, tagNames)
  281. if err != nil {
  282. if models.IsErrAttachmentNotExist(err) {
  283. ctx.Error(404)
  284. return
  285. }
  286. ctx.ServerError("RedirectDownload", err)
  287. return
  288. }
  289. if len(releases) == 1 {
  290. release := releases[0]
  291. att, err := models.GetAttachmentByReleaseIDFileName(release.ID, fileName)
  292. if err != nil {
  293. ctx.Error(404)
  294. return
  295. }
  296. if att != nil {
  297. ctx.Redirect(setting.AppSubURL + "/attachments/" + att.UUID)
  298. return
  299. }
  300. }
  301. ctx.Error(404)
  302. }
  303. // Download download an archive of a repository
  304. func Download(ctx *context.Context) {
  305. var (
  306. uri = ctx.Params("*")
  307. refName string
  308. ext string
  309. archivePath string
  310. archiveType git.ArchiveType
  311. )
  312. switch {
  313. case strings.HasSuffix(uri, ".zip"):
  314. ext = ".zip"
  315. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/zip")
  316. archiveType = git.ZIP
  317. case strings.HasSuffix(uri, ".tar.gz"):
  318. ext = ".tar.gz"
  319. archivePath = path.Join(ctx.Repo.GitRepo.Path, "archives/targz")
  320. archiveType = git.TARGZ
  321. default:
  322. log.Trace("Unknown format: %s", uri)
  323. ctx.Error(404)
  324. return
  325. }
  326. refName = strings.TrimSuffix(uri, ext)
  327. if !com.IsDir(archivePath) {
  328. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  329. ctx.ServerError("Download -> os.MkdirAll(archivePath)", err)
  330. return
  331. }
  332. }
  333. // Get corresponding commit.
  334. var (
  335. commit *git.Commit
  336. err error
  337. )
  338. gitRepo := ctx.Repo.GitRepo
  339. if gitRepo.IsBranchExist(refName) {
  340. commit, err = gitRepo.GetBranchCommit(refName)
  341. if err != nil {
  342. ctx.ServerError("GetBranchCommit", err)
  343. return
  344. }
  345. } else if gitRepo.IsTagExist(refName) {
  346. commit, err = gitRepo.GetTagCommit(refName)
  347. if err != nil {
  348. ctx.ServerError("GetTagCommit", err)
  349. return
  350. }
  351. } else if len(refName) >= 4 && len(refName) <= 40 {
  352. commit, err = gitRepo.GetCommit(refName)
  353. if err != nil {
  354. ctx.NotFound("GetCommit", nil)
  355. return
  356. }
  357. } else {
  358. ctx.NotFound("Download", nil)
  359. return
  360. }
  361. archivePath = path.Join(archivePath, base.ShortSha(commit.ID.String())+ext)
  362. if !com.IsFile(archivePath) {
  363. if err := commit.CreateArchive(archivePath, archiveType); err != nil {
  364. ctx.ServerError("Download -> CreateArchive "+archivePath, err)
  365. return
  366. }
  367. }
  368. ctx.ServeFile(archivePath, ctx.Repo.Repository.Name+"-"+refName+ext)
  369. }