Files
Atay-Makhzan/modules/markup/render.go
T

366 lines
11 KiB
Go
Raw Normal View History

2024-11-04 18:59:50 +08:00
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package markup
import (
2026-01-26 10:34:38 +08:00
"bytes"
2024-11-04 18:59:50 +08:00
"context"
"fmt"
2025-10-23 16:01:38 +08:00
"html/template"
2024-11-04 18:59:50 +08:00
"io"
"net/url"
2025-04-05 11:56:48 +08:00
"strconv"
2024-11-04 18:59:50 +08:00
"strings"
2024-11-22 13:48:09 +08:00
"time"
2024-11-04 18:59:50 +08:00
2025-10-23 16:01:38 +08:00
"code.gitea.io/gitea/modules/htmlutil"
2024-11-18 13:25:42 +08:00
"code.gitea.io/gitea/modules/markup/internal"
2026-03-29 12:24:30 +02:00
"code.gitea.io/gitea/modules/public"
2024-11-04 18:59:50 +08:00
"code.gitea.io/gitea/modules/setting"
2026-01-26 10:34:38 +08:00
"code.gitea.io/gitea/modules/typesniffer"
2024-11-04 18:59:50 +08:00
"code.gitea.io/gitea/modules/util"
2024-11-18 13:25:42 +08:00
"golang.org/x/sync/errgroup"
2024-11-04 18:59:50 +08:00
)
type RenderMetaMode string
const (
RenderMetaAsDetails RenderMetaMode = "details" // default
RenderMetaAsNone RenderMetaMode = "none"
RenderMetaAsTable RenderMetaMode = "table"
)
2024-11-14 13:02:11 +08:00
var RenderBehaviorForTesting struct {
2024-11-24 16:18:57 +08:00
// Gitea will emit some additional attributes for various purposes, these attributes don't affect rendering.
2024-11-14 13:02:11 +08:00
// But there are too many hard-coded test cases, to avoid changing all of them again and again, we can disable emitting these internal attributes.
2024-11-24 16:18:57 +08:00
DisableAdditionalAttributes bool
2024-11-14 13:02:11 +08:00
}
type WebThemeInterface interface {
PublicAssetURI() string
}
type StandalonePageOptions struct {
CurrentWebTheme WebThemeInterface
}
2024-11-22 13:48:09 +08:00
type RenderOptions struct {
2024-11-24 16:18:57 +08:00
UseAbsoluteLink bool
2024-11-22 13:48:09 +08:00
// relative path from tree root of the branch
RelativePath string
2024-11-14 13:02:11 +08:00
// eg: "orgmode", "asciicast", "console"
// for file mode, it could be left as empty, and will be detected by file extension in RelativePath
MarkupType string
// user&repo, format&style&regexp (for external issue pattern), teams&org (for mention)
2025-01-12 11:39:46 +08:00
// RefTypeNameSubURL (for iframe&asciicast)
2024-11-24 16:18:57 +08:00
// markupAllowShortIssuePattern
2025-04-05 11:56:48 +08:00
// markdownNewLineHardBreak
Metas map[string]string
2024-11-14 13:02:11 +08:00
2024-11-22 13:48:09 +08:00
// used by external render. the router "/org/repo/render/..." will output the rendered content in a standalone page
StandalonePageOptions *StandalonePageOptions
// EnableHeadingIDGeneration controls whether to auto-generate IDs for HTML headings without id attribute.
// This should be enabled for repository files and wiki pages, but disabled for comments to avoid duplicate IDs.
EnableHeadingIDGeneration bool
2024-11-22 13:48:09 +08:00
}
type TocShowInSectionType string
const (
TocShowInSidebar TocShowInSectionType = "sidebar"
TocShowInMain TocShowInSectionType = "main"
)
type TocHeadingItem struct {
HeadingLevel int
AnchorID string
InnerText string
}
2024-11-22 13:48:09 +08:00
// RenderContext represents a render context
type RenderContext struct {
ctx context.Context
2024-11-18 13:25:42 +08:00
// the context might be used by the "render" function, but it might also be used by "postProcess" function
usedByRender bool
TocShowInSection TocShowInSectionType
TocHeadingItems []*TocHeadingItem
2024-11-22 13:48:09 +08:00
RenderHelper RenderHelper
RenderOptions RenderOptions
2024-11-18 13:25:42 +08:00
RenderInternal internal.RenderInternal
2024-11-04 18:59:50 +08:00
}
2024-11-22 13:48:09 +08:00
func (ctx *RenderContext) Deadline() (deadline time.Time, ok bool) {
return ctx.ctx.Deadline()
}
func (ctx *RenderContext) Done() <-chan struct{} {
return ctx.ctx.Done()
}
func (ctx *RenderContext) Err() error {
return ctx.ctx.Err()
}
func (ctx *RenderContext) Value(key any) any {
return ctx.ctx.Value(key)
}
var _ context.Context = (*RenderContext)(nil)
func NewRenderContext(ctx context.Context) *RenderContext {
2024-11-24 16:18:57 +08:00
return &RenderContext{ctx: ctx, RenderHelper: &SimpleRenderHelper{}}
2024-11-22 13:48:09 +08:00
}
func (ctx *RenderContext) WithMarkupType(typ string) *RenderContext {
ctx.RenderOptions.MarkupType = typ
return ctx
}
func (ctx *RenderContext) WithRelativePath(path string) *RenderContext {
ctx.RenderOptions.RelativePath = path
return ctx
}
func (ctx *RenderContext) WithMetas(metas map[string]string) *RenderContext {
ctx.RenderOptions.Metas = metas
return ctx
}
func (ctx *RenderContext) WithStandalonePage(opts StandalonePageOptions) *RenderContext {
ctx.RenderOptions.StandalonePageOptions = &opts
return ctx
}
func (ctx *RenderContext) WithEnableHeadingIDGeneration(v bool) *RenderContext {
ctx.RenderOptions.EnableHeadingIDGeneration = v
2024-11-22 13:48:09 +08:00
return ctx
}
2024-11-24 16:18:57 +08:00
func (ctx *RenderContext) WithUseAbsoluteLink(v bool) *RenderContext {
ctx.RenderOptions.UseAbsoluteLink = v
2024-11-22 13:48:09 +08:00
return ctx
}
2024-11-24 16:18:57 +08:00
func (ctx *RenderContext) WithHelper(helper RenderHelper) *RenderContext {
ctx.RenderHelper = helper
2024-11-22 13:48:09 +08:00
return ctx
}
2026-01-26 10:34:38 +08:00
func (ctx *RenderContext) DetectMarkupRenderer(prefetchBuf []byte) Renderer {
2024-11-22 13:48:09 +08:00
if ctx.RenderOptions.MarkupType == "" && ctx.RenderOptions.RelativePath != "" {
2026-01-26 10:34:38 +08:00
var sniffedType typesniffer.SniffedType
if len(prefetchBuf) > 0 {
sniffedType = typesniffer.DetectContentType(prefetchBuf)
2024-11-14 13:02:11 +08:00
}
2026-01-26 10:34:38 +08:00
ctx.RenderOptions.MarkupType = DetectRendererTypeByPrefetch(ctx.RenderOptions.RelativePath, sniffedType, prefetchBuf)
2024-11-14 13:02:11 +08:00
}
2026-01-26 10:34:38 +08:00
return renderers[ctx.RenderOptions.MarkupType]
}
2024-11-14 13:02:11 +08:00
2026-01-26 10:34:38 +08:00
func (ctx *RenderContext) DetectMarkupRendererByReader(in io.Reader) (Renderer, io.Reader, error) {
prefetchBuf := make([]byte, 512)
n, err := util.ReadAtMost(in, prefetchBuf)
if err != nil && err != io.EOF {
return nil, nil, err
}
prefetchBuf = prefetchBuf[:n]
renderer := ctx.DetectMarkupRenderer(prefetchBuf)
2024-11-14 13:02:11 +08:00
if renderer == nil {
2026-01-26 10:34:38 +08:00
return nil, nil, util.NewInvalidArgumentErrorf("unable to find a render")
2024-11-14 13:02:11 +08:00
}
2026-01-26 10:34:38 +08:00
return renderer, io.MultiReader(bytes.NewReader(prefetchBuf), in), nil
2025-10-23 07:41:38 +08:00
}
func RendererNeedPostProcess(renderer Renderer) bool {
if r, ok := renderer.(PostProcessRenderer); ok && r.NeedPostProcess() {
return true
2024-11-04 18:59:50 +08:00
}
2025-10-23 07:41:38 +08:00
return false
}
2024-11-14 13:02:11 +08:00
2025-10-23 07:41:38 +08:00
// Render renders markup file to HTML with all specific handling stuff.
2026-01-26 10:34:38 +08:00
func Render(rctx *RenderContext, origInput io.Reader, output io.Writer) error {
renderer, input, err := rctx.DetectMarkupRendererByReader(origInput)
2025-10-23 07:41:38 +08:00
if err != nil {
return err
}
2026-01-26 10:34:38 +08:00
return RenderWithRenderer(rctx, renderer, input, output)
2024-11-04 18:59:50 +08:00
}
// RenderString renders Markup string to HTML with all specific handling stuff and return string
func RenderString(ctx *RenderContext, content string) (string, error) {
var buf strings.Builder
if err := Render(ctx, strings.NewReader(content), &buf); err != nil {
return "", err
}
return buf.String(), nil
}
func RenderIFrame(ctx *RenderContext, opts *ExternalRendererOptions, output io.Writer) error {
2025-10-23 16:01:38 +08:00
src := fmt.Sprintf("%s/%s/%s/render/%s/%s", setting.AppSubURL,
2024-11-22 13:48:09 +08:00
url.PathEscape(ctx.RenderOptions.Metas["user"]),
url.PathEscape(ctx.RenderOptions.Metas["repo"]),
2025-10-23 16:01:38 +08:00
util.PathEscapeSegments(ctx.RenderOptions.Metas["RefTypeNameSubURL"]),
util.PathEscapeSegments(ctx.RenderOptions.RelativePath),
)
var extraAttrs template.HTML
if opts.ContentSandbox != "" {
extraAttrs = htmlutil.HTMLFormat(` sandbox="%s"`, opts.ContentSandbox)
2025-10-23 16:01:38 +08:00
}
_, err := htmlutil.HTMLPrintf(output, `<iframe data-src="%s" class="external-render-iframe"%s></iframe>`, src, extraAttrs)
2024-11-04 18:59:50 +08:00
return err
}
2024-11-18 13:25:42 +08:00
func pipes() (io.ReadCloser, io.WriteCloser, func()) {
2024-11-04 18:59:50 +08:00
pr, pw := io.Pipe()
2024-11-18 13:25:42 +08:00
return pr, pw, func() {
2024-11-04 18:59:50 +08:00
_ = pr.Close()
_ = pw.Close()
}
2024-11-18 13:25:42 +08:00
}
2024-11-04 18:59:50 +08:00
2025-10-23 16:01:38 +08:00
func getExternalRendererOptions(renderer Renderer) (ret ExternalRendererOptions, _ bool) {
if externalRender, ok := renderer.(ExternalRenderer); ok {
return externalRender.GetExternalRendererOptions(), true
}
return ret, false
}
2025-10-23 07:41:38 +08:00
func RenderWithRenderer(ctx *RenderContext, renderer Renderer, input io.Reader, output io.Writer) error {
2025-10-23 16:01:38 +08:00
var extraHeadHTML template.HTML
if extOpts, ok := getExternalRendererOptions(renderer); ok && extOpts.DisplayInIframe {
if ctx.RenderOptions.StandalonePageOptions == nil {
2025-10-23 07:41:38 +08:00
// for an external "DisplayInIFrame" render, it could only output its content in a standalone page
// otherwise, a <iframe> should be outputted to embed the external rendered page
return RenderIFrame(ctx, &extOpts, output)
2025-10-23 07:41:38 +08:00
}
2025-10-23 16:01:38 +08:00
// else: this is a standalone page, fallthrough to the real rendering, and add extra JS/CSS
extraScriptSrc := public.AssetURI("js/external-render-helper.js")
extraLinkHref := ctx.RenderOptions.StandalonePageOptions.CurrentWebTheme.PublicAssetURI()
2025-10-23 16:01:38 +08:00
// "<script>" must go before "<link>", to make Golang's http.DetectContentType() can still recognize the content as "text/html"
// DO NOT use "type=module", the script must run as early as possible, to set up the environment in the iframe
extraHeadHTML = htmlutil.HTMLFormat(`<script crossorigin src="%s"></script><link rel="stylesheet" href="%s">`, extraScriptSrc, extraLinkHref)
2025-10-23 07:41:38 +08:00
}
ctx.usedByRender = true
2024-11-24 16:18:57 +08:00
if ctx.RenderHelper != nil {
defer ctx.RenderHelper.CleanUp()
}
2025-10-23 16:01:38 +08:00
finalProcessor := ctx.RenderInternal.Init(output, extraHeadHTML)
2024-11-18 13:25:42 +08:00
defer finalProcessor.Close()
// input -> (pw1=pr1) -> renderer -> (pw2=pr2) -> SanitizeReader -> finalProcessor -> output
// no sanitizer: input -> (pw1=pr1) -> renderer -> pw2(finalProcessor) -> output
pr1, pw1, close1 := pipes()
defer close1()
2024-11-22 13:48:09 +08:00
eg, _ := errgroup.WithContext(ctx)
2024-11-18 13:25:42 +08:00
var pw2 io.WriteCloser = util.NopCloser{Writer: finalProcessor}
2025-10-23 16:01:38 +08:00
if r, ok := renderer.(ExternalRenderer); !ok || !r.GetExternalRendererOptions().SanitizerDisabled {
2024-11-18 13:25:42 +08:00
var pr2 io.ReadCloser
var close2 func()
pr2, pw2, close2 = pipes()
defer close2()
eg.Go(func() error {
defer pr2.Close()
return SanitizeReader(pr2, renderer.Name(), finalProcessor)
})
2024-11-04 18:59:50 +08:00
}
2024-11-18 13:25:42 +08:00
eg.Go(func() (err error) {
2025-10-23 07:41:38 +08:00
if RendererNeedPostProcess(renderer) {
2024-11-27 00:46:02 +08:00
err = PostProcessDefault(ctx, pr1, pw2)
2024-11-04 18:59:50 +08:00
} else {
2024-11-18 13:25:42 +08:00
_, err = io.Copy(pw2, pr1)
2024-11-04 18:59:50 +08:00
}
2024-11-18 13:25:42 +08:00
_, _ = pr1.Close(), pw2.Close()
return err
})
2024-11-04 18:59:50 +08:00
2024-11-18 13:25:42 +08:00
if err := renderer.Render(ctx, input, pw1); err != nil {
return err
2024-11-04 18:59:50 +08:00
}
2024-11-18 13:25:42 +08:00
_ = pw1.Close()
2024-11-04 18:59:50 +08:00
2024-11-18 13:25:42 +08:00
return eg.Wait()
2024-11-04 18:59:50 +08:00
}
// Init initializes the render global variables
2024-11-24 16:18:57 +08:00
func Init(renderHelpFuncs *RenderHelperFuncs) {
DefaultRenderHelperFuncs = renderHelpFuncs
2024-11-04 18:59:50 +08:00
if len(setting.Markdown.CustomURLSchemes) > 0 {
CustomLinkURLSchemes(setting.Markdown.CustomURLSchemes)
}
// since setting maybe changed extensions, this will reload all renderer extensions mapping
2026-01-26 10:34:38 +08:00
fileNameRenderers = make(map[string]Renderer)
2024-11-04 18:59:50 +08:00
for _, renderer := range renderers {
2026-01-26 10:34:38 +08:00
for _, pattern := range renderer.FileNamePatterns() {
fileNameRenderers[pattern] = renderer
2024-11-04 18:59:50 +08:00
}
}
2026-01-26 10:34:38 +08:00
RefreshFileNamePatterns()
2024-11-04 18:59:50 +08:00
}
func ComposeSimpleDocumentMetas() map[string]string {
2025-04-05 11:56:48 +08:00
// TODO: there is no separate config option for "simple document" rendering, so temporarily use the same config as "repo file"
return map[string]string{"markdownNewLineHardBreak": strconv.FormatBool(setting.Markdown.RenderOptionsRepoFile.NewLineHardBreak)}
}
2024-11-22 13:48:09 +08:00
2024-11-24 16:18:57 +08:00
type TestRenderHelper struct {
ctx *RenderContext
BaseLink string
}
func (r *TestRenderHelper) CleanUp() {}
func (r *TestRenderHelper) IsCommitIDExisting(commitID string) bool {
return strings.HasPrefix(commitID, "65f1bf2") //|| strings.HasPrefix(commitID, "88fc37a")
}
func (r *TestRenderHelper) ResolveLink(link, preferLinkType string) string {
linkType, link := ParseRenderedLink(link, preferLinkType)
switch linkType {
case LinkTypeRoot:
return r.ctx.ResolveLinkRoot(link)
default:
return r.ctx.ResolveLinkRelative(r.BaseLink, "", link)
}
2024-11-24 16:18:57 +08:00
}
var _ RenderHelper = (*TestRenderHelper)(nil)
2024-11-22 13:48:09 +08:00
// NewTestRenderContext is a helper function to create a RenderContext for testing purpose
2024-11-24 16:18:57 +08:00
// It accepts string (BaseLink), map[string]string (Metas)
func NewTestRenderContext(baseLinkOrMetas ...any) *RenderContext {
2024-11-22 13:48:09 +08:00
if !setting.IsInTesting {
panic("NewTestRenderContext should only be used in testing")
}
2024-11-24 16:18:57 +08:00
helper := &TestRenderHelper{}
ctx := NewRenderContext(context.Background()).WithHelper(helper)
helper.ctx = ctx
for _, v := range baseLinkOrMetas {
2024-11-22 13:48:09 +08:00
switch v := v.(type) {
case string:
2024-11-24 16:18:57 +08:00
helper.BaseLink = v
2024-11-22 13:48:09 +08:00
case map[string]string:
ctx = ctx.WithMetas(v)
default:
panic(fmt.Sprintf("unknown type %T", v))
}
}
return ctx
}