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

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