本站源代码
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.

477 lines
13KB

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