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.

repo.go 19KB

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