本站源代码
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

715 Zeilen
21KB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package context
  6. import (
  7. "fmt"
  8. "io/ioutil"
  9. "net/url"
  10. "path"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/cache"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "gitea.com/macaron/macaron"
  18. "github.com/editorconfig/editorconfig-core-go/v2"
  19. "github.com/unknwon/com"
  20. )
  21. // PullRequest contains informations to make a pull request
  22. type PullRequest struct {
  23. BaseRepo *models.Repository
  24. Allowed bool
  25. SameRepo bool
  26. HeadInfo string // [<user>:]<branch>
  27. }
  28. // Repository contains information to operate a repository
  29. type Repository struct {
  30. models.Permission
  31. IsWatching bool
  32. IsViewBranch bool
  33. IsViewTag bool
  34. IsViewCommit bool
  35. Repository *models.Repository
  36. Owner *models.User
  37. Commit *git.Commit
  38. Tag *git.Tag
  39. GitRepo *git.Repository
  40. BranchName string
  41. TagName string
  42. TreePath string
  43. CommitID string
  44. RepoLink string
  45. CloneLink models.CloneLink
  46. CommitsCount int64
  47. Mirror *models.Mirror
  48. PullRequest *PullRequest
  49. }
  50. // CanEnableEditor returns true if repository is editable and user has proper access level.
  51. func (r *Repository) CanEnableEditor() bool {
  52. return r.Permission.CanWrite(models.UnitTypeCode) && r.Repository.CanEnableEditor() && r.IsViewBranch && !r.Repository.IsArchived
  53. }
  54. // CanCreateBranch returns true if repository is editable and user has proper access level.
  55. func (r *Repository) CanCreateBranch() bool {
  56. return r.Permission.CanWrite(models.UnitTypeCode) && r.Repository.CanCreateBranch()
  57. }
  58. // RepoMustNotBeArchived checks if a repo is archived
  59. func RepoMustNotBeArchived() macaron.Handler {
  60. return func(ctx *Context) {
  61. if ctx.Repo.Repository.IsArchived {
  62. ctx.NotFound("IsArchived", fmt.Errorf(ctx.Tr("repo.archive.title")))
  63. }
  64. }
  65. }
  66. // CanCommitToBranch returns true if repository is editable and user has proper access level
  67. // and branch is not protected for push
  68. func (r *Repository) CanCommitToBranch(doer *models.User) (bool, error) {
  69. protectedBranch, err := r.Repository.IsProtectedBranchForPush(r.BranchName, doer)
  70. if err != nil {
  71. return false, err
  72. }
  73. return r.CanEnableEditor() && !protectedBranch, nil
  74. }
  75. // CanUseTimetracker returns whether or not a user can use the timetracker.
  76. func (r *Repository) CanUseTimetracker(issue *models.Issue, user *models.User) bool {
  77. // Checking for following:
  78. // 1. Is timetracker enabled
  79. // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this?
  80. isAssigned, _ := models.IsUserAssignedToIssue(issue, user)
  81. return r.Repository.IsTimetrackerEnabled() && (!r.Repository.AllowOnlyContributorsToTrackTime() ||
  82. r.Permission.CanWrite(models.UnitTypeIssues) || issue.IsPoster(user.ID) || isAssigned)
  83. }
  84. // CanCreateIssueDependencies returns whether or not a user can create dependencies.
  85. func (r *Repository) CanCreateIssueDependencies(user *models.User) bool {
  86. return r.Permission.CanWrite(models.UnitTypeIssues) && r.Repository.IsDependenciesEnabled()
  87. }
  88. // GetCommitsCount returns cached commit count for current view
  89. func (r *Repository) GetCommitsCount() (int64, error) {
  90. var contextName string
  91. if r.IsViewBranch {
  92. contextName = r.BranchName
  93. } else if r.IsViewTag {
  94. contextName = r.TagName
  95. } else {
  96. contextName = r.CommitID
  97. }
  98. return cache.GetInt64(r.Repository.GetCommitsCountCacheKey(contextName, r.IsViewBranch || r.IsViewTag), func() (int64, error) {
  99. return r.Commit.CommitsCount()
  100. })
  101. }
  102. // BranchNameSubURL sub-URL for the BranchName field
  103. func (r *Repository) BranchNameSubURL() string {
  104. switch {
  105. case r.IsViewBranch:
  106. return "branch/" + r.BranchName
  107. case r.IsViewTag:
  108. return "tag/" + r.BranchName
  109. case r.IsViewCommit:
  110. return "commit/" + r.BranchName
  111. }
  112. log.Error("Unknown view type for repo: %v", r)
  113. return ""
  114. }
  115. // FileExists returns true if a file exists in the given repo branch
  116. func (r *Repository) FileExists(path string, branch string) (bool, error) {
  117. if branch == "" {
  118. branch = r.Repository.DefaultBranch
  119. }
  120. commit, err := r.GitRepo.GetBranchCommit(branch)
  121. if err != nil {
  122. return false, err
  123. }
  124. if _, err := commit.GetTreeEntryByPath(path); err != nil {
  125. return false, err
  126. }
  127. return true, nil
  128. }
  129. // GetEditorconfig returns the .editorconfig definition if found in the
  130. // HEAD of the default repo branch.
  131. func (r *Repository) GetEditorconfig() (*editorconfig.Editorconfig, error) {
  132. if r.GitRepo == nil {
  133. return nil, nil
  134. }
  135. commit, err := r.GitRepo.GetBranchCommit(r.Repository.DefaultBranch)
  136. if err != nil {
  137. return nil, err
  138. }
  139. treeEntry, err := commit.GetTreeEntryByPath(".editorconfig")
  140. if err != nil {
  141. return nil, err
  142. }
  143. if treeEntry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  144. return nil, git.ErrNotExist{ID: "", RelPath: ".editorconfig"}
  145. }
  146. reader, err := treeEntry.Blob().DataAsync()
  147. if err != nil {
  148. return nil, err
  149. }
  150. defer reader.Close()
  151. data, err := ioutil.ReadAll(reader)
  152. if err != nil {
  153. return nil, err
  154. }
  155. return editorconfig.ParseBytes(data)
  156. }
  157. // RetrieveBaseRepo retrieves base repository
  158. func RetrieveBaseRepo(ctx *Context, repo *models.Repository) {
  159. // Non-fork repository will not return error in this method.
  160. if err := repo.GetBaseRepo(); err != nil {
  161. if models.IsErrRepoNotExist(err) {
  162. repo.IsFork = false
  163. repo.ForkID = 0
  164. return
  165. }
  166. ctx.ServerError("GetBaseRepo", err)
  167. return
  168. } else if err = repo.BaseRepo.GetOwner(); err != nil {
  169. ctx.ServerError("BaseRepo.GetOwner", err)
  170. return
  171. }
  172. }
  173. // ComposeGoGetImport returns go-get-import meta content.
  174. func ComposeGoGetImport(owner, repo string) string {
  175. /// setting.AppUrl is guaranteed to be parse as url
  176. appURL, _ := url.Parse(setting.AppURL)
  177. return path.Join(appURL.Host, setting.AppSubURL, url.PathEscape(owner), url.PathEscape(repo))
  178. }
  179. // EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  180. // if user does not have actual access to the requested repository,
  181. // or the owner or repository does not exist at all.
  182. // This is particular a workaround for "go get" command which does not respect
  183. // .netrc file.
  184. func EarlyResponseForGoGetMeta(ctx *Context) {
  185. username := ctx.Params(":username")
  186. reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  187. if username == "" || reponame == "" {
  188. ctx.PlainText(400, []byte("invalid repository path"))
  189. return
  190. }
  191. ctx.PlainText(200, []byte(com.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
  192. map[string]string{
  193. "GoGetImport": ComposeGoGetImport(username, reponame),
  194. "CloneLink": models.ComposeHTTPSCloneURL(username, reponame),
  195. })))
  196. }
  197. // RedirectToRepo redirect to a differently-named repository
  198. func RedirectToRepo(ctx *Context, redirectRepoID int64) {
  199. ownerName := ctx.Params(":username")
  200. previousRepoName := ctx.Params(":reponame")
  201. repo, err := models.GetRepositoryByID(redirectRepoID)
  202. if err != nil {
  203. ctx.ServerError("GetRepositoryByID", err)
  204. return
  205. }
  206. redirectPath := strings.Replace(
  207. ctx.Req.URL.Path,
  208. fmt.Sprintf("%s/%s", ownerName, previousRepoName),
  209. fmt.Sprintf("%s/%s", repo.MustOwnerName(), repo.Name),
  210. 1,
  211. )
  212. if ctx.Req.URL.RawQuery != "" {
  213. redirectPath += "?" + ctx.Req.URL.RawQuery
  214. }
  215. ctx.Redirect(path.Join(setting.AppSubURL, redirectPath))
  216. }
  217. func repoAssignment(ctx *Context, repo *models.Repository) {
  218. var err error
  219. if err = repo.GetOwner(); err != nil {
  220. ctx.ServerError("GetOwner", err)
  221. return
  222. }
  223. ctx.Repo.Permission, err = models.GetUserRepoPermission(repo, ctx.User)
  224. if err != nil {
  225. ctx.ServerError("GetUserRepoPermission", err)
  226. return
  227. }
  228. // Check access.
  229. if ctx.Repo.Permission.AccessMode == models.AccessModeNone {
  230. if ctx.Query("go-get") == "1" {
  231. EarlyResponseForGoGetMeta(ctx)
  232. return
  233. }
  234. ctx.NotFound("no access right", nil)
  235. return
  236. }
  237. ctx.Data["HasAccess"] = true
  238. ctx.Data["Permission"] = &ctx.Repo.Permission
  239. if repo.IsMirror {
  240. var err error
  241. ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  242. if err != nil {
  243. ctx.ServerError("GetMirror", err)
  244. return
  245. }
  246. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  247. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  248. ctx.Data["Mirror"] = ctx.Repo.Mirror
  249. }
  250. ctx.Repo.Repository = repo
  251. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  252. ctx.Data["IsEmptyRepo"] = ctx.Repo.Repository.IsEmpty
  253. }
  254. // RepoIDAssignment returns a macaron handler which assigns the repo to the context.
  255. func RepoIDAssignment() macaron.Handler {
  256. return func(ctx *Context) {
  257. repoID := ctx.ParamsInt64(":repoid")
  258. // Get repository.
  259. repo, err := models.GetRepositoryByID(repoID)
  260. if err != nil {
  261. if models.IsErrRepoNotExist(err) {
  262. ctx.NotFound("GetRepositoryByID", nil)
  263. } else {
  264. ctx.ServerError("GetRepositoryByID", err)
  265. }
  266. return
  267. }
  268. repoAssignment(ctx, repo)
  269. }
  270. }
  271. // RepoAssignment returns a macaron to handle repository assignment
  272. func RepoAssignment() macaron.Handler {
  273. return func(ctx *Context) {
  274. var (
  275. owner *models.User
  276. err error
  277. )
  278. userName := ctx.Params(":username")
  279. repoName := ctx.Params(":reponame")
  280. // Check if the user is the same as the repository owner
  281. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  282. owner = ctx.User
  283. } else {
  284. owner, err = models.GetUserByName(userName)
  285. if err != nil {
  286. if models.IsErrUserNotExist(err) {
  287. if ctx.Query("go-get") == "1" {
  288. EarlyResponseForGoGetMeta(ctx)
  289. return
  290. }
  291. ctx.NotFound("GetUserByName", nil)
  292. } else {
  293. ctx.ServerError("GetUserByName", err)
  294. }
  295. return
  296. }
  297. }
  298. ctx.Repo.Owner = owner
  299. ctx.Data["Username"] = ctx.Repo.Owner.Name
  300. // Get repository.
  301. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  302. if err != nil {
  303. if models.IsErrRepoNotExist(err) {
  304. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  305. if err == nil {
  306. RedirectToRepo(ctx, redirectRepoID)
  307. } else if models.IsErrRepoRedirectNotExist(err) {
  308. if ctx.Query("go-get") == "1" {
  309. EarlyResponseForGoGetMeta(ctx)
  310. return
  311. }
  312. ctx.NotFound("GetRepositoryByName", nil)
  313. } else {
  314. ctx.ServerError("LookupRepoRedirect", err)
  315. }
  316. } else {
  317. ctx.ServerError("GetRepositoryByName", err)
  318. }
  319. return
  320. }
  321. repo.Owner = owner
  322. repoAssignment(ctx, repo)
  323. if ctx.Written() {
  324. return
  325. }else if ctx.Repo.UnitsMode[models.UnitTypeCode] == models.AccessModeNone {
  326. wikiUrl := repo.Link() + "/wiki"
  327. if ctx.Link == repo.Link() {
  328. //无代码权限用户跳转到默认wiki页面
  329. ctx.Redirect(wikiUrl)
  330. }
  331. }
  332. ctx.Repo.RepoLink = repo.Link()
  333. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  334. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  335. unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  336. if err == nil {
  337. ctx.Data["RepoExternalIssuesLink"] = unit.ExternalTrackerConfig().ExternalTrackerURL
  338. }
  339. count, err := models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
  340. IncludeDrafts: false,
  341. IncludeTags: true,
  342. })
  343. if err != nil {
  344. ctx.ServerError("GetReleaseCountByRepoID", err)
  345. return
  346. }
  347. ctx.Repo.Repository.NumReleases = int(count)
  348. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  349. ctx.Data["Repository"] = repo
  350. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  351. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  352. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  353. ctx.Data["RepoOwnerIsOrganization"] = repo.Owner.IsOrganization()
  354. ctx.Data["CanWriteCode"] = ctx.Repo.CanWrite(models.UnitTypeCode)
  355. ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
  356. ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(models.UnitTypePullRequests)
  357. if ctx.Data["CanSignedUserFork"], err = ctx.Repo.Repository.CanUserFork(ctx.User); err != nil {
  358. ctx.ServerError("CanUserFork", err)
  359. return
  360. }
  361. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  362. ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
  363. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  364. ctx.Data["RepoSearchEnabled"] = setting.Indexer.RepoIndexerEnabled
  365. ctx.Data["CloneLink"] = repo.CloneLink()
  366. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  367. if ctx.IsSigned {
  368. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  369. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  370. }
  371. if repo.IsFork {
  372. RetrieveBaseRepo(ctx, repo)
  373. if ctx.Written() {
  374. return
  375. }
  376. }
  377. // Disable everything when the repo is being created
  378. if ctx.Repo.Repository.IsBeingCreated() {
  379. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  380. return
  381. }
  382. gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
  383. if err != nil {
  384. ctx.ServerError("RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
  385. return
  386. }
  387. ctx.Repo.GitRepo = gitRepo
  388. // Stop at this point when the repo is empty.
  389. if ctx.Repo.Repository.IsEmpty {
  390. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  391. return
  392. }
  393. tags, err := ctx.Repo.GitRepo.GetTags()
  394. if err != nil {
  395. ctx.ServerError("GetTags", err)
  396. return
  397. }
  398. ctx.Data["Tags"] = tags
  399. brs, err := ctx.Repo.GitRepo.GetBranches()
  400. if err != nil {
  401. ctx.ServerError("GetBranches", err)
  402. return
  403. }
  404. ctx.Data["Branches"] = brs
  405. ctx.Data["BranchesCount"] = len(brs)
  406. ctx.Data["TagName"] = ctx.Repo.TagName
  407. // If not branch selected, try default one.
  408. // If default branch doesn't exists, fall back to some other branch.
  409. if len(ctx.Repo.BranchName) == 0 {
  410. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  411. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  412. } else if len(brs) > 0 {
  413. ctx.Repo.BranchName = brs[0]
  414. }
  415. }
  416. ctx.Data["BranchName"] = ctx.Repo.BranchName
  417. ctx.Data["CommitID"] = ctx.Repo.CommitID
  418. // People who have push access or have forked repository can propose a new pull request.
  419. if ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) {
  420. // Pull request is allowed if this is a fork repository
  421. // and base repository accepts pull requests.
  422. if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
  423. ctx.Data["BaseRepo"] = repo.BaseRepo
  424. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  425. ctx.Repo.PullRequest.Allowed = true
  426. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  427. } else if repo.AllowsPulls() {
  428. // Or, this is repository accepts pull requests between branches.
  429. ctx.Data["BaseRepo"] = repo
  430. ctx.Repo.PullRequest.BaseRepo = repo
  431. ctx.Repo.PullRequest.Allowed = true
  432. ctx.Repo.PullRequest.SameRepo = true
  433. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  434. }
  435. }
  436. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  437. if ctx.Query("go-get") == "1" {
  438. ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
  439. prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", "branch", ctx.Repo.BranchName)
  440. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  441. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  442. }
  443. }
  444. }
  445. // RepoRefType type of repo reference
  446. type RepoRefType int
  447. const (
  448. // RepoRefLegacy unknown type, make educated guess and redirect.
  449. // for backward compatibility with previous URL scheme
  450. RepoRefLegacy RepoRefType = iota
  451. // RepoRefAny is for usage where educated guess is needed
  452. // but redirect can not be made
  453. RepoRefAny
  454. // RepoRefBranch branch
  455. RepoRefBranch
  456. // RepoRefTag tag
  457. RepoRefTag
  458. // RepoRefCommit commit
  459. RepoRefCommit
  460. // RepoRefBlob blob
  461. RepoRefBlob
  462. )
  463. // RepoRef handles repository reference names when the ref name is not
  464. // explicitly given
  465. func RepoRef() macaron.Handler {
  466. // since no ref name is explicitly specified, ok to just use branch
  467. return RepoRefByType(RepoRefBranch)
  468. }
  469. func getRefNameFromPath(ctx *Context, path string, isExist func(string) bool) string {
  470. refName := ""
  471. parts := strings.Split(path, "/")
  472. for i, part := range parts {
  473. refName = strings.TrimPrefix(refName+"/"+part, "/")
  474. if isExist(refName) {
  475. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  476. return refName
  477. }
  478. }
  479. return ""
  480. }
  481. func getRefName(ctx *Context, pathType RepoRefType) string {
  482. path := ctx.Params("*")
  483. switch pathType {
  484. case RepoRefLegacy, RepoRefAny:
  485. if refName := getRefName(ctx, RepoRefBranch); len(refName) > 0 {
  486. return refName
  487. }
  488. if refName := getRefName(ctx, RepoRefTag); len(refName) > 0 {
  489. return refName
  490. }
  491. if refName := getRefName(ctx, RepoRefCommit); len(refName) > 0 {
  492. return refName
  493. }
  494. if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 {
  495. return refName
  496. }
  497. ctx.Repo.TreePath = path
  498. return ctx.Repo.Repository.DefaultBranch
  499. case RepoRefBranch:
  500. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsBranchExist)
  501. case RepoRefTag:
  502. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist)
  503. case RepoRefCommit:
  504. parts := strings.Split(path, "/")
  505. if len(parts) > 0 && len(parts[0]) == 40 {
  506. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  507. return parts[0]
  508. }
  509. case RepoRefBlob:
  510. _, err := ctx.Repo.GitRepo.GetBlob(path)
  511. if err != nil {
  512. return ""
  513. }
  514. return path
  515. default:
  516. log.Error("Unrecognized path type: %v", path)
  517. }
  518. return ""
  519. }
  520. // RepoRefByType handles repository reference name for a specific type
  521. // of repository reference
  522. func RepoRefByType(refType RepoRefType) macaron.Handler {
  523. return func(ctx *Context) {
  524. // Empty repository does not have reference information.
  525. if ctx.Repo.Repository.IsEmpty {
  526. return
  527. }
  528. var (
  529. refName string
  530. err error
  531. )
  532. // For API calls.
  533. if ctx.Repo.GitRepo == nil {
  534. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  535. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  536. if err != nil {
  537. ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
  538. return
  539. }
  540. }
  541. // Get default branch.
  542. if len(ctx.Params("*")) == 0 {
  543. refName = ctx.Repo.Repository.DefaultBranch
  544. ctx.Repo.BranchName = refName
  545. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  546. brs, err := ctx.Repo.GitRepo.GetBranches()
  547. if err != nil {
  548. ctx.ServerError("GetBranches", err)
  549. return
  550. } else if len(brs) == 0 {
  551. err = fmt.Errorf("No branches in non-empty repository %s",
  552. ctx.Repo.GitRepo.Path)
  553. ctx.ServerError("GetBranches", err)
  554. return
  555. }
  556. refName = brs[0]
  557. }
  558. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  559. if err != nil {
  560. ctx.ServerError("GetBranchCommit", err)
  561. return
  562. }
  563. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  564. ctx.Repo.IsViewBranch = true
  565. } else {
  566. refName = getRefName(ctx, refType)
  567. ctx.Repo.BranchName = refName
  568. if ctx.Repo.GitRepo.IsBranchExist(refName) {
  569. ctx.Repo.IsViewBranch = true
  570. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  571. if err != nil {
  572. ctx.ServerError("GetBranchCommit", err)
  573. return
  574. }
  575. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  576. } else if ctx.Repo.GitRepo.IsTagExist(refName) {
  577. ctx.Repo.IsViewTag = true
  578. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  579. if err != nil {
  580. ctx.ServerError("GetTagCommit", err)
  581. return
  582. }
  583. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  584. } else if len(refName) == 40 {
  585. ctx.Repo.IsViewCommit = true
  586. ctx.Repo.CommitID = refName
  587. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  588. if err != nil {
  589. ctx.NotFound("GetCommit", nil)
  590. return
  591. }
  592. } else {
  593. ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  594. return
  595. }
  596. if refType == RepoRefLegacy {
  597. // redirect from old URL scheme to new URL scheme
  598. ctx.Redirect(path.Join(
  599. setting.AppSubURL,
  600. strings.TrimSuffix(ctx.Req.URL.Path, ctx.Params("*")),
  601. ctx.Repo.BranchNameSubURL(),
  602. ctx.Repo.TreePath))
  603. return
  604. }
  605. }
  606. ctx.Data["BranchName"] = ctx.Repo.BranchName
  607. ctx.Data["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
  608. ctx.Data["CommitID"] = ctx.Repo.CommitID
  609. ctx.Data["TreePath"] = ctx.Repo.TreePath
  610. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  611. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  612. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  613. ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
  614. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  615. if err != nil {
  616. ctx.ServerError("GetCommitsCount", err)
  617. return
  618. }
  619. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  620. }
  621. }
  622. // GitHookService checks if repository Git hooks service has been enabled.
  623. func GitHookService() macaron.Handler {
  624. return func(ctx *Context) {
  625. if !ctx.User.CanEditGitHook() {
  626. ctx.NotFound("GitHookService", nil)
  627. return
  628. }
  629. }
  630. }
  631. // UnitTypes returns a macaron middleware to set unit types to context variables.
  632. func UnitTypes() macaron.Handler {
  633. return func(ctx *Context) {
  634. ctx.Data["UnitTypeCode"] = models.UnitTypeCode
  635. ctx.Data["UnitTypeIssues"] = models.UnitTypeIssues
  636. ctx.Data["UnitTypePullRequests"] = models.UnitTypePullRequests
  637. ctx.Data["UnitTypeReleases"] = models.UnitTypeReleases
  638. ctx.Data["UnitTypeWiki"] = models.UnitTypeWiki
  639. ctx.Data["UnitTypeExternalWiki"] = models.UnitTypeExternalWiki
  640. ctx.Data["UnitTypeExternalTracker"] = models.UnitTypeExternalTracker
  641. }
  642. }
上海开阖软件有限公司 沪ICP备12045867号-1