Home

ugit @c0fb1e8988d9995a4b751d8123f3ab4007913c05 - refs - log -
-
https://git.jolheiser.com/ugit.git
The code powering this h*ckin' site
ugit / internal / html / markup / markdown.go
- raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package markup

import (
	"bytes"
	"fmt"
	"io"
	"net/url"
	"path/filepath"
	"strings"

	"golang.org/x/net/html"

	"go.jolheiser.com/ugit/internal/git"

	chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
	"github.com/yuin/goldmark"
	emoji "github.com/yuin/goldmark-emoji"
	highlighting "github.com/yuin/goldmark-highlighting/v2"
	"github.com/yuin/goldmark/ast"
	"github.com/yuin/goldmark/extension"
	"github.com/yuin/goldmark/parser"
	goldmarkhtml "github.com/yuin/goldmark/renderer/html"
	"github.com/yuin/goldmark/text"
	"github.com/yuin/goldmark/util"
)

var markdown = goldmark.New(
	goldmark.WithRendererOptions(
		goldmarkhtml.WithUnsafe(),
	),
	goldmark.WithParserOptions(
		parser.WithAutoHeadingID(),
		parser.WithASTTransformers(
			util.Prioritized(astTransformer{}, 100),
		),
	),
	goldmark.WithExtensions(
		extension.GFM,
		emoji.Emoji,
		highlighting.NewHighlighting(
			highlighting.WithStyle("catppuccin-mocha"),
			highlighting.WithFormatOptions(
				chromahtml.WithClasses(true),
			),
		),
	),
)

// Readme transforms a readme, potentially from markdown, into HTML
func Readme(repo *git.Repo, ref, path string) (string, error) {
	var readme string
	var err error
	for _, md := range []string{"README.md", "readme.md"} {
		readme, err = repo.FileContent(ref, filepath.Join(path, md))
		if err == nil {
			break
		}
	}

	if readme != "" {
		ctx := parser.NewContext()
		mdCtx := markdownContext{
			repo: repo.Name(),
			ref:  ref,
			path: path,
		}
		ctx.Set(renderContextKey, mdCtx)
		var buf bytes.Buffer
		if err := markdown.Convert([]byte(readme), &buf, parser.WithContext(ctx)); err != nil {
			return "", err
		}
		var out bytes.Buffer
		if err := postProcess(buf.String(), mdCtx, &out); err != nil {
			return "", err
		}

		return out.String(), nil
	}

	for _, md := range []string{"README.txt", "README", "readme.txt", "readme"} {
		readme, err = repo.FileContent(ref, filepath.Join(path, md))
		if err == nil {
			return readme, nil
		}
	}

	return "", nil
}

var renderContextKey = parser.NewContextKey()

type markdownContext struct {
	repo string
	ref  string
	path string
}

type astTransformer struct{}

// Transform does two main things
// 1. Changes images to work relative to the source and wraps them in links
// 2. Changes links to work relative to the source
func (a astTransformer) Transform(node *ast.Document, _ text.Reader, pc parser.Context) {
	_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
		if !entering {
			return ast.WalkContinue, nil
		}

		ctx := pc.Get(renderContextKey).(markdownContext)

		switch v := n.(type) {
		case *ast.Image:
			link := v.Destination
			if len(link) > 0 && !bytes.HasPrefix(link, []byte("http")) {
				v.Destination = []byte(resolveLink(ctx.repo, ctx.ref, ctx.path, string(link)) + "?raw&pretty")
			}

			parent := n.Parent()
			if _, ok := parent.(*ast.Link); !ok && parent != nil {
				next := n.NextSibling()
				wrapper := ast.NewLink()
				wrapper.Destination = v.Destination
				wrapper.Title = v.Title
				wrapper.SetAttributeString("target", []byte("_blank"))
				img := ast.NewImage(ast.NewLink())
				img.Destination = link
				img.Title = v.Title
				for _, attr := range v.Attributes() {
					img.SetAttribute(attr.Name, attr.Value)
				}
				for child := v.FirstChild(); child != nil; {
					nextChild := child.NextSibling()
					img.AppendChild(img, child)
					child = nextChild
				}
				wrapper.AppendChild(wrapper, img)
				wrapper.SetNextSibling(next)
				parent.ReplaceChild(parent, n, wrapper)
				v.SetNextSibling(next)
			}
		case *ast.Link:
			link := v.Destination
			if len(link) > 0 && !bytes.HasPrefix(link, []byte("http")) && link[0] != '#' && !bytes.HasPrefix(link, []byte("mailto")) {
				v.Destination = []byte(resolveLink(ctx.repo, ctx.ref, ctx.path, string(link)))
			}
		}

		return ast.WalkContinue, nil
	})
}

func postProcess(in string, ctx markdownContext, out io.Writer) error {
	node, err := html.Parse(strings.NewReader("<html><body>" + in + "</body></html"))
	if err != nil {
		return err
	}
	if node.Type == html.DocumentNode {
		node = node.FirstChild
	}

	process(ctx, node)

	renderNodes := make([]*html.Node, 0)
	if node.Data == "html" {
		node = node.FirstChild
		for node != nil && node.Data != "body" {
			node = node.NextSibling
		}
	}
	if node != nil {
		if node.Data == "body" {
			child := node.FirstChild
			for child != nil {
				renderNodes = append(renderNodes, child)
				child = child.NextSibling
			}
		} else {
			renderNodes = append(renderNodes, node)
		}
	}
	for _, node := range renderNodes {
		if err := html.Render(out, node); err != nil {
			return err
		}
	}
	return nil
}

func process(ctx markdownContext, node *html.Node) {
	if node.Type == html.ElementNode && node.Data == "img" {
		for i, attr := range node.Attr {
			if attr.Key != "src" {
				continue
			}
			if len(attr.Val) > 0 && !strings.HasPrefix(attr.Val, "http") && !strings.HasPrefix(attr.Val, "data:image/") {
				attr.Val = resolveLink(ctx.repo, ctx.ref, ctx.path, attr.Val) + "?raw&pretty"
			}
			node.Attr[i] = attr
		}
	}
	for n := node.FirstChild; n != nil; n = n.NextSibling {
		process(ctx, n)
	}
}

func resolveLink(repo, ref, path, link string) string {
	baseURL, err := url.Parse(fmt.Sprintf("/%s/tree/%s/%s", repo, ref, path))
	if err != nil {
		return ""
	}
	linkURL, err := url.Parse(link)
	if err != nil {
		return ""
	}
	return baseURL.ResolveReference(linkURL).String()
}