gitea源码

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package renderhelper
  4. import (
  5. "context"
  6. "fmt"
  7. "path"
  8. repo_model "code.gitea.io/gitea/models/repo"
  9. "code.gitea.io/gitea/modules/markup"
  10. "code.gitea.io/gitea/modules/util"
  11. )
  12. type RepoFile struct {
  13. ctx *markup.RenderContext
  14. opts RepoFileOptions
  15. commitChecker *commitChecker
  16. repoLink string
  17. }
  18. func (r *RepoFile) CleanUp() {
  19. _ = r.commitChecker.Close()
  20. }
  21. func (r *RepoFile) IsCommitIDExisting(commitID string) bool {
  22. return r.commitChecker.IsCommitIDExisting(commitID)
  23. }
  24. func (r *RepoFile) ResolveLink(link, preferLinkType string) (finalLink string) {
  25. linkType, link := markup.ParseRenderedLink(link, preferLinkType)
  26. switch linkType {
  27. case markup.LinkTypeRoot:
  28. finalLink = r.ctx.ResolveLinkRoot(link)
  29. case markup.LinkTypeRaw:
  30. finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "raw", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link)
  31. case markup.LinkTypeMedia:
  32. finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "media", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link)
  33. default:
  34. finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "src", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link)
  35. }
  36. return finalLink
  37. }
  38. var _ markup.RenderHelper = (*RepoFile)(nil)
  39. type RepoFileOptions struct {
  40. DeprecatedRepoName string // it is only a patch for the non-standard "markup" api
  41. DeprecatedOwnerName string // it is only a patch for the non-standard "markup" api
  42. CurrentRefPath string // eg: "branch/main"
  43. CurrentTreePath string // eg: "path/to/file" in the repo
  44. }
  45. func NewRenderContextRepoFile(ctx context.Context, repo *repo_model.Repository, opts ...RepoFileOptions) *markup.RenderContext {
  46. helper := &RepoFile{opts: util.OptionalArg(opts)}
  47. rctx := markup.NewRenderContext(ctx)
  48. helper.ctx = rctx
  49. if repo != nil {
  50. helper.repoLink = repo.Link()
  51. helper.commitChecker = newCommitChecker(ctx, repo)
  52. rctx = rctx.WithMetas(repo.ComposeRepoFileMetas(ctx))
  53. } else {
  54. // this is almost dead code, only to pass the incorrect tests
  55. helper.repoLink = fmt.Sprintf("%s/%s", helper.opts.DeprecatedOwnerName, helper.opts.DeprecatedRepoName)
  56. rctx = rctx.WithMetas(map[string]string{
  57. "user": helper.opts.DeprecatedOwnerName,
  58. "repo": helper.opts.DeprecatedRepoName,
  59. })
  60. }
  61. rctx = rctx.WithHelper(helper)
  62. return rctx
  63. }