gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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/markup/markdown"
  11. "code.gitea.io/gitea/modules/util"
  12. )
  13. type RepoWiki struct {
  14. ctx *markup.RenderContext
  15. opts RepoWikiOptions
  16. commitChecker *commitChecker
  17. repoLink string
  18. }
  19. func (r *RepoWiki) CleanUp() {
  20. _ = r.commitChecker.Close()
  21. }
  22. func (r *RepoWiki) IsCommitIDExisting(commitID string) bool {
  23. return r.commitChecker.IsCommitIDExisting(commitID)
  24. }
  25. func (r *RepoWiki) ResolveLink(link, preferLinkType string) (finalLink string) {
  26. linkType, link := markup.ParseRenderedLink(link, preferLinkType)
  27. switch linkType {
  28. case markup.LinkTypeRoot:
  29. finalLink = r.ctx.ResolveLinkRoot(link)
  30. case markup.LinkTypeMedia, markup.LinkTypeRaw:
  31. finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "wiki/raw", r.opts.currentRefPath), r.opts.currentTreePath, link)
  32. default:
  33. finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "wiki", r.opts.currentRefPath), r.opts.currentTreePath, link)
  34. }
  35. return finalLink
  36. }
  37. var _ markup.RenderHelper = (*RepoWiki)(nil)
  38. type RepoWikiOptions struct {
  39. DeprecatedRepoName string // it is only a patch for the non-standard "markup" api
  40. DeprecatedOwnerName string // it is only a patch for the non-standard "markup" api
  41. // these options are not used at the moment because Wiki doesn't support sub-path, nor branch
  42. currentRefPath string // eg: "branch/main"
  43. currentTreePath string // eg: "path/to/file" in the repo
  44. }
  45. func NewRenderContextRepoWiki(ctx context.Context, repo *repo_model.Repository, opts ...RepoWikiOptions) *markup.RenderContext {
  46. helper := &RepoWiki{opts: util.OptionalArg(opts)}
  47. rctx := markup.NewRenderContext(ctx).WithMarkupType(markdown.MarkupName)
  48. if repo != nil {
  49. helper.repoLink = repo.Link()
  50. helper.commitChecker = newCommitChecker(ctx, repo)
  51. rctx = rctx.WithMetas(repo.ComposeWikiMetas(ctx))
  52. } else {
  53. // this is almost dead code, only to pass the incorrect tests
  54. helper.repoLink = fmt.Sprintf("%s/%s", helper.opts.DeprecatedOwnerName, helper.opts.DeprecatedRepoName)
  55. rctx = rctx.WithMetas(map[string]string{
  56. "user": helper.opts.DeprecatedOwnerName,
  57. "repo": helper.opts.DeprecatedRepoName,
  58. "markupAllowShortIssuePattern": "true",
  59. })
  60. }
  61. rctx = rctx.WithHelper(helper)
  62. helper.ctx = rctx
  63. return rctx
  64. }