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

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