Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

repo.go 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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. "context"
  8. "fmt"
  9. "html"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "path"
  14. "strings"
  15. "code.gitea.io/gitea/models"
  16. repo_model "code.gitea.io/gitea/models/repo"
  17. unit_model "code.gitea.io/gitea/models/unit"
  18. user_model "code.gitea.io/gitea/models/user"
  19. "code.gitea.io/gitea/modules/cache"
  20. "code.gitea.io/gitea/modules/git"
  21. code_indexer "code.gitea.io/gitea/modules/indexer/code"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/markup/markdown"
  24. "code.gitea.io/gitea/modules/setting"
  25. api "code.gitea.io/gitea/modules/structs"
  26. "code.gitea.io/gitea/modules/util"
  27. asymkey_service "code.gitea.io/gitea/services/asymkey"
  28. "github.com/editorconfig/editorconfig-core-go/v2"
  29. )
  30. // IssueTemplateDirCandidates issue templates directory
  31. var IssueTemplateDirCandidates = []string{
  32. "ISSUE_TEMPLATE",
  33. "issue_template",
  34. ".gitea/ISSUE_TEMPLATE",
  35. ".gitea/issue_template",
  36. ".github/ISSUE_TEMPLATE",
  37. ".github/issue_template",
  38. ".gitlab/ISSUE_TEMPLATE",
  39. ".gitlab/issue_template",
  40. }
  41. // PullRequest contains information to make a pull request
  42. type PullRequest struct {
  43. BaseRepo *repo_model.Repository
  44. Allowed bool
  45. SameRepo bool
  46. HeadInfoSubURL string // [<user>:]<branch> url segment
  47. }
  48. // Repository contains information to operate a repository
  49. type Repository struct {
  50. models.Permission
  51. IsWatching bool
  52. IsViewBranch bool
  53. IsViewTag bool
  54. IsViewCommit bool
  55. Repository *repo_model.Repository
  56. Owner *user_model.User
  57. Commit *git.Commit
  58. Tag *git.Tag
  59. GitRepo *git.Repository
  60. RefName string
  61. BranchName string
  62. TagName string
  63. TreePath string
  64. CommitID string
  65. RepoLink string
  66. CloneLink repo_model.CloneLink
  67. CommitsCount int64
  68. Mirror *repo_model.Mirror
  69. PullRequest *PullRequest
  70. }
  71. // CanEnableEditor returns true if repository is editable and user has proper access level.
  72. func (r *Repository) CanEnableEditor(user *user_model.User) bool {
  73. return r.IsViewBranch && r.Permission.CanWriteToBranch(user, r.BranchName) && r.Repository.CanEnableEditor() && !r.Repository.IsArchived
  74. }
  75. // CanCreateBranch returns true if repository is editable and user has proper access level.
  76. func (r *Repository) CanCreateBranch() bool {
  77. return r.Permission.CanWrite(unit_model.TypeCode) && r.Repository.CanCreateBranch()
  78. }
  79. // RepoMustNotBeArchived checks if a repo is archived
  80. func RepoMustNotBeArchived() func(ctx *Context) {
  81. return func(ctx *Context) {
  82. if ctx.Repo.Repository.IsArchived {
  83. ctx.NotFound("IsArchived", fmt.Errorf(ctx.Tr("repo.archive.title")))
  84. }
  85. }
  86. }
  87. // CanCommitToBranchResults represents the results of CanCommitToBranch
  88. type CanCommitToBranchResults struct {
  89. CanCommitToBranch bool
  90. EditorEnabled bool
  91. UserCanPush bool
  92. RequireSigned bool
  93. WillSign bool
  94. SigningKey string
  95. WontSignReason string
  96. }
  97. // CanCommitToBranch returns true if repository is editable and user has proper access level
  98. // and branch is not protected for push
  99. func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.User) (CanCommitToBranchResults, error) {
  100. protectedBranch, err := models.GetProtectedBranchBy(r.Repository.ID, r.BranchName)
  101. if err != nil {
  102. return CanCommitToBranchResults{}, err
  103. }
  104. userCanPush := true
  105. requireSigned := false
  106. if protectedBranch != nil {
  107. userCanPush = protectedBranch.CanUserPush(doer.ID)
  108. requireSigned = protectedBranch.RequireSignedCommits
  109. }
  110. sign, keyID, _, err := asymkey_service.SignCRUDAction(ctx, r.Repository.RepoPath(), doer, r.Repository.RepoPath(), git.BranchPrefix+r.BranchName)
  111. canCommit := r.CanEnableEditor(doer) && userCanPush
  112. if requireSigned {
  113. canCommit = canCommit && sign
  114. }
  115. wontSignReason := ""
  116. if err != nil {
  117. if asymkey_service.IsErrWontSign(err) {
  118. wontSignReason = string(err.(*asymkey_service.ErrWontSign).Reason)
  119. err = nil
  120. } else {
  121. wontSignReason = "error"
  122. }
  123. }
  124. return CanCommitToBranchResults{
  125. CanCommitToBranch: canCommit,
  126. EditorEnabled: r.CanEnableEditor(doer),
  127. UserCanPush: userCanPush,
  128. RequireSigned: requireSigned,
  129. WillSign: sign,
  130. SigningKey: keyID,
  131. WontSignReason: wontSignReason,
  132. }, err
  133. }
  134. // CanUseTimetracker returns whether or not a user can use the timetracker.
  135. func (r *Repository) CanUseTimetracker(issue *models.Issue, user *user_model.User) bool {
  136. // Checking for following:
  137. // 1. Is timetracker enabled
  138. // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this?
  139. isAssigned, _ := models.IsUserAssignedToIssue(issue, user)
  140. return r.Repository.IsTimetrackerEnabled() && (!r.Repository.AllowOnlyContributorsToTrackTime() ||
  141. r.Permission.CanWriteIssuesOrPulls(issue.IsPull) || issue.IsPoster(user.ID) || isAssigned)
  142. }
  143. // CanCreateIssueDependencies returns whether or not a user can create dependencies.
  144. func (r *Repository) CanCreateIssueDependencies(user *user_model.User, isPull bool) bool {
  145. return r.Repository.IsDependenciesEnabled() && r.Permission.CanWriteIssuesOrPulls(isPull)
  146. }
  147. // GetCommitsCount returns cached commit count for current view
  148. func (r *Repository) GetCommitsCount() (int64, error) {
  149. var contextName string
  150. if r.IsViewBranch {
  151. contextName = r.BranchName
  152. } else if r.IsViewTag {
  153. contextName = r.TagName
  154. } else {
  155. contextName = r.CommitID
  156. }
  157. return cache.GetInt64(r.Repository.GetCommitsCountCacheKey(contextName, r.IsViewBranch || r.IsViewTag), func() (int64, error) {
  158. return r.Commit.CommitsCount()
  159. })
  160. }
  161. // GetCommitGraphsCount returns cached commit count for current view
  162. func (r *Repository) GetCommitGraphsCount(ctx context.Context, hidePRRefs bool, branches, files []string) (int64, error) {
  163. cacheKey := fmt.Sprintf("commits-count-%d-graph-%t-%s-%s", r.Repository.ID, hidePRRefs, branches, files)
  164. return cache.GetInt64(cacheKey, func() (int64, error) {
  165. if len(branches) == 0 {
  166. return git.AllCommitsCount(ctx, r.Repository.RepoPath(), hidePRRefs, files...)
  167. }
  168. return git.CommitsCountFiles(ctx, r.Repository.RepoPath(), branches, files)
  169. })
  170. }
  171. // BranchNameSubURL sub-URL for the BranchName field
  172. func (r *Repository) BranchNameSubURL() string {
  173. switch {
  174. case r.IsViewBranch:
  175. return "branch/" + util.PathEscapeSegments(r.BranchName)
  176. case r.IsViewTag:
  177. return "tag/" + util.PathEscapeSegments(r.TagName)
  178. case r.IsViewCommit:
  179. return "commit/" + util.PathEscapeSegments(r.CommitID)
  180. }
  181. log.Error("Unknown view type for repo: %v", r)
  182. return ""
  183. }
  184. // FileExists returns true if a file exists in the given repo branch
  185. func (r *Repository) FileExists(path, branch string) (bool, error) {
  186. if branch == "" {
  187. branch = r.Repository.DefaultBranch
  188. }
  189. commit, err := r.GitRepo.GetBranchCommit(branch)
  190. if err != nil {
  191. return false, err
  192. }
  193. if _, err := commit.GetTreeEntryByPath(path); err != nil {
  194. return false, err
  195. }
  196. return true, nil
  197. }
  198. // GetEditorconfig returns the .editorconfig definition if found in the
  199. // HEAD of the default repo branch.
  200. func (r *Repository) GetEditorconfig(optCommit ...*git.Commit) (*editorconfig.Editorconfig, error) {
  201. if r.GitRepo == nil {
  202. return nil, nil
  203. }
  204. var (
  205. err error
  206. commit *git.Commit
  207. )
  208. if len(optCommit) != 0 {
  209. commit = optCommit[0]
  210. } else {
  211. commit, err = r.GitRepo.GetBranchCommit(r.Repository.DefaultBranch)
  212. if err != nil {
  213. return nil, err
  214. }
  215. }
  216. treeEntry, err := commit.GetTreeEntryByPath(".editorconfig")
  217. if err != nil {
  218. return nil, err
  219. }
  220. if treeEntry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  221. return nil, git.ErrNotExist{ID: "", RelPath: ".editorconfig"}
  222. }
  223. reader, err := treeEntry.Blob().DataAsync()
  224. if err != nil {
  225. return nil, err
  226. }
  227. defer reader.Close()
  228. return editorconfig.Parse(reader)
  229. }
  230. // RetrieveBaseRepo retrieves base repository
  231. func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository) {
  232. // Non-fork repository will not return error in this method.
  233. if err := repo.GetBaseRepo(); err != nil {
  234. if repo_model.IsErrRepoNotExist(err) {
  235. repo.IsFork = false
  236. repo.ForkID = 0
  237. return
  238. }
  239. ctx.ServerError("GetBaseRepo", err)
  240. return
  241. } else if err = repo.BaseRepo.GetOwner(ctx); err != nil {
  242. ctx.ServerError("BaseRepo.GetOwner", err)
  243. return
  244. }
  245. }
  246. // RetrieveTemplateRepo retrieves template repository used to generate this repository
  247. func RetrieveTemplateRepo(ctx *Context, repo *repo_model.Repository) {
  248. // Non-generated repository will not return error in this method.
  249. templateRepo, err := repo_model.GetTemplateRepo(repo)
  250. if err != nil {
  251. if repo_model.IsErrRepoNotExist(err) {
  252. repo.TemplateID = 0
  253. return
  254. }
  255. ctx.ServerError("GetTemplateRepo", err)
  256. return
  257. } else if err = templateRepo.GetOwner(ctx); err != nil {
  258. ctx.ServerError("TemplateRepo.GetOwner", err)
  259. return
  260. }
  261. perm, err := models.GetUserRepoPermission(ctx, templateRepo, ctx.Doer)
  262. if err != nil {
  263. ctx.ServerError("GetUserRepoPermission", err)
  264. return
  265. }
  266. if !perm.CanRead(unit_model.TypeCode) {
  267. repo.TemplateID = 0
  268. }
  269. }
  270. // ComposeGoGetImport returns go-get-import meta content.
  271. func ComposeGoGetImport(owner, repo string) string {
  272. /// setting.AppUrl is guaranteed to be parse as url
  273. appURL, _ := url.Parse(setting.AppURL)
  274. return path.Join(appURL.Host, setting.AppSubURL, url.PathEscape(owner), url.PathEscape(repo))
  275. }
  276. // EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  277. // if user does not have actual access to the requested repository,
  278. // or the owner or repository does not exist at all.
  279. // This is particular a workaround for "go get" command which does not respect
  280. // .netrc file.
  281. func EarlyResponseForGoGetMeta(ctx *Context) {
  282. username := ctx.Params(":username")
  283. reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  284. if username == "" || reponame == "" {
  285. ctx.PlainText(http.StatusBadRequest, "invalid repository path")
  286. return
  287. }
  288. goImportContent := fmt.Sprintf("%s git %s", ComposeGoGetImport(username, reponame), repo_model.ComposeHTTPSCloneURL(username, reponame))
  289. htmlMeta := fmt.Sprintf(`<meta name="go-import" content="%s">`, html.EscapeString(goImportContent))
  290. ctx.PlainText(http.StatusOK, htmlMeta)
  291. }
  292. // RedirectToRepo redirect to a differently-named repository
  293. func RedirectToRepo(ctx *Context, redirectRepoID int64) {
  294. ownerName := ctx.Params(":username")
  295. previousRepoName := ctx.Params(":reponame")
  296. repo, err := repo_model.GetRepositoryByID(redirectRepoID)
  297. if err != nil {
  298. ctx.ServerError("GetRepositoryByID", err)
  299. return
  300. }
  301. redirectPath := strings.Replace(
  302. ctx.Req.URL.EscapedPath(),
  303. url.PathEscape(ownerName)+"/"+url.PathEscape(previousRepoName),
  304. url.PathEscape(repo.OwnerName)+"/"+url.PathEscape(repo.Name),
  305. 1,
  306. )
  307. if ctx.Req.URL.RawQuery != "" {
  308. redirectPath += "?" + ctx.Req.URL.RawQuery
  309. }
  310. ctx.Redirect(path.Join(setting.AppSubURL, redirectPath), http.StatusTemporaryRedirect)
  311. }
  312. func repoAssignment(ctx *Context, repo *repo_model.Repository) {
  313. var err error
  314. if err = repo.GetOwner(ctx); err != nil {
  315. ctx.ServerError("GetOwner", err)
  316. return
  317. }
  318. ctx.Repo.Permission, err = models.GetUserRepoPermission(ctx, repo, ctx.Doer)
  319. if err != nil {
  320. ctx.ServerError("GetUserRepoPermission", err)
  321. return
  322. }
  323. // Check access.
  324. if !ctx.Repo.Permission.HasAccess() {
  325. if ctx.FormString("go-get") == "1" {
  326. EarlyResponseForGoGetMeta(ctx)
  327. return
  328. }
  329. ctx.NotFound("no access right", nil)
  330. return
  331. }
  332. ctx.Data["HasAccess"] = true
  333. ctx.Data["Permission"] = &ctx.Repo.Permission
  334. if repo.IsMirror {
  335. // Check if the mirror has finsihed migrationg, only then we can
  336. // lookup the mirror informtation the database.
  337. finishedMigrating, err := models.HasFinishedMigratingTask(repo.ID)
  338. if err != nil {
  339. ctx.ServerError("HasFinishedMigratingTask", err)
  340. return
  341. }
  342. if finishedMigrating {
  343. ctx.Repo.Mirror, err = repo_model.GetMirrorByRepoID(repo.ID)
  344. if err != nil {
  345. ctx.ServerError("GetMirrorByRepoID", err)
  346. return
  347. }
  348. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  349. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  350. ctx.Data["Mirror"] = ctx.Repo.Mirror
  351. }
  352. }
  353. pushMirrors, err := repo_model.GetPushMirrorsByRepoID(repo.ID)
  354. if err != nil {
  355. ctx.ServerError("GetPushMirrorsByRepoID", err)
  356. return
  357. }
  358. ctx.Repo.Repository = repo
  359. ctx.Data["PushMirrors"] = pushMirrors
  360. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  361. ctx.Data["IsEmptyRepo"] = ctx.Repo.Repository.IsEmpty
  362. }
  363. // RepoIDAssignment returns a handler which assigns the repo to the context.
  364. func RepoIDAssignment() func(ctx *Context) {
  365. return func(ctx *Context) {
  366. repoID := ctx.ParamsInt64(":repoid")
  367. // Get repository.
  368. repo, err := repo_model.GetRepositoryByID(repoID)
  369. if err != nil {
  370. if repo_model.IsErrRepoNotExist(err) {
  371. ctx.NotFound("GetRepositoryByID", nil)
  372. } else {
  373. ctx.ServerError("GetRepositoryByID", err)
  374. }
  375. return
  376. }
  377. repoAssignment(ctx, repo)
  378. }
  379. }
  380. // RepoAssignment returns a middleware to handle repository assignment
  381. func RepoAssignment(ctx *Context) (cancel context.CancelFunc) {
  382. if _, repoAssignmentOnce := ctx.Data["repoAssignmentExecuted"]; repoAssignmentOnce {
  383. log.Trace("RepoAssignment was exec already, skipping second call ...")
  384. return
  385. }
  386. ctx.Data["repoAssignmentExecuted"] = true
  387. var (
  388. owner *user_model.User
  389. err error
  390. )
  391. userName := ctx.Params(":username")
  392. repoName := ctx.Params(":reponame")
  393. repoName = strings.TrimSuffix(repoName, ".git")
  394. repoName = strings.TrimSuffix(repoName, ".rss")
  395. repoName = strings.TrimSuffix(repoName, ".atom")
  396. // Check if the user is the same as the repository owner
  397. if ctx.IsSigned && ctx.Doer.LowerName == strings.ToLower(userName) {
  398. owner = ctx.Doer
  399. } else {
  400. owner, err = user_model.GetUserByName(userName)
  401. if err != nil {
  402. if user_model.IsErrUserNotExist(err) {
  403. if ctx.FormString("go-get") == "1" {
  404. EarlyResponseForGoGetMeta(ctx)
  405. return
  406. }
  407. ctx.NotFound("GetUserByName", nil)
  408. } else {
  409. ctx.ServerError("GetUserByName", err)
  410. }
  411. return
  412. }
  413. }
  414. ctx.Repo.Owner = owner
  415. ctx.ContextUser = owner
  416. ctx.Data["Username"] = ctx.Repo.Owner.Name
  417. // redirect link to wiki
  418. if strings.HasSuffix(repoName, ".wiki") {
  419. // ctx.Req.URL.Path does not have the preceding appSubURL - any redirect must have this added
  420. // Now we happen to know that all of our paths are: /:username/:reponame/whatever_else
  421. originalRepoName := ctx.Params(":reponame")
  422. redirectRepoName := strings.TrimSuffix(repoName, ".wiki")
  423. redirectRepoName += originalRepoName[len(redirectRepoName)+5:]
  424. redirectPath := strings.Replace(
  425. ctx.Req.URL.EscapedPath(),
  426. url.PathEscape(userName)+"/"+url.PathEscape(originalRepoName),
  427. url.PathEscape(userName)+"/"+url.PathEscape(redirectRepoName)+"/wiki",
  428. 1,
  429. )
  430. if ctx.Req.URL.RawQuery != "" {
  431. redirectPath += "?" + ctx.Req.URL.RawQuery
  432. }
  433. ctx.Redirect(path.Join(setting.AppSubURL, redirectPath))
  434. return
  435. }
  436. // Get repository.
  437. repo, err := repo_model.GetRepositoryByName(owner.ID, repoName)
  438. if err != nil {
  439. if repo_model.IsErrRepoNotExist(err) {
  440. redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName)
  441. if err == nil {
  442. RedirectToRepo(ctx, redirectRepoID)
  443. } else if repo_model.IsErrRedirectNotExist(err) {
  444. if ctx.FormString("go-get") == "1" {
  445. EarlyResponseForGoGetMeta(ctx)
  446. return
  447. }
  448. ctx.NotFound("GetRepositoryByName", nil)
  449. } else {
  450. ctx.ServerError("LookupRepoRedirect", err)
  451. }
  452. } else {
  453. ctx.ServerError("GetRepositoryByName", err)
  454. }
  455. return
  456. }
  457. repo.Owner = owner
  458. repoAssignment(ctx, repo)
  459. if ctx.Written() {
  460. return
  461. }
  462. ctx.Repo.RepoLink = repo.Link()
  463. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  464. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  465. unit, err := ctx.Repo.Repository.GetUnit(unit_model.TypeExternalTracker)
  466. if err == nil {
  467. ctx.Data["RepoExternalIssuesLink"] = unit.ExternalTrackerConfig().ExternalTrackerURL
  468. }
  469. ctx.Data["NumTags"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
  470. IncludeTags: true,
  471. })
  472. if err != nil {
  473. ctx.ServerError("GetReleaseCountByRepoID", err)
  474. return
  475. }
  476. ctx.Data["NumReleases"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{})
  477. if err != nil {
  478. ctx.ServerError("GetReleaseCountByRepoID", err)
  479. return
  480. }
  481. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  482. ctx.Data["Repository"] = repo
  483. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  484. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  485. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  486. ctx.Data["RepoOwnerIsOrganization"] = repo.Owner.IsOrganization()
  487. ctx.Data["CanWriteCode"] = ctx.Repo.CanWrite(unit_model.TypeCode)
  488. ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(unit_model.TypeIssues)
  489. ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(unit_model.TypePullRequests)
  490. canSignedUserFork, err := models.CanUserForkRepo(ctx.Doer, ctx.Repo.Repository)
  491. if err != nil {
  492. ctx.ServerError("CanUserForkRepo", err)
  493. return
  494. }
  495. ctx.Data["CanSignedUserFork"] = canSignedUserFork
  496. userAndOrgForks, err := models.GetForksByUserAndOrgs(ctx, ctx.Doer, ctx.Repo.Repository)
  497. if err != nil {
  498. ctx.ServerError("GetForksByUserAndOrgs", err)
  499. return
  500. }
  501. ctx.Data["UserAndOrgForks"] = userAndOrgForks
  502. // canSignedUserFork is true if the current user doesn't have a fork of this repo yet or
  503. // if he owns an org that doesn't have a fork of this repo yet
  504. // If multiple forks are available or if the user can fork to another account, but there is already a fork: open selection dialog
  505. ctx.Data["ShowForkModal"] = len(userAndOrgForks) > 1 || (canSignedUserFork && len(userAndOrgForks) > 0)
  506. ctx.Data["RepoCloneLink"] = repo.CloneLink()
  507. cloneButtonShowHTTPS := !setting.Repository.DisableHTTPGit
  508. cloneButtonShowSSH := !setting.SSH.Disabled && (ctx.IsSigned || setting.SSH.ExposeAnonymous)
  509. if !cloneButtonShowHTTPS && !cloneButtonShowSSH {
  510. // We have to show at least one link, so we just show the HTTPS
  511. cloneButtonShowHTTPS = true
  512. }
  513. ctx.Data["CloneButtonShowHTTPS"] = cloneButtonShowHTTPS
  514. ctx.Data["CloneButtonShowSSH"] = cloneButtonShowSSH
  515. ctx.Data["CloneButtonOriginLink"] = ctx.Data["RepoCloneLink"] // it may be rewritten to the WikiCloneLink by the router middleware
  516. ctx.Data["RepoSearchEnabled"] = setting.Indexer.RepoIndexerEnabled
  517. if setting.Indexer.RepoIndexerEnabled {
  518. ctx.Data["CodeIndexerUnavailable"] = !code_indexer.IsAvailable()
  519. }
  520. if ctx.IsSigned {
  521. ctx.Data["IsWatchingRepo"] = repo_model.IsWatching(ctx.Doer.ID, repo.ID)
  522. ctx.Data["IsStaringRepo"] = repo_model.IsStaring(ctx.Doer.ID, repo.ID)
  523. }
  524. if repo.IsFork {
  525. RetrieveBaseRepo(ctx, repo)
  526. if ctx.Written() {
  527. return
  528. }
  529. }
  530. if repo.IsGenerated() {
  531. RetrieveTemplateRepo(ctx, repo)
  532. if ctx.Written() {
  533. return
  534. }
  535. }
  536. isHomeOrSettings := ctx.Link == ctx.Repo.RepoLink || ctx.Link == ctx.Repo.RepoLink+"/settings" || strings.HasPrefix(ctx.Link, ctx.Repo.RepoLink+"/settings/")
  537. // Disable everything when the repo is being created
  538. if ctx.Repo.Repository.IsBeingCreated() || ctx.Repo.Repository.IsBroken() {
  539. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  540. if !isHomeOrSettings {
  541. ctx.Redirect(ctx.Repo.RepoLink)
  542. }
  543. return
  544. }
  545. gitRepo, err := git.OpenRepository(ctx, repo_model.RepoPath(userName, repoName))
  546. if err != nil {
  547. if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "no such file or directory") {
  548. log.Error("Repository %-v has a broken repository on the file system: %s Error: %v", ctx.Repo.Repository, ctx.Repo.Repository.RepoPath(), err)
  549. ctx.Repo.Repository.Status = repo_model.RepositoryBroken
  550. ctx.Repo.Repository.IsEmpty = true
  551. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  552. // Only allow access to base of repo or settings
  553. if !isHomeOrSettings {
  554. ctx.Redirect(ctx.Repo.RepoLink)
  555. }
  556. return
  557. }
  558. ctx.ServerError("RepoAssignment Invalid repo "+repo_model.RepoPath(userName, repoName), err)
  559. return
  560. }
  561. if ctx.Repo.GitRepo != nil {
  562. ctx.Repo.GitRepo.Close()
  563. }
  564. ctx.Repo.GitRepo = gitRepo
  565. // We opened it, we should close it
  566. cancel = func() {
  567. // If it's been set to nil then assume someone else has closed it.
  568. if ctx.Repo.GitRepo != nil {
  569. ctx.Repo.GitRepo.Close()
  570. }
  571. }
  572. // Stop at this point when the repo is empty.
  573. if ctx.Repo.Repository.IsEmpty {
  574. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  575. return
  576. }
  577. tags, err := ctx.Repo.GitRepo.GetTags(0, 0)
  578. if err != nil {
  579. if strings.Contains(err.Error(), "fatal: not a git repository ") {
  580. log.Error("Repository %-v has a broken repository on the file system: %s Error: %v", ctx.Repo.Repository, ctx.Repo.Repository.RepoPath(), err)
  581. ctx.Repo.Repository.Status = repo_model.RepositoryBroken
  582. ctx.Repo.Repository.IsEmpty = true
  583. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  584. // Only allow access to base of repo or settings
  585. if !isHomeOrSettings {
  586. ctx.Redirect(ctx.Repo.RepoLink)
  587. }
  588. return
  589. }
  590. ctx.ServerError("GetTags", err)
  591. return
  592. }
  593. ctx.Data["Tags"] = tags
  594. brs, _, err := ctx.Repo.GitRepo.GetBranchNames(0, 0)
  595. if err != nil {
  596. ctx.ServerError("GetBranches", err)
  597. return
  598. }
  599. ctx.Data["Branches"] = brs
  600. ctx.Data["BranchesCount"] = len(brs)
  601. // If not branch selected, try default one.
  602. // If default branch doesn't exists, fall back to some other branch.
  603. if len(ctx.Repo.BranchName) == 0 {
  604. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  605. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  606. } else if len(brs) > 0 {
  607. ctx.Repo.BranchName = brs[0]
  608. }
  609. ctx.Repo.RefName = ctx.Repo.BranchName
  610. }
  611. ctx.Data["BranchName"] = ctx.Repo.BranchName
  612. // People who have push access or have forked repository can propose a new pull request.
  613. canPush := ctx.Repo.CanWrite(unit_model.TypeCode) ||
  614. (ctx.IsSigned && repo_model.HasForkedRepo(ctx.Doer.ID, ctx.Repo.Repository.ID))
  615. canCompare := false
  616. // Pull request is allowed if this is a fork repository
  617. // and base repository accepts pull requests.
  618. if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
  619. canCompare = true
  620. ctx.Data["BaseRepo"] = repo.BaseRepo
  621. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  622. ctx.Repo.PullRequest.Allowed = canPush
  623. ctx.Repo.PullRequest.HeadInfoSubURL = url.PathEscape(ctx.Repo.Owner.Name) + ":" + util.PathEscapeSegments(ctx.Repo.BranchName)
  624. } else if repo.AllowsPulls() {
  625. // Or, this is repository accepts pull requests between branches.
  626. canCompare = true
  627. ctx.Data["BaseRepo"] = repo
  628. ctx.Repo.PullRequest.BaseRepo = repo
  629. ctx.Repo.PullRequest.Allowed = canPush
  630. ctx.Repo.PullRequest.SameRepo = true
  631. ctx.Repo.PullRequest.HeadInfoSubURL = util.PathEscapeSegments(ctx.Repo.BranchName)
  632. }
  633. ctx.Data["CanCompareOrPull"] = canCompare
  634. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  635. if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer {
  636. repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository)
  637. if err != nil {
  638. ctx.ServerError("GetPendingRepositoryTransfer", err)
  639. return
  640. }
  641. if err := repoTransfer.LoadAttributes(); err != nil {
  642. ctx.ServerError("LoadRecipient", err)
  643. return
  644. }
  645. ctx.Data["RepoTransfer"] = repoTransfer
  646. if ctx.Doer != nil {
  647. ctx.Data["CanUserAcceptTransfer"] = repoTransfer.CanUserAcceptTransfer(ctx.Doer)
  648. }
  649. }
  650. if ctx.FormString("go-get") == "1" {
  651. ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
  652. prefix := repo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(ctx.Repo.BranchName)
  653. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  654. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  655. }
  656. return
  657. }
  658. // RepoRefType type of repo reference
  659. type RepoRefType int
  660. const (
  661. // RepoRefLegacy unknown type, make educated guess and redirect.
  662. // for backward compatibility with previous URL scheme
  663. RepoRefLegacy RepoRefType = iota
  664. // RepoRefAny is for usage where educated guess is needed
  665. // but redirect can not be made
  666. RepoRefAny
  667. // RepoRefBranch branch
  668. RepoRefBranch
  669. // RepoRefTag tag
  670. RepoRefTag
  671. // RepoRefCommit commit
  672. RepoRefCommit
  673. // RepoRefBlob blob
  674. RepoRefBlob
  675. )
  676. // RepoRef handles repository reference names when the ref name is not
  677. // explicitly given
  678. func RepoRef() func(*Context) context.CancelFunc {
  679. // since no ref name is explicitly specified, ok to just use branch
  680. return RepoRefByType(RepoRefBranch)
  681. }
  682. // RefTypeIncludesBranches returns true if ref type can be a branch
  683. func (rt RepoRefType) RefTypeIncludesBranches() bool {
  684. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefBranch {
  685. return true
  686. }
  687. return false
  688. }
  689. // RefTypeIncludesTags returns true if ref type can be a tag
  690. func (rt RepoRefType) RefTypeIncludesTags() bool {
  691. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefTag {
  692. return true
  693. }
  694. return false
  695. }
  696. func getRefNameFromPath(ctx *Context, path string, isExist func(string) bool) string {
  697. refName := ""
  698. parts := strings.Split(path, "/")
  699. for i, part := range parts {
  700. refName = strings.TrimPrefix(refName+"/"+part, "/")
  701. if isExist(refName) {
  702. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  703. return refName
  704. }
  705. }
  706. return ""
  707. }
  708. func getRefName(ctx *Context, pathType RepoRefType) string {
  709. path := ctx.Params("*")
  710. switch pathType {
  711. case RepoRefLegacy, RepoRefAny:
  712. if refName := getRefName(ctx, RepoRefBranch); len(refName) > 0 {
  713. return refName
  714. }
  715. if refName := getRefName(ctx, RepoRefTag); len(refName) > 0 {
  716. return refName
  717. }
  718. // For legacy and API support only full commit sha
  719. parts := strings.Split(path, "/")
  720. if len(parts) > 0 && len(parts[0]) == 40 {
  721. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  722. return parts[0]
  723. }
  724. if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 {
  725. return refName
  726. }
  727. ctx.Repo.TreePath = path
  728. return ctx.Repo.Repository.DefaultBranch
  729. case RepoRefBranch:
  730. ref := getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsBranchExist)
  731. if len(ref) == 0 {
  732. // maybe it's a renamed branch
  733. return getRefNameFromPath(ctx, path, func(s string) bool {
  734. b, exist, err := models.FindRenamedBranch(ctx.Repo.Repository.ID, s)
  735. if err != nil {
  736. log.Error("FindRenamedBranch", err)
  737. return false
  738. }
  739. if !exist {
  740. return false
  741. }
  742. ctx.Data["IsRenamedBranch"] = true
  743. ctx.Data["RenamedBranchName"] = b.To
  744. return true
  745. })
  746. }
  747. return ref
  748. case RepoRefTag:
  749. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist)
  750. case RepoRefCommit:
  751. parts := strings.Split(path, "/")
  752. if len(parts) > 0 && len(parts[0]) >= 7 && len(parts[0]) <= 40 {
  753. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  754. return parts[0]
  755. }
  756. case RepoRefBlob:
  757. _, err := ctx.Repo.GitRepo.GetBlob(path)
  758. if err != nil {
  759. return ""
  760. }
  761. return path
  762. default:
  763. log.Error("Unrecognized path type: %v", path)
  764. }
  765. return ""
  766. }
  767. // RepoRefByType handles repository reference name for a specific type
  768. // of repository reference
  769. func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context) context.CancelFunc {
  770. return func(ctx *Context) (cancel context.CancelFunc) {
  771. // Empty repository does not have reference information.
  772. if ctx.Repo.Repository.IsEmpty {
  773. return
  774. }
  775. var (
  776. refName string
  777. err error
  778. )
  779. if ctx.Repo.GitRepo == nil {
  780. repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  781. ctx.Repo.GitRepo, err = git.OpenRepository(ctx, repoPath)
  782. if err != nil {
  783. ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
  784. return
  785. }
  786. // We opened it, we should close it
  787. cancel = func() {
  788. // If it's been set to nil then assume someone else has closed it.
  789. if ctx.Repo.GitRepo != nil {
  790. ctx.Repo.GitRepo.Close()
  791. }
  792. }
  793. }
  794. // Get default branch.
  795. if len(ctx.Params("*")) == 0 {
  796. refName = ctx.Repo.Repository.DefaultBranch
  797. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  798. brs, _, err := ctx.Repo.GitRepo.GetBranchNames(0, 0)
  799. if err != nil {
  800. ctx.ServerError("GetBranches", err)
  801. return
  802. } else if len(brs) == 0 {
  803. err = fmt.Errorf("No branches in non-empty repository %s",
  804. ctx.Repo.GitRepo.Path)
  805. ctx.ServerError("GetBranches", err)
  806. return
  807. }
  808. refName = brs[0]
  809. }
  810. ctx.Repo.RefName = refName
  811. ctx.Repo.BranchName = refName
  812. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  813. if err != nil {
  814. ctx.ServerError("GetBranchCommit", err)
  815. return
  816. }
  817. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  818. ctx.Repo.IsViewBranch = true
  819. } else {
  820. refName = getRefName(ctx, refType)
  821. ctx.Repo.RefName = refName
  822. isRenamedBranch, has := ctx.Data["IsRenamedBranch"].(bool)
  823. if isRenamedBranch && has {
  824. renamedBranchName := ctx.Data["RenamedBranchName"].(string)
  825. ctx.Flash.Info(ctx.Tr("repo.branch.renamed", refName, renamedBranchName))
  826. link := setting.AppSubURL + strings.Replace(ctx.Req.URL.EscapedPath(), util.PathEscapeSegments(refName), util.PathEscapeSegments(renamedBranchName), 1)
  827. ctx.Redirect(link)
  828. return
  829. }
  830. if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) {
  831. ctx.Repo.IsViewBranch = true
  832. ctx.Repo.BranchName = refName
  833. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  834. if err != nil {
  835. ctx.ServerError("GetBranchCommit", err)
  836. return
  837. }
  838. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  839. } else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) {
  840. ctx.Repo.IsViewTag = true
  841. ctx.Repo.TagName = refName
  842. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  843. if err != nil {
  844. ctx.ServerError("GetTagCommit", err)
  845. return
  846. }
  847. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  848. } else if len(refName) >= 7 && len(refName) <= 40 {
  849. ctx.Repo.IsViewCommit = true
  850. ctx.Repo.CommitID = refName
  851. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  852. if err != nil {
  853. ctx.NotFound("GetCommit", err)
  854. return
  855. }
  856. // If short commit ID add canonical link header
  857. if len(refName) < 40 {
  858. ctx.RespHeader().Set("Link", fmt.Sprintf("<%s>; rel=\"canonical\"",
  859. util.URLJoin(setting.AppURL, strings.Replace(ctx.Req.URL.RequestURI(), util.PathEscapeSegments(refName), url.PathEscape(ctx.Repo.Commit.ID.String()), 1))))
  860. }
  861. } else {
  862. if len(ignoreNotExistErr) > 0 && ignoreNotExistErr[0] {
  863. return
  864. }
  865. ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  866. return
  867. }
  868. if refType == RepoRefLegacy {
  869. // redirect from old URL scheme to new URL scheme
  870. prefix := strings.TrimPrefix(setting.AppSubURL+strings.ToLower(strings.TrimSuffix(ctx.Req.URL.Path, ctx.Params("*"))), strings.ToLower(ctx.Repo.RepoLink))
  871. ctx.Redirect(path.Join(
  872. ctx.Repo.RepoLink,
  873. util.PathEscapeSegments(prefix),
  874. ctx.Repo.BranchNameSubURL(),
  875. util.PathEscapeSegments(ctx.Repo.TreePath)))
  876. return
  877. }
  878. }
  879. ctx.Data["BranchName"] = ctx.Repo.BranchName
  880. ctx.Data["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
  881. ctx.Data["TagName"] = ctx.Repo.TagName
  882. ctx.Data["CommitID"] = ctx.Repo.CommitID
  883. ctx.Data["TreePath"] = ctx.Repo.TreePath
  884. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  885. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  886. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  887. ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
  888. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  889. if err != nil {
  890. ctx.ServerError("GetCommitsCount", err)
  891. return
  892. }
  893. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  894. return
  895. }
  896. }
  897. // GitHookService checks if repository Git hooks service has been enabled.
  898. func GitHookService() func(ctx *Context) {
  899. return func(ctx *Context) {
  900. if !ctx.Doer.CanEditGitHook() {
  901. ctx.NotFound("GitHookService", nil)
  902. return
  903. }
  904. }
  905. }
  906. // UnitTypes returns a middleware to set unit types to context variables.
  907. func UnitTypes() func(ctx *Context) {
  908. return func(ctx *Context) {
  909. ctx.Data["UnitTypeCode"] = unit_model.TypeCode
  910. ctx.Data["UnitTypeIssues"] = unit_model.TypeIssues
  911. ctx.Data["UnitTypePullRequests"] = unit_model.TypePullRequests
  912. ctx.Data["UnitTypeReleases"] = unit_model.TypeReleases
  913. ctx.Data["UnitTypeWiki"] = unit_model.TypeWiki
  914. ctx.Data["UnitTypeExternalWiki"] = unit_model.TypeExternalWiki
  915. ctx.Data["UnitTypeExternalTracker"] = unit_model.TypeExternalTracker
  916. ctx.Data["UnitTypeProjects"] = unit_model.TypeProjects
  917. ctx.Data["UnitTypePackages"] = unit_model.TypePackages
  918. }
  919. }
  920. // IssueTemplatesFromDefaultBranch checks for issue templates in the repo's default branch
  921. func (ctx *Context) IssueTemplatesFromDefaultBranch() []api.IssueTemplate {
  922. var issueTemplates []api.IssueTemplate
  923. if ctx.Repo.Repository.IsEmpty {
  924. return issueTemplates
  925. }
  926. if ctx.Repo.Commit == nil {
  927. var err error
  928. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  929. if err != nil {
  930. return issueTemplates
  931. }
  932. }
  933. for _, dirName := range IssueTemplateDirCandidates {
  934. tree, err := ctx.Repo.Commit.SubTree(dirName)
  935. if err != nil {
  936. continue
  937. }
  938. entries, err := tree.ListEntries()
  939. if err != nil {
  940. return issueTemplates
  941. }
  942. for _, entry := range entries {
  943. if strings.HasSuffix(entry.Name(), ".md") {
  944. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  945. log.Debug("Issue template is too large: %s", entry.Name())
  946. continue
  947. }
  948. r, err := entry.Blob().DataAsync()
  949. if err != nil {
  950. log.Debug("DataAsync: %v", err)
  951. continue
  952. }
  953. closed := false
  954. defer func() {
  955. if !closed {
  956. _ = r.Close()
  957. }
  958. }()
  959. data, err := io.ReadAll(r)
  960. if err != nil {
  961. log.Debug("ReadAll: %v", err)
  962. continue
  963. }
  964. _ = r.Close()
  965. var it api.IssueTemplate
  966. content, err := markdown.ExtractMetadata(string(data), &it)
  967. if err != nil {
  968. log.Debug("ExtractMetadata: %v", err)
  969. continue
  970. }
  971. it.Content = content
  972. it.FileName = entry.Name()
  973. if it.Valid() {
  974. issueTemplates = append(issueTemplates, it)
  975. }
  976. }
  977. }
  978. if len(issueTemplates) > 0 {
  979. return issueTemplates
  980. }
  981. }
  982. return issueTemplates
  983. }