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

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