Debian Codegraph @

markup/goldmark/hugocontext/hugocontext.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hugocontext
15
16 import (
17 "bytes"
18 "fmt"
19 "regexp"
20 "strconv"
21
22 "github.com/gohugoio/hugo/bufferpool"
23 "github.com/gohugoio/hugo/common/constants"
24 "github.com/gohugoio/hugo/common/loggers"
25 "github.com/gohugoio/hugo/markup/goldmark/internal/render"
26 "github.com/yuin/goldmark"
27 "github.com/yuin/goldmark/ast"
28 "github.com/yuin/goldmark/parser"
29 "github.com/yuin/goldmark/renderer"
30 "github.com/yuin/goldmark/renderer/html"
31 "github.com/yuin/goldmark/text"
32 "github.com/yuin/goldmark/util"
33 )
34
35 func New(logger loggers.Logger) goldmark.Extender {
36 return &hugoContextExtension{logger: logger}
37 }
38
39 // Wrap wraps the given byte slice in a Hugo context that used to determine the correct Page
40 // in .RenderShortcodes.
41 func Wrap(b []byte, pid uint64) string {
42 buf := bufferpool.GetBuffer()
43 defer bufferpool.PutBuffer(buf)
44 buf.Write(hugoCtxPrefix)
45 buf.WriteString(" pid=")
46 buf.WriteString(strconv.FormatUint(pid, 10))
47 buf.Write(hugoCtxEndDelim)
48 buf.WriteByte('\n')
49 buf.Write(b)
50 // To make sure that we're able to parse it, make sure it ends with a newline.
51 if len(b) > 0 && b[len(b)-1] != '\n' {
52 buf.WriteByte('\n')
53 }
54 buf.Write(hugoCtxPrefix)
55 buf.Write(hugoCtxClosingDelim)
56 buf.WriteByte('\n')
57 return buf.String()
58 }
59
60 var kindHugoContext = ast.NewNodeKind("HugoContext")
61
62 // HugoContext is a node that represents a Hugo context.
63 type HugoContext struct {
64 ast.BaseInline
65
66 Closing bool
67
68 // Internal page ID. Not persisted.
69 Pid uint64
70 }
71
72 // Dump implements Node.Dump.
73 func (n *HugoContext) Dump(source []byte, level int) {
74 m := map[string]string{}
75 m["Pid"] = fmt.Sprintf("%v", n.Pid)
76 ast.DumpHelper(n, source, level, m, nil)
77 }
78
79 func (n *HugoContext) parseAttrs(attrBytes []byte) {
80 keyPairs := bytes.SplitSeq(attrBytes, []byte(" "))
81 for keyPair := range keyPairs {
82 kv := bytes.Split(keyPair, []byte("="))
83 if len(kv) != 2 {
84 continue
85 }
86 key := string(kv[0])
87 val := string(kv[1])
88 switch key {
89 case "pid":
90 pid, _ := strconv.ParseUint(val, 10, 64)
91 n.Pid = pid
92 }
93 }
94 }
95
96 func (h *HugoContext) Kind() ast.NodeKind {
97 return kindHugoContext
98 }
99
100 var (
101 hugoCtxPrefix = []byte("{{__hugo_ctx")
102 hugoCtxEndDelim = []byte("}}")
103 hugoCtxClosingDelim = []byte("/}}")
104 hugoCtxRe = regexp.MustCompile(`{{__hugo_ctx( pid=\d+)?/?}}\n?`)
105 hugoCtxIndentedRe = regexp.MustCompile(`(?m)^[ \t]+({{__hugo_ctx[^\n]*}})`)
106 )
107
108 // DedentMarkers removes leading whitespace from Hugo context marker lines
109 // to prevent them from being treated as indented code blocks by Goldmark.
110 func DedentMarkers(b []byte) []byte {
111 if !bytes.Contains(b, hugoCtxPrefix) {
112 return b
113 }
114 return hugoCtxIndentedRe.ReplaceAll(b, []byte("$1"))
115 }
116
117 // Strip strips any Hugo context markers from b.
118 func Strip(b []byte) []byte {
119 if !bytes.Contains(b, hugoCtxPrefix) {
120 return b
121 }
122 return hugoCtxRe.ReplaceAll(b, nil)
123 }
124
125 var _ parser.InlineParser = (*hugoContextParser)(nil)
126
127 type hugoContextParser struct{}
128
129 func (a *hugoContextParser) Trigger() []byte {
130 return []byte{'{'}
131 }
132
133 func (s *hugoContextParser) Parse(parent ast.Node, reader text.Reader, pc parser.Context) ast.Node {
134 line, _ := reader.PeekLine()
135 if !bytes.HasPrefix(line, hugoCtxPrefix) {
136 return nil
137 }
138 end := bytes.Index(line, hugoCtxEndDelim)
139 if end == -1 {
140 return nil
141 }
142
143 reader.Advance(end + len(hugoCtxEndDelim) + 1) // +1 for the newline
144
145 if line[end-1] == '/' {
146 return &HugoContext{Closing: true}
147 }
148
149 attrBytes := line[len(hugoCtxPrefix)+1 : end]
150 h := &HugoContext{}
151 h.parseAttrs(attrBytes)
152 return h
153 }
154
155 type hugoContextRenderer struct {
156 logger loggers.Logger
157 html.Config
158 }
159
160 func (r *hugoContextRenderer) SetOption(name renderer.OptionName, value any) {
161 r.Config.SetOption(name, value)
162 }
163
164 func (r *hugoContextRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
165 reg.Register(kindHugoContext, r.handleHugoContext)
166 reg.Register(ast.KindRawHTML, r.renderRawHTML)
167 reg.Register(ast.KindHTMLBlock, r.renderHTMLBlock)
168 }
169
170 func (r *hugoContextRenderer) stripHugoCtx(b []byte) ([]byte, bool) {
171 if !bytes.Contains(b, hugoCtxPrefix) {
172 return b, false
173 }
174 return hugoCtxRe.ReplaceAll(b, nil), true
175 }
176
177 func (r *hugoContextRenderer) logRawHTMLEmittedWarn(w util.BufWriter) {
178 r.logger.Warnidf(constants.WarnGoldmarkRawHTML, "Raw HTML omitted while rendering %q; see https://gohugo.io/getting-started/configuration-markup/#rendererunsafe", r.getPage(w))
179 }
180
181 func (r *hugoContextRenderer) getPage(w util.BufWriter) any {
182 var p any
183 ctx, ok := w.(*render.Context)
184 if ok {
185 p, _ = render.GetPageAndPageInner(ctx)
186 }
187 return p
188 }
189
190 func (r *hugoContextRenderer) isHTMLComment(b []byte) bool {
191 return len(b) > 4 && b[0] == '<' && b[1] == '!' && b[2] == '-' && b[3] == '-'
192 }
193
194 // HTML rendering based on Goldmark implementation.
195 func (r *hugoContextRenderer) renderHTMLBlock(
196 w util.BufWriter, source []byte, node ast.Node, entering bool,
197 ) (ast.WalkStatus, error) {
198 n := node.(*ast.HTMLBlock)
199
200 if entering {
201 if r.Unsafe {
202 l := n.Lines().Len()
203 for i := range l {
204 line := n.Lines().At(i)
205 linev := line.Value(source)
206 var stripped bool
207 linev, stripped = r.stripHugoCtx(linev)
208 if stripped {
209 r.logger.Warnidf(constants.WarnRenderShortcodesInHTML, ".RenderShortcodes detected inside HTML block in %q; this may not be what you intended, see https://gohugo.io/methods/page/rendershortcodes/#limitations", r.getPage(w))
210 }
211 r.Writer.SecureWrite(w, linev)
212 }
213 } else {
214 l := n.Lines().At(0)
215 v := l.Value(source)
216 if !r.isHTMLComment(v) {
217 r.logRawHTMLEmittedWarn(w)
218 _, _ = w.WriteString("<!-- raw HTML omitted -->\n")
219 }
220 }
221 } else {
222 if n.HasClosure() {
223 if r.Unsafe {
224 closure := n.ClosureLine
225 r.Writer.SecureWrite(w, closure.Value(source))
226 } else {
227 l := n.Lines().At(0)
228 v := l.Value(source)
229 if !r.isHTMLComment(v) {
230 _, _ = w.WriteString("<!-- raw HTML omitted -->\n")
231 }
232 }
233 }
234 }
235 return ast.WalkContinue, nil
236 }
237
238 func (r *hugoContextRenderer) renderRawHTML(
239 w util.BufWriter, source []byte, node ast.Node, entering bool,
240 ) (ast.WalkStatus, error) {
241 if !entering {
242 return ast.WalkSkipChildren, nil
243 }
244 n := node.(*ast.RawHTML)
245 l := n.Segments.Len()
246 if r.Unsafe {
247 for i := range l {
248 segment := n.Segments.At(i)
249 _, _ = w.Write(segment.Value(source))
250 }
251 return ast.WalkSkipChildren, nil
252 }
253 segment := n.Segments.At(0)
254 v := segment.Value(source)
255 if !r.isHTMLComment(v) {
256 r.logRawHTMLEmittedWarn(w)
257 _, _ = w.WriteString("<!-- raw HTML omitted -->")
258 }
259 return ast.WalkSkipChildren, nil
260 }
261
262 func (r *hugoContextRenderer) handleHugoContext(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
263 if !entering {
264 return ast.WalkContinue, nil
265 }
266
267 hctx := node.(*HugoContext)
268 ctx, ok := w.(*render.Context)
269 if !ok {
270 return ast.WalkContinue, nil
271 }
272 if hctx.Closing {
273 _ = ctx.PopPid()
274 } else {
275 ctx.PushPid(hctx.Pid)
276 }
277 return ast.WalkContinue, nil
278 }
279
280 type hugoContextTransformer struct{}
281
282 var _ parser.ASTTransformer = (*hugoContextTransformer)(nil)
283
284 func (a *hugoContextTransformer) Transform(n *ast.Document, reader text.Reader, pc parser.Context) {
285 ast.Walk(n, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
286 s := ast.WalkContinue
287 if !entering || n.Kind() != kindHugoContext {
288 return s, nil
289 }
290
291 if p, ok := n.Parent().(*ast.Paragraph); ok {
292 if p.ChildCount() == 1 {
293 // Avoid empty paragraphs.
294 p.Parent().ReplaceChild(p.Parent(), p, n)
295 } else {
296 if t, ok := n.PreviousSibling().(*ast.Text); ok {
297 // Remove the newline produced by the Hugo context markers.
298 if t.SoftLineBreak() {
299 if t.Segment.Len() == 0 {
300 p.RemoveChild(p, t)
301 } else {
302 t.SetSoftLineBreak(false)
303 }
304 }
305 }
306 }
307 }
308
309 return s, nil
310 })
311 }
312
313 type hugoContextExtension struct {
314 logger loggers.Logger
315 }
316
317 func (a *hugoContextExtension) Extend(m goldmark.Markdown) {
318 m.Parser().AddOptions(
319 parser.WithInlineParsers(
320 util.Prioritized(&hugoContextParser{}, 50),
321 ),
322 parser.WithASTTransformers(util.Prioritized(&hugoContextTransformer{}, 10)),
323 )
324
325 m.Renderer().AddOptions(
326 renderer.WithNodeRenderers(
327 util.Prioritized(&hugoContextRenderer{
328 logger: a.logger,
329 Config: html.Config{
330 Writer: html.DefaultWriter,
331 },
332 }, 50),
333 ),
334 )
335 }