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

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