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

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