|
| 1 | +// Copyright 2024 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package renderhelper |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "html/template" |
| 9 | + "path" |
| 10 | + |
| 11 | + repo_model "code.gitea.io/gitea/models/repo" |
| 12 | + "code.gitea.io/gitea/modules/markup" |
| 13 | + "code.gitea.io/gitea/modules/util" |
| 14 | +) |
| 15 | + |
| 16 | +type RepoFile struct { |
| 17 | + ctx *markup.RenderContext |
| 18 | + opts RepoFileOptions |
| 19 | + repo *repo_model.Repository |
| 20 | + |
| 21 | + commitChecker *commitChecker |
| 22 | + repoLink string |
| 23 | +} |
| 24 | + |
| 25 | +func (r *RepoFile) CleanUp() { |
| 26 | + _ = r.commitChecker.Close() |
| 27 | +} |
| 28 | + |
| 29 | +func (r *RepoFile) IsUsernameMentionable(username string) bool { |
| 30 | + return markup.DefaultRenderHelperFuncs.IsUsernameMentionable(r.ctx, username) |
| 31 | +} |
| 32 | + |
| 33 | +func (r *RepoFile) IsCommitIDExisting(commitID string) bool { |
| 34 | + return r.commitChecker.IsCommitIDExisting(commitID) |
| 35 | +} |
| 36 | + |
| 37 | +func (r *RepoFile) RenderRepoFileCodePreview(options markup.RenderCodePreviewOptions) (template.HTML, error) { |
| 38 | + return "", nil |
| 39 | +} |
| 40 | + |
| 41 | +func (r *RepoFile) ResolveLink(link string, likeType markup.LinkType) string { |
| 42 | + finalLink := link |
| 43 | + switch likeType { |
| 44 | + case markup.LinkTypeApp: |
| 45 | + finalLink = r.ctx.ResolveLinkApp(link) |
| 46 | + case markup.LinkTypeDefault: |
| 47 | + finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "src", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link) |
| 48 | + case markup.LinkTypeRaw: |
| 49 | + finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "raw", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link) |
| 50 | + case markup.LinkTypeMedia: |
| 51 | + finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "media", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link) |
| 52 | + } |
| 53 | + return finalLink |
| 54 | +} |
| 55 | + |
| 56 | +var _ markup.RenderHelper = (*RepoFile)(nil) |
| 57 | + |
| 58 | +type RepoFileOptions struct { |
| 59 | + CurrentRefPath string // eg: "branch/main" |
| 60 | + CurrentTreePath string // eg: "path/to/file" in the repo |
| 61 | +} |
| 62 | + |
| 63 | +func NewRenderContextRepoFile(ctx context.Context, repo *repo_model.Repository, opts ...RepoFileOptions) *markup.RenderContext { |
| 64 | + helper := &RepoFile{ |
| 65 | + repo: repo, |
| 66 | + repoLink: repo.Link(), |
| 67 | + opts: util.OptionalArg(opts), |
| 68 | + commitChecker: newCommitChecker(ctx, repo), |
| 69 | + } |
| 70 | + rctx := markup.NewRenderContext(ctx).WithHelper(helper).WithMetas(markup.ComposeSimpleDocumentMetas()) |
| 71 | + helper.ctx = rctx |
| 72 | + return rctx |
| 73 | +} |
0 commit comments