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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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.CanWrite(models.UnitTypeIssues) || 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) bool {
  124. return r.Permission.CanWrite(models.UnitTypeIssues) && r.Repository.IsDependenciesEnabled()
  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. count, 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.Repo.Repository.NumReleases = int(count)
  403. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  404. ctx.Data["Repository"] = repo
  405. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  406. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  407. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  408. ctx.Data["RepoOwnerIsOrganization"] = repo.Owner.IsOrganization()
  409. ctx.Data["CanWriteCode"] = ctx.Repo.CanWrite(models.UnitTypeCode)
  410. ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
  411. ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(models.UnitTypePullRequests)
  412. if ctx.Data["CanSignedUserFork"], err = ctx.Repo.Repository.CanUserFork(ctx.User); err != nil {
  413. ctx.ServerError("CanUserFork", err)
  414. return
  415. }
  416. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  417. ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
  418. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  419. ctx.Data["RepoSearchEnabled"] = setting.Indexer.RepoIndexerEnabled
  420. ctx.Data["CloneLink"] = repo.CloneLink()
  421. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  422. if ctx.IsSigned {
  423. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  424. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  425. }
  426. if repo.IsFork {
  427. RetrieveBaseRepo(ctx, repo)
  428. if ctx.Written() {
  429. return
  430. }
  431. }
  432. if repo.IsGenerated() {
  433. RetrieveTemplateRepo(ctx, repo)
  434. if ctx.Written() {
  435. return
  436. }
  437. }
  438. // Disable everything when the repo is being created
  439. if ctx.Repo.Repository.IsBeingCreated() {
  440. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  441. return
  442. }
  443. gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
  444. if err != nil {
  445. ctx.ServerError("RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
  446. return
  447. }
  448. ctx.Repo.GitRepo = gitRepo
  449. // We opened it, we should close it
  450. defer func() {
  451. // If it's been set to nil then assume someone else has closed it.
  452. if ctx.Repo.GitRepo != nil {
  453. ctx.Repo.GitRepo.Close()
  454. }
  455. }()
  456. // Stop at this point when the repo is empty.
  457. if ctx.Repo.Repository.IsEmpty {
  458. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  459. ctx.Next()
  460. return
  461. }
  462. tags, err := ctx.Repo.GitRepo.GetTags()
  463. if err != nil {
  464. ctx.ServerError("GetTags", err)
  465. return
  466. }
  467. ctx.Data["Tags"] = tags
  468. brs, err := ctx.Repo.GitRepo.GetBranches()
  469. if err != nil {
  470. ctx.ServerError("GetBranches", err)
  471. return
  472. }
  473. ctx.Data["Branches"] = brs
  474. ctx.Data["BranchesCount"] = len(brs)
  475. ctx.Data["TagName"] = ctx.Repo.TagName
  476. // If not branch selected, try default one.
  477. // If default branch doesn't exists, fall back to some other branch.
  478. if len(ctx.Repo.BranchName) == 0 {
  479. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  480. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  481. } else if len(brs) > 0 {
  482. ctx.Repo.BranchName = brs[0]
  483. }
  484. }
  485. ctx.Data["BranchName"] = ctx.Repo.BranchName
  486. ctx.Data["CommitID"] = ctx.Repo.CommitID
  487. // People who have push access or have forked repository can propose a new pull request.
  488. if ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) {
  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. ctx.Data["BaseRepo"] = repo.BaseRepo
  493. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  494. ctx.Repo.PullRequest.Allowed = true
  495. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  496. } else if repo.AllowsPulls() {
  497. // Or, this is repository accepts pull requests between branches.
  498. ctx.Data["BaseRepo"] = repo
  499. ctx.Repo.PullRequest.BaseRepo = repo
  500. ctx.Repo.PullRequest.Allowed = true
  501. ctx.Repo.PullRequest.SameRepo = true
  502. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  503. }
  504. }
  505. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  506. if ctx.Query("go-get") == "1" {
  507. ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
  508. prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", "branch", ctx.Repo.BranchName)
  509. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  510. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  511. }
  512. ctx.Next()
  513. }
  514. }
  515. // RepoRefType type of repo reference
  516. type RepoRefType int
  517. const (
  518. // RepoRefLegacy unknown type, make educated guess and redirect.
  519. // for backward compatibility with previous URL scheme
  520. RepoRefLegacy RepoRefType = iota
  521. // RepoRefAny is for usage where educated guess is needed
  522. // but redirect can not be made
  523. RepoRefAny
  524. // RepoRefBranch branch
  525. RepoRefBranch
  526. // RepoRefTag tag
  527. RepoRefTag
  528. // RepoRefCommit commit
  529. RepoRefCommit
  530. // RepoRefBlob blob
  531. RepoRefBlob
  532. )
  533. // RepoRef handles repository reference names when the ref name is not
  534. // explicitly given
  535. func RepoRef() macaron.Handler {
  536. // since no ref name is explicitly specified, ok to just use branch
  537. return RepoRefByType(RepoRefBranch)
  538. }
  539. // RefTypeIncludesBranches returns true if ref type can be a branch
  540. func (rt RepoRefType) RefTypeIncludesBranches() bool {
  541. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefBranch {
  542. return true
  543. }
  544. return false
  545. }
  546. // RefTypeIncludesTags returns true if ref type can be a tag
  547. func (rt RepoRefType) RefTypeIncludesTags() bool {
  548. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefTag {
  549. return true
  550. }
  551. return false
  552. }
  553. func getRefNameFromPath(ctx *Context, path string, isExist func(string) bool) string {
  554. refName := ""
  555. parts := strings.Split(path, "/")
  556. for i, part := range parts {
  557. refName = strings.TrimPrefix(refName+"/"+part, "/")
  558. if isExist(refName) {
  559. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  560. return refName
  561. }
  562. }
  563. return ""
  564. }
  565. func getRefName(ctx *Context, pathType RepoRefType) string {
  566. path := ctx.Params("*")
  567. switch pathType {
  568. case RepoRefLegacy, RepoRefAny:
  569. if refName := getRefName(ctx, RepoRefBranch); len(refName) > 0 {
  570. return refName
  571. }
  572. if refName := getRefName(ctx, RepoRefTag); len(refName) > 0 {
  573. return refName
  574. }
  575. if refName := getRefName(ctx, RepoRefCommit); len(refName) > 0 {
  576. return refName
  577. }
  578. if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 {
  579. return refName
  580. }
  581. ctx.Repo.TreePath = path
  582. return ctx.Repo.Repository.DefaultBranch
  583. case RepoRefBranch:
  584. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsBranchExist)
  585. case RepoRefTag:
  586. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist)
  587. case RepoRefCommit:
  588. parts := strings.Split(path, "/")
  589. if len(parts) > 0 && len(parts[0]) == 40 {
  590. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  591. return parts[0]
  592. }
  593. case RepoRefBlob:
  594. _, err := ctx.Repo.GitRepo.GetBlob(path)
  595. if err != nil {
  596. return ""
  597. }
  598. return path
  599. default:
  600. log.Error("Unrecognized path type: %v", path)
  601. }
  602. return ""
  603. }
  604. // RepoRefByType handles repository reference name for a specific type
  605. // of repository reference
  606. func RepoRefByType(refType RepoRefType) macaron.Handler {
  607. return func(ctx *Context) {
  608. // Empty repository does not have reference information.
  609. if ctx.Repo.Repository.IsEmpty {
  610. return
  611. }
  612. var (
  613. refName string
  614. err error
  615. )
  616. // For API calls.
  617. if ctx.Repo.GitRepo == nil {
  618. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  619. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  620. if err != nil {
  621. ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
  622. return
  623. }
  624. // We opened it, we should close it
  625. defer func() {
  626. // If it's been set to nil then assume someone else has closed it.
  627. if ctx.Repo.GitRepo != nil {
  628. ctx.Repo.GitRepo.Close()
  629. }
  630. }()
  631. }
  632. // Get default branch.
  633. if len(ctx.Params("*")) == 0 {
  634. refName = ctx.Repo.Repository.DefaultBranch
  635. ctx.Repo.BranchName = refName
  636. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  637. brs, err := ctx.Repo.GitRepo.GetBranches()
  638. if err != nil {
  639. ctx.ServerError("GetBranches", err)
  640. return
  641. } else if len(brs) == 0 {
  642. err = fmt.Errorf("No branches in non-empty repository %s",
  643. ctx.Repo.GitRepo.Path)
  644. ctx.ServerError("GetBranches", err)
  645. return
  646. }
  647. refName = brs[0]
  648. }
  649. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  650. if err != nil {
  651. ctx.ServerError("GetBranchCommit", err)
  652. return
  653. }
  654. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  655. ctx.Repo.IsViewBranch = true
  656. } else {
  657. refName = getRefName(ctx, refType)
  658. ctx.Repo.BranchName = refName
  659. if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) {
  660. ctx.Repo.IsViewBranch = true
  661. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  662. if err != nil {
  663. ctx.ServerError("GetBranchCommit", err)
  664. return
  665. }
  666. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  667. } else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) {
  668. ctx.Repo.IsViewTag = true
  669. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  670. if err != nil {
  671. ctx.ServerError("GetTagCommit", err)
  672. return
  673. }
  674. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  675. } else if len(refName) == 40 {
  676. ctx.Repo.IsViewCommit = true
  677. ctx.Repo.CommitID = refName
  678. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  679. if err != nil {
  680. ctx.NotFound("GetCommit", nil)
  681. return
  682. }
  683. } else {
  684. ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  685. return
  686. }
  687. if refType == RepoRefLegacy {
  688. // redirect from old URL scheme to new URL scheme
  689. ctx.Redirect(path.Join(
  690. setting.AppSubURL,
  691. strings.TrimSuffix(ctx.Req.URL.Path, ctx.Params("*")),
  692. ctx.Repo.BranchNameSubURL(),
  693. ctx.Repo.TreePath))
  694. return
  695. }
  696. }
  697. ctx.Data["BranchName"] = ctx.Repo.BranchName
  698. ctx.Data["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
  699. ctx.Data["CommitID"] = ctx.Repo.CommitID
  700. ctx.Data["TreePath"] = ctx.Repo.TreePath
  701. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  702. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  703. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  704. ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
  705. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  706. if err != nil {
  707. ctx.ServerError("GetCommitsCount", err)
  708. return
  709. }
  710. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  711. ctx.Next()
  712. }
  713. }
  714. // GitHookService checks if repository Git hooks service has been enabled.
  715. func GitHookService() macaron.Handler {
  716. return func(ctx *Context) {
  717. if !ctx.User.CanEditGitHook() {
  718. ctx.NotFound("GitHookService", nil)
  719. return
  720. }
  721. }
  722. }
  723. // UnitTypes returns a macaron middleware to set unit types to context variables.
  724. func UnitTypes() macaron.Handler {
  725. return func(ctx *Context) {
  726. ctx.Data["UnitTypeCode"] = models.UnitTypeCode
  727. ctx.Data["UnitTypeIssues"] = models.UnitTypeIssues
  728. ctx.Data["UnitTypePullRequests"] = models.UnitTypePullRequests
  729. ctx.Data["UnitTypeReleases"] = models.UnitTypeReleases
  730. ctx.Data["UnitTypeWiki"] = models.UnitTypeWiki
  731. ctx.Data["UnitTypeExternalWiki"] = models.UnitTypeExternalWiki
  732. ctx.Data["UnitTypeExternalTracker"] = models.UnitTypeExternalTracker
  733. }
  734. }