選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

repo.go 21KB

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