Debian Codegraph @

markup/pandoc/convert.go

raw
1 // Copyright 2019 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 pandoc converts content to HTML using Pandoc as an external helper.
15 package pandoc
16
17 import (
18 "fmt"
19
20 "github.com/gohugoio/hugo/common/hexec"
21 "github.com/gohugoio/hugo/htesting"
22 "github.com/gohugoio/hugo/identity"
23
24 "github.com/gohugoio/hugo/markup/converter"
25 "github.com/gohugoio/hugo/markup/internal"
26 )
27
28 // Provider is the package entry point.
29 var Provider converter.ProviderProvider = provider{}
30
31 type provider struct{}
32
33 func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) {
34 return converter.NewProvider("pandoc", func(ctx converter.DocumentContext) (converter.Converter, error) {
35 return &pandocConverter{
36 ctx: ctx,
37 cfg: cfg,
38 }, nil
39 }), nil
40 }
41
42 type pandocConverter struct {
43 ctx converter.DocumentContext
44 cfg converter.ProviderConfig
45 }
46
47 func (c *pandocConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) {
48 b, err := c.getPandocContent(ctx.Src, c.ctx)
49 if err != nil {
50 return nil, err
51 }
52 return converter.Bytes(b), nil
53 }
54
55 func (c *pandocConverter) Supports(feature identity.Identity) bool {
56 return false
57 }
58
59 // getPandocContent calls pandoc as an external helper to convert pandoc markdown to HTML.
60 func (c *pandocConverter) getPandocContent(src []byte, ctx converter.DocumentContext) ([]byte, error) {
61 binaryName := getPandocBinaryName()
62 if binaryName == "" {
63 return nil, fmt.Errorf("pandoc not found in $PATH, cannot render %q", ctx.DocumentName)
64 }
65 args := []string{"--mathjax", "--citeproc"}
66 return internal.ExternallyRenderContent(c.cfg, ctx, src, binaryName, args)
67 }
68
69 const pandocBinary = "pandoc"
70
71 func getPandocBinaryName() string {
72 if hexec.InPath(pandocBinary) {
73 return pandocBinary
74 }
75 return ""
76 }
77
78 // Supports returns whether Pandoc is installed on this computer.
79 func Supports() bool {
80 hasBin := getPandocBinaryName() != ""
81 if htesting.SupportsAll() {
82 if !hasBin {
83 panic("pandoc not installed")
84 }
85 return true
86 }
87 return hasBin
88 }