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

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