all repos

mugit @ 20a3418b9ff77829a78332c5a71bcff0f3febc3f

🐮 git server that your cow will love

mugit/internal/markdown/relink.go(view 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
package markdown

import (
	"bytes"
	"net/url"
	"path"
	"regexp"
	"strings"

	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/ast"
	"github.com/yuin/goldmark/parser"
	"github.com/yuin/goldmark/renderer"
	"github.com/yuin/goldmark/text"
	"github.com/yuin/goldmark/util"
)

type relativeLink struct{}

func (e *relativeLink) Extend(m goldmark.Markdown) {
	m.Parser().AddOptions(parser.WithASTTransformers(util.Prioritized(&relLinkTransformer{}, 99)))
	m.Renderer().AddOptions(renderer.WithNodeRenderers(util.Prioritized(&rawBlockRenderer{}, 100)))
}

type relLinkTransformer struct {
	repoName string
	repoRef  string
	baseDir  string
}

func (m *relLinkTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {
	m.repoName, _ = pc.Get(repoNameKey).(string)
	m.repoRef, _ = pc.Get(repoRefKey).(string)
	m.baseDir, _ = pc.Get(baseDirKey).(string)

	_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
		if !entering {
			return ast.WalkContinue, nil
		}

		switch n := n.(type) {
		case *ast.Link:
			m.relativeLinkTransformer(n)

		case *ast.Image:
			m.imageFromRepoTransformer(n)

		case *ast.RawHTML:
			buf := m.segmentsToBytes(n.Segments, reader)
			updated := m.rewriteSrc(buf)
			if !bytes.Equal(updated, buf) {
				s := ast.NewString(updated)
				s.SetRaw(true)
				n.Parent().ReplaceChild(n.Parent(), n, s)
			}

		case *ast.HTMLBlock:
			buf := m.segmentsToBytes(n.Lines(), reader)
			updated := m.rewriteSrc(buf)
			if !bytes.Equal(updated, buf) {
				n.Parent().ReplaceChild(n.Parent(), n, &rawBlock{data: updated})
			}
		}

		return ast.WalkContinue, nil
	})
}

func (m *relLinkTransformer) relativeLinkTransformer(link *ast.Link) {
	dst := string(link.Destination)
	if isAbsoluteURL(dst) {
		return
	}

	act := m.path(dst)
	link.Destination = []byte(path.Join("/", m.repoName, "tree", m.repoRef, act))
}

func (m *relLinkTransformer) imageFromRepoTransformer(img *ast.Image) {
	img.Destination = []byte(m.imageFromRepo(
		string(img.Destination)))
}

func (m *relLinkTransformer) imageFromRepo(dst string) string {
	if isAbsoluteURL(dst) {
		return dst
	}

	absPath := m.path(dst)
	return path.Join("/", url.PathEscape(m.repoName), "blob", m.repoRef, absPath) +
		"?raw=true"
}

func (m *relLinkTransformer) path(dst string) string {
	if path.IsAbs(dst) {
		return dst
	}
	return path.Join(m.baseDir, dst)
}

var imgSrcRe = regexp.MustCompile(`src="([^"]*)"`)

func (m *relLinkTransformer) rewriteSrc(buf []byte) []byte {
	return imgSrcRe.ReplaceAllFunc(buf, func(match []byte) []byte {
		start := bytes.IndexByte(match, '"') + 1
		end := bytes.LastIndexByte(match, '"')
		src := string(match[start:end])
		return []byte(`src="` + m.imageFromRepo(src) + `"`)
	})
}

func (m *relLinkTransformer) segmentsToBytes(segs *text.Segments, reader text.Reader) []byte {
	var buf []byte
	for i := 0; i < segs.Len(); i++ {
		buf = append(buf, reader.Value(segs.At(i))...)
	}
	return buf
}

func isAbsoluteURL(link string) bool {
	if strings.HasPrefix(link, "#") {
		return true
	}
	u, err := url.Parse(link)
	return err == nil && (u.Scheme != "" || strings.HasPrefix(link, "//"))
}

// row block

type rawBlock struct {
	ast.BaseBlock
	data []byte
}

var rawBlockKind = ast.NewNodeKind("RawBlock")

func (r *rawBlock) Kind() ast.NodeKind   { return rawBlockKind }
func (r *rawBlock) Dump(_ []byte, _ int) {}

type rawBlockRenderer struct{}

func (r *rawBlockRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
	reg.Register(rawBlockKind, func(w util.BufWriter, _ []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
		if entering {
			w.Write(node.(*rawBlock).data)
		}
		return ast.WalkContinue, nil
	})
}