gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package markup
  4. import (
  5. "context"
  6. "strings"
  7. "code.gitea.io/gitea/modules/httplib"
  8. "code.gitea.io/gitea/modules/setting"
  9. "code.gitea.io/gitea/modules/util"
  10. )
  11. func resolveLinkRelative(ctx context.Context, base, cur, link string, absolute bool) (finalLink string) {
  12. if IsFullURLString(link) {
  13. return link
  14. }
  15. if strings.HasPrefix(link, "/") {
  16. if strings.HasPrefix(link, base) && strings.Count(base, "/") >= 4 {
  17. // a trick to tolerate that some users were using absolute paths (the old gitea's behavior)
  18. finalLink = link
  19. } else {
  20. finalLink = util.URLJoin(base, "./", link)
  21. }
  22. } else {
  23. finalLink = util.URLJoin(base, "./", cur, link)
  24. }
  25. finalLink = strings.TrimSuffix(finalLink, "/")
  26. if absolute {
  27. finalLink = httplib.MakeAbsoluteURL(ctx, finalLink)
  28. }
  29. return finalLink
  30. }
  31. func (ctx *RenderContext) ResolveLinkRelative(base, cur, link string) string {
  32. if strings.HasPrefix(link, "/:") {
  33. setting.PanicInDevOrTesting("invalid link %q, forgot to cut?", link)
  34. }
  35. return resolveLinkRelative(ctx, base, cur, link, ctx.RenderOptions.UseAbsoluteLink)
  36. }
  37. func (ctx *RenderContext) ResolveLinkRoot(link string) string {
  38. return ctx.ResolveLinkRelative(setting.AppSubURL+"/", "", link)
  39. }
  40. func ParseRenderedLink(s, preferLinkType string) (linkType, link string) {
  41. if strings.HasPrefix(s, "/:") {
  42. p := strings.IndexByte(s[1:], '/')
  43. if p == -1 {
  44. return s, ""
  45. }
  46. return s[:p+1], s[p+2:]
  47. }
  48. return preferLinkType, s
  49. }