|
| 1 | +// Copyright 2024 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package markup |
| 5 | + |
| 6 | +import ( |
| 7 | + "html/template" |
| 8 | + "net/url" |
| 9 | + "regexp" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "code.gitea.io/gitea/modules/httplib" |
| 14 | + |
| 15 | + "golang.org/x/net/html" |
| 16 | +) |
| 17 | + |
| 18 | +// codePreviewPattern matches "http://domain/.../{owner}/{repo}/src/commit/{commit}/{filepath}#L10-L20" |
| 19 | +var codePreviewPattern = regexp.MustCompile(`https?://\S+/([^\s/]+)/([^\s/]+)/src/commit/([0-9a-f]{7,64})(/\S+)#(L\d+(-L\d+)?)`) |
| 20 | + |
| 21 | +type RenderCodePreviewOptions struct { |
| 22 | + FullURL string |
| 23 | + OwnerName string |
| 24 | + RepoName string |
| 25 | + CommitID string |
| 26 | + FilePath string |
| 27 | + |
| 28 | + LineStart, LineStop int |
| 29 | +} |
| 30 | + |
| 31 | +func renderCodeBlock(ctx *RenderContext, node *html.Node) (urlPosStart, urlPosStop int, htm template.HTML, err error) { |
| 32 | + m := codePreviewPattern.FindStringSubmatchIndex(node.Data) |
| 33 | + if m == nil { |
| 34 | + return 0, 0, "", nil |
| 35 | + } |
| 36 | + |
| 37 | + opts := RenderCodePreviewOptions{ |
| 38 | + FullURL: node.Data[m[0]:m[1]], |
| 39 | + OwnerName: node.Data[m[2]:m[3]], |
| 40 | + RepoName: node.Data[m[4]:m[5]], |
| 41 | + CommitID: node.Data[m[6]:m[7]], |
| 42 | + FilePath: node.Data[m[8]:m[9]], |
| 43 | + } |
| 44 | + if !httplib.IsCurrentGiteaSiteURL(opts.FullURL) { |
| 45 | + return 0, 0, "", nil |
| 46 | + } |
| 47 | + u, err := url.Parse(opts.FilePath) |
| 48 | + if err != nil { |
| 49 | + return 0, 0, "", err |
| 50 | + } |
| 51 | + opts.FilePath = strings.TrimPrefix(u.Path, "/") |
| 52 | + |
| 53 | + lineStartStr, lineStopStr, _ := strings.Cut(node.Data[m[10]:m[11]], "-") |
| 54 | + lineStart, _ := strconv.Atoi(strings.TrimPrefix(lineStartStr, "L")) |
| 55 | + lineStop, _ := strconv.Atoi(strings.TrimPrefix(lineStopStr, "L")) |
| 56 | + opts.LineStart, opts.LineStop = lineStart, lineStop |
| 57 | + h, err := DefaultProcessorHelper.RenderRepoFileCodePreview(ctx.Ctx, opts) |
| 58 | + return m[0], m[1], h, err |
| 59 | +} |
| 60 | + |
| 61 | +func codePreviewPatternProcessor(ctx *RenderContext, node *html.Node) { |
| 62 | + for node != nil { |
| 63 | + urlPosStart, urlPosEnd, h, err := renderCodeBlock(ctx, node) |
| 64 | + if err != nil || h == "" { |
| 65 | + node = node.NextSibling |
| 66 | + continue |
| 67 | + } |
| 68 | + next := node.NextSibling |
| 69 | + nodeText := node.Data |
| 70 | + node.Data = nodeText[:urlPosStart] |
| 71 | + node.Parent.InsertBefore(&html.Node{Type: html.RawNode, Data: string(h)}, next) |
| 72 | + node.Parent.InsertBefore(&html.Node{Type: html.TextNode, Data: nodeText[urlPosEnd:]}, next) |
| 73 | + node = next |
| 74 | + } |
| 75 | +} |
0 commit comments