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

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