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 20KB

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