Debian Codegraph @

markup/asciidocext/internal/converter.go

raw
1 package internal
2
3 import (
4 "bytes"
5 "fmt"
6 "net/url"
7 "path"
8 "path/filepath"
9 "strings"
10
11 "github.com/gohugoio/hugo/common/hexec"
12 "github.com/gohugoio/hugo/common/loggers"
13 "github.com/gohugoio/hugo/config/security"
14 "github.com/gohugoio/hugo/identity"
15 "github.com/gohugoio/hugo/langs"
16 "github.com/gohugoio/hugo/markup/asciidocext/asciidocext_config"
17 "github.com/gohugoio/hugo/markup/converter"
18 "github.com/gohugoio/hugo/markup/internal"
19 "github.com/gohugoio/hugo/markup/tableofcontents"
20 "github.com/spf13/cast"
21 "golang.org/x/net/html"
22 )
23
24 type AsciiDocConverter struct {
25 Ctx converter.DocumentContext
26 Cfg converter.ProviderConfig
27 }
28
29 type asciiDocResult struct {
30 converter.ResultRender
31 toc *tableofcontents.Fragments
32 }
33
34 type pageSubset interface {
35 IsPage() bool
36 RelPermalink() string
37 Section() string
38 }
39
40 const (
41 // asciiDocBinaryName is name of the AsciiDoc converter CLI.
42 asciiDocBinaryName = "asciidoctor"
43
44 // asciiDocDiagramExtension is the name of the AsciiDoc converter diagram
45 // extension.
46 asciiDocDiagramExtension = "asciidoctor-diagram"
47
48 // asciiDocDiagramCacheDirKey is the AsciiDoc converter attribute key for
49 // setting the path to the diagram cache directory.
50 asciiDocDiagramCacheDirKey = "diagram-cachedir"
51
52 // asciiDocDiagramCacheImagesOptionKey is the AsciiDoc converter attribute
53 // key for determining whether to cache image files in addition to
54 // metadata files.
55 asciiDocDiagramCacheImagesOptionKey = "diagram-cache-images-option"
56
57 // gemBinaryName is the name of the RubyGems CLI.
58 gemBinaryName = "gem"
59
60 // goatBinaryName is the name of the GoAT CLI.
61 goatBinaryName = "goat"
62 )
63
64 func (r asciiDocResult) TableOfContents() *tableofcontents.Fragments {
65 return r.toc
66 }
67
68 func (a *AsciiDocConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) {
69 b, err := a.GetAsciiDocContent(ctx.Src, a.Ctx)
70 if err != nil {
71 return nil, err
72 }
73 content, toc, err := a.extractTOC(b)
74 if err != nil {
75 return nil, err
76 }
77 return asciiDocResult{
78 ResultRender: converter.Bytes(content),
79 toc: toc,
80 }, nil
81 }
82
83 func (a *AsciiDocConverter) Supports(_ identity.Identity) bool {
84 return false
85 }
86
87 // GetAsciiDocContent calls asciidoctor as an external helper to convert
88 // AsciiDoc content to HTML.
89 func (a *AsciiDocConverter) GetAsciiDocContent(src []byte, ctx converter.DocumentContext) ([]byte, error) {
90 if !hexec.InPath(asciiDocBinaryName) {
91 return nil, fmt.Errorf("asciidoctor not found in $PATH, cannot render %q", ctx.DocumentName)
92 }
93
94 args, err := a.ParseArgs(ctx)
95 if err != nil {
96 return nil, err
97 }
98 args = append(args, "-") // read from stdin
99
100 a.Cfg.Logger.Infof("Rendering %s using Asciidoctor args %s ...", ctx.DocumentName, args)
101
102 return internal.ExternallyRenderContent(a.Cfg, ctx, src, asciiDocBinaryName, args)
103 }
104
105 func (a *AsciiDocConverter) ParseArgs(ctx converter.DocumentContext) ([]string, error) {
106 cfg := a.Cfg.MarkupConfig().AsciiDocExt
107 args := []string{}
108
109 args = a.AppendArg(args, "-b", cfg.Backend, asciidocext_config.CliDefault.Backend, asciidocext_config.AllowedBackend)
110
111 for _, extension := range cfg.Extensions {
112 if strings.LastIndexAny(extension, `\/.`) > -1 {
113 a.Cfg.Logger.Errorf(
114 "The %q Asciidoctor extension is unsupported and ignored. Only installed Asciidoctor extensions are allowed.",
115 extension,
116 )
117 continue
118 }
119
120 args = append(args, "-r", extension)
121
122 if extension == asciiDocDiagramExtension {
123 cacheDir := filepath.Clean(filepath.Join(a.Cfg.Conf.CacheDirMisc(), asciiDocDiagramExtension))
124 args = append(args, "-a", asciiDocDiagramCacheDirKey+"="+cacheDir)
125 args = append(args, "-a", asciiDocDiagramCacheImagesOptionKey)
126 }
127 }
128
129 for attributeKey, attributeValue := range cfg.Attributes {
130 if asciidocext_config.DisallowedAttributes[attributeKey] {
131 a.Cfg.Logger.Errorf(
132 "The %q Asciidoctor attribute is unsupported and ignored.",
133 attributeKey,
134 )
135 continue
136 }
137
138 if attributeKey == asciiDocDiagramCacheImagesOptionKey {
139 a.Cfg.Logger.Warnf(
140 "The %q Asciidoctor attribute is fixed and cannot be modified. To disable caching of both image and metadata files, set markup.asciidocext.attributes.diagram-nocache-option to true in your project configuration.",
141 attributeKey,
142 )
143 continue
144 }
145
146 if attributeKey == asciiDocDiagramCacheDirKey {
147 a.Cfg.Logger.Warnf(
148 "The %q Asciidoctor attribute is fixed and cannot be modified. To change the cache location, modify caches.misc.dir in your project configuration.",
149 attributeKey,
150 )
151 continue
152 }
153
154 // To set a document attribute to true: -a attributeKey
155 // To set a document attribute to false: -a '!attributeKey'
156 // For other types: -a attributeKey=attributeValue
157 if b, ok := attributeValue.(bool); ok {
158 arg := attributeKey
159 if !b {
160 arg = "'!" + attributeKey + "'"
161 }
162 args = append(args, "-a", arg)
163 } else {
164 args = append(args, "-a", attributeKey+"="+cast.ToString(attributeValue))
165 }
166 }
167
168 if cfg.WorkingFolderCurrent {
169 page, ok := ctx.Document.(pageSubset)
170 if !ok {
171 return nil, fmt.Errorf("expected pageSubset, got %T", ctx.Document)
172 }
173
174 // Derive the outdir document attribute from the relative permalink.
175 relPath := strings.TrimPrefix(page.RelPermalink(), a.Cfg.Conf.BaseURL().BasePathNoTrailingSlash)
176 relPath, err := url.PathUnescape(relPath)
177 if err != nil {
178 return nil, err
179 }
180
181 if a.Cfg.Conf.IsMultihost() {
182 // In a multi-host configuration, neither absolute nor relative
183 // permalinks include the language key; prepend it.
184 language, ok := a.Cfg.Conf.Language().(*langs.Language)
185 if !ok {
186 return nil, fmt.Errorf("expected *langs.Language, got %T", a.Cfg.Conf.Language())
187 }
188 relPath = path.Join(language.Lang, relPath)
189 }
190
191 if a.Cfg.Conf.IsUglyURLs(page.Section()) {
192 if page.IsPage() {
193 // Remove the extension.
194 relPath = strings.TrimSuffix(relPath, path.Ext(relPath))
195 } else {
196 // Remove the file name.
197 relPath = path.Dir(relPath)
198 }
199
200 // Set imagesoutdir and imagesdir attributes.
201 imagesoutdir, err := filepath.Abs(filepath.Join(a.Cfg.Conf.BaseConfig().PublishDir, relPath))
202 if err != nil {
203 return nil, err
204 }
205 imagesdir := filepath.Base(imagesoutdir)
206
207 if page.IsPage() {
208 args = append(args, "-a", "imagesoutdir="+imagesoutdir, "-a", "imagesdir="+imagesdir)
209 } else {
210 args = append(args, "-a", "imagesoutdir="+imagesoutdir)
211 }
212 }
213 // Prepend the publishDir.
214 outDir, err := filepath.Abs(filepath.Join(a.Cfg.Conf.BaseConfig().PublishDir, relPath))
215 if err != nil {
216 return nil, err
217 }
218
219 args = append(args, "--base-dir", filepath.Dir(ctx.Filename), "-a", "outdir="+outDir)
220 }
221
222 if cfg.NoHeaderOrFooter {
223 args = append(args, "--no-header-footer")
224 } else {
225 a.Cfg.Logger.Warnln("Asciidoctor parameter NoHeaderOrFooter is required for correct HTML rendering")
226 }
227
228 if cfg.SectionNumbers {
229 args = append(args, "--section-numbers")
230 }
231
232 if cfg.Verbose {
233 args = append(args, "--verbose")
234 }
235
236 if cfg.Trace {
237 args = append(args, "--trace")
238 }
239
240 args = a.AppendArg(args, "--failure-level", cfg.FailureLevel, asciidocext_config.CliDefault.FailureLevel, asciidocext_config.AllowedFailureLevel)
241
242 args = a.AppendArg(args, "--safe-mode", cfg.SafeMode, asciidocext_config.CliDefault.SafeMode, asciidocext_config.AllowedSafeMode)
243
244 return args, nil
245 }
246
247 func (a *AsciiDocConverter) AppendArg(args []string, option, value, defaultValue string, allowedValues map[string]bool) []string {
248 if value != defaultValue {
249 if allowedValues[value] {
250 args = append(args, option, value)
251 } else {
252 a.Cfg.Logger.Errorf(
253 "Unsupported Asciidoctor value %q for option %q was passed in and will be ignored.",
254 value,
255 option,
256 )
257 }
258 }
259 return args
260 }
261
262 // HasAsciiDoc reports whether the AsciiDoc converter is installed.
263 func HasAsciiDoc() (bool, error) {
264 if !hexec.InPath(asciiDocBinaryName) {
265 return false, fmt.Errorf("the AsciiDoc converter (%s) is not installed", asciiDocBinaryName)
266 }
267 return true, nil
268 }
269
270 // CanRenderGoATDiagrams reports whether the AsciiDoc converter can render
271 // GoAT diagrams. Only used in tests.
272 func CanRenderGoATDiagrams() (bool, error) {
273 // Verify that the AsciiDoc converter is installed.
274 if ok, err := HasAsciiDoc(); !ok {
275 return false, err
276 }
277
278 // Verify that the RubyGems CLI is installed.
279 if !hexec.InPath(gemBinaryName) {
280 return false, fmt.Errorf("the RubyGems CLI (%s) is not installed", gemBinaryName)
281 }
282
283 // Verify that the required AsciiDoc converter extension is installed.
284 sc := security.DefaultConfig
285 sc.Exec.Allow = security.MustNewWhitelist(gemBinaryName)
286 ex := hexec.New(sc, "", loggers.NewDefault())
287
288 args := []any{"list", asciiDocDiagramExtension, "--installed"}
289 cmd, err := ex.New(gemBinaryName, args...)
290 if err != nil {
291 return false, err
292 }
293 err = cmd.Run()
294 if err != nil {
295 return false, fmt.Errorf("the %s gem is not installed", asciiDocDiagramExtension)
296 }
297
298 // Verify that the GoAT CLI is installed.
299 if !hexec.InPath(goatBinaryName) {
300 return false, fmt.Errorf("the GoAT CLI (%s) is not installed", goatBinaryName)
301 }
302
303 return true, nil
304 }
305
306 // extractTOC extracts the toc from the given src html.
307 // It returns the html without the TOC, and the TOC data
308 func (a *AsciiDocConverter) extractTOC(src []byte) ([]byte, *tableofcontents.Fragments, error) {
309 var buf bytes.Buffer
310 buf.Write(src)
311 node, err := html.Parse(&buf)
312 if err != nil {
313 return nil, nil, err
314 }
315 var (
316 f func(*html.Node) bool
317 toc *tableofcontents.Fragments
318 toVisit []*html.Node
319 )
320 f = func(n *html.Node) bool {
321 if n.Type == html.ElementNode && (n.Data == "div" || n.Data == "nav") && attr(n, "id") == "toc" {
322 toc = parseTOC(n)
323 if !a.Cfg.MarkupConfig().AsciiDocExt.PreserveTOC {
324 n.Parent.RemoveChild(n)
325 }
326 return true
327 }
328 if n.FirstChild != nil {
329 toVisit = append(toVisit, n.FirstChild)
330 }
331 if n.NextSibling != nil && f(n.NextSibling) {
332 return true
333 }
334 for len(toVisit) > 0 {
335 nv := toVisit[0]
336 toVisit = toVisit[1:]
337 if f(nv) {
338 return true
339 }
340 }
341 return false
342 }
343 f(node)
344 if err != nil {
345 return nil, nil, err
346 }
347 buf.Reset()
348 err = html.Render(&buf, node)
349 if err != nil {
350 return nil, nil, err
351 }
352 // ltrim <html><head></head><body> and rtrim </body></html> which are added by html.Render
353 res := buf.Bytes()[25:]
354 res = res[:len(res)-14]
355 return res, toc, nil
356 }
357
358 // parseTOC returns a TOC root from the given toc Node
359 func parseTOC(doc *html.Node) *tableofcontents.Fragments {
360 var (
361 toc tableofcontents.Builder
362 f func(*html.Node, int, int)
363 )
364 f = func(n *html.Node, row, level int) {
365 if n.Type == html.ElementNode {
366 switch n.Data {
367 case "ul", "ol":
368 if level == 0 {
369 row++
370 }
371 level++
372 f(n.FirstChild, row, level)
373 case "li":
374 for c := n.FirstChild; c != nil; c = c.NextSibling {
375 if c.Type != html.ElementNode || c.Data != "a" {
376 continue
377 }
378 href := attr(c, "href")[1:]
379 toc.AddAt(&tableofcontents.Heading{
380 Title: nodeContent(c),
381 ID: href,
382 Level: level + 1,
383 }, row, level)
384 }
385 f(n.FirstChild, row, level)
386 }
387 }
388 if n.NextSibling != nil {
389 f(n.NextSibling, row, level)
390 }
391 }
392 f(doc.FirstChild, -1, 0)
393 return toc.Build()
394 }
395
396 func attr(node *html.Node, key string) string {
397 for _, a := range node.Attr {
398 if a.Key == key {
399 return a.Val
400 }
401 }
402 return ""
403 }
404
405 func nodeContent(node *html.Node) string {
406 var buf bytes.Buffer
407 for c := node.FirstChild; c != nil; c = c.NextSibling {
408 html.Render(&buf, c)
409 }
410 return buf.String()
411 }