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

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