Add Markdown diagrams and render hooks for code blocks

You can now create custom hook templates for code blocks, either one for all (`render-codeblock.html`) or for a given code language (e.g. `render-codeblock-go.html`).

We also used this new hook to add support for diagrams in Hugo:

* Goat (Go ASCII Tool) is built-in and enabled by default; just create a fenced code block with the language `goat` and start draw your Ascii diagrams.
* Another popular alternative for diagrams in Markdown, Mermaid (supported by GitHub), can also be implemented with a simple template. See the Hugo documentation for more information.

Updates #7765
Closes #9538
Fixes #9553
Fixes #8520
Fixes #6702
Fixes #9558
This commit is contained in:
Bjørn Erik Pedersen
2022-02-17 13:04:00 +01:00
parent 2c20f5bc00
commit 08fdca9d93
73 changed files with 1887 additions and 1986 deletions

View File

@@ -19,6 +19,7 @@ import (
"errors"
"fmt"
_os "os"
"path/filepath"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/afero"
@@ -27,17 +28,9 @@ import (
// New returns a new instance of the os-namespaced template functions.
func New(d *deps.Deps) *Namespace {
var rfs afero.Fs
if d.Fs != nil {
rfs = d.Fs.WorkingDir
if d.PathSpec != nil && d.PathSpec.BaseFs != nil {
rfs = afero.NewReadOnlyFs(afero.NewCopyOnWriteFs(d.PathSpec.BaseFs.Content.Fs, d.Fs.WorkingDir))
}
}
return &Namespace{
readFileFs: rfs,
readFileFs: afero.NewReadOnlyFs(afero.NewCopyOnWriteFs(d.PathSpec.BaseFs.Content.Fs, d.PathSpec.BaseFs.Work)),
workFs: d.PathSpec.BaseFs.Work,
deps: d,
}
}
@@ -45,6 +38,7 @@ func New(d *deps.Deps) *Namespace {
// Namespace provides template functions for the "os" namespace.
type Namespace struct {
readFileFs afero.Fs
workFs afero.Fs
deps *deps.Deps
}
@@ -66,8 +60,9 @@ func (ns *Namespace) Getenv(key interface{}) (string, error) {
// readFile reads the file named by filename in the given filesystem
// and returns the contents as a string.
func readFile(fs afero.Fs, filename string) (string, error) {
if filename == "" {
return "", errors.New("readFile needs a filename")
filename = filepath.Clean(filename)
if filename == "" || filename == "." || filename == string(_os.PathSeparator) {
return "", errors.New("invalid filename")
}
b, err := afero.ReadFile(fs, filename)
@@ -101,7 +96,7 @@ func (ns *Namespace) ReadDir(i interface{}) ([]_os.FileInfo, error) {
return nil, err
}
list, err := afero.ReadDir(ns.deps.Fs.WorkingDir, path)
list, err := afero.ReadDir(ns.workFs, path)
if err != nil {
return nil, fmt.Errorf("failed to read directory %q: %s", path, err)
}