Documentation
¶
Overview ¶
Package plugin is tryck's public plugin API.
Plugins are compiled into a custom binary with tryck.Main (package pkg/tryck). Every plugin implements Plugin plus any of the phase interfaces below. A build parses every page, then renders every page, then finalizes once; each phase calls the plugins that implement it, ordered by Priority (lower first, default 100) and then by Name.
Plugins see copies and read-only views, never the build's own state.
Index ¶
- Constants
- type ConfigKeys
- type Diagnostic
- type Directive
- type DirectiveRenderer
- type Finalizer
- type FrontMatter
- type MarkdownExtender
- type NavNode
- type Ordered
- type Outputs
- type Page
- type PageInfo
- type PageParser
- type PageRenderer
- type Plugin
- type Reporter
- type Severity
- type SiteInfo
- type SiteView
- type Stylesheets
- type TOCEntry
Examples ¶
Constants ¶
const DefaultPriority = 100
DefaultPriority applies to plugins that do not implement Ordered.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ConfigKeys ¶ added in v0.2.0
type ConfigKeys interface{ ConfigKeys() []string }
ConfigKeys is implemented by plugins that declare their config keys, so typos in their section produce config.unknownKey warnings. "enabled" is always allowed.
type Diagnostic ¶
type Diagnostic struct {
Severity Severity
Line int
Col int
Code string // stable id, e.g. "link.broken"
Message string
}
Diagnostic is a problem a plugin reports about a page. Line and Col are 1-based file positions, or 0 when unknown.
type Directive ¶
type Directive struct {
Name string
Title string // from :::name[title]
Attrs map[string]string // from {key=value .class #id}; class and id included
}
Directive describes a ::: block for a DirectiveRenderer.
type DirectiveRenderer ¶
type DirectiveRenderer interface {
// DirectiveNames lists the directive names this plugin renders.
DirectiveNames() []string
// RenderDirective writes the opening HTML (entering) or closing HTML
// (!entering) of d. The directive's Markdown content is rendered
// between the two calls.
RenderDirective(w io.Writer, d Directive, entering bool) error
}
DirectiveRenderer renders ::: directives with names tryck does not know. Registered names do not produce directive.unknown warnings.
Example ¶
A DirectiveRenderer gives new ::: names their HTML.
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/Pinta365/tryck/pkg/plugin"
"github.com/Pinta365/tryck/pkg/tryck"
)
// buildSite writes files into a new directory, builds it with plugins
// and returns the directory. The output is in dist/.
func buildSite(files map[string]string, plugins ...plugin.Plugin) string {
dir, err := os.MkdirTemp("", "tryck-example")
if err != nil {
panic(err)
}
files["tryck.config.yaml"] = "site:\n title: Example\n baseUrl: https://example.com/\n" + files["tryck.config.yaml"]
for name, body := range files {
p := filepath.Join(dir, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
panic(err)
}
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
panic(err)
}
}
if code := tryck.Run([]string{"build", "--config", filepath.Join(dir, "tryck.config.yaml")}, io.Discard, os.Stderr, plugins...); code != 0 {
panic(fmt.Sprintf("build failed with exit code %d", code))
}
return dir
}
func read(dir, path string) string {
b, err := os.ReadFile(filepath.Join(dir, "dist", filepath.FromSlash(path)))
if err != nil {
panic(err)
}
return string(b)
}
// badge renders :::badge[text]{color=...} blocks.
type badge struct{}
func (badge) Name() string { return "badge" }
func (badge) Init(map[string]any, plugin.SiteInfo) error { return nil }
func (badge) DirectiveNames() []string { return []string{"badge"} }
// RenderDirective writes the opening HTML when entering and the closing
// HTML when leaving; the directive's Markdown body is rendered between.
func (badge) RenderDirective(w io.Writer, d plugin.Directive, entering bool) error {
if !entering {
_, err := io.WriteString(w, "</span>\n")
return err
}
_, err := fmt.Fprintf(w, "<span class=\"badge badge-%s\">%s", d.Attrs["color"], d.Title)
return err
}
func main() {
dir := buildSite(map[string]string{
"layouts/doc.html": `{{ .Content }}`,
"content/a.md": ":::badge[New]{color=green}\n:::\n",
}, badge{})
defer os.RemoveAll(dir)
fmt.Print(read(dir, "a/index.html"))
}
Output: <span class="badge badge-green">New</span>
type Finalizer ¶
Finalizer runs once, after every page is rendered. It may add output files.
Example ¶
A Finalizer adds files to the output.
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Pinta365/tryck/pkg/plugin"
"github.com/Pinta365/tryck/pkg/tryck"
)
// buildSite writes files into a new directory, builds it with plugins
// and returns the directory. The output is in dist/.
func buildSite(files map[string]string, plugins ...plugin.Plugin) string {
dir, err := os.MkdirTemp("", "tryck-example")
if err != nil {
panic(err)
}
files["tryck.config.yaml"] = "site:\n title: Example\n baseUrl: https://example.com/\n" + files["tryck.config.yaml"]
for name, body := range files {
p := filepath.Join(dir, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
panic(err)
}
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
panic(err)
}
}
if code := tryck.Run([]string{"build", "--config", filepath.Join(dir, "tryck.config.yaml")}, io.Discard, os.Stderr, plugins...); code != 0 {
panic(fmt.Sprintf("build failed with exit code %d", code))
}
return dir
}
func read(dir, path string) string {
b, err := os.ReadFile(filepath.Join(dir, "dist", filepath.FromSlash(path)))
if err != nil {
panic(err)
}
return string(b)
}
// pageList writes a list of every page.
type pageList struct{}
func (pageList) Name() string { return "pageList" }
func (pageList) Init(map[string]any, plugin.SiteInfo) error { return nil }
// OnBuildComplete runs once, after every page is rendered.
func (pageList) OnBuildComplete(s plugin.SiteView, out plugin.Outputs) error {
var b strings.Builder
for _, p := range s.Pages() {
fmt.Fprintf(&b, "%s %s\n", p.URL, p.Title)
}
return out.Add("pages.txt", []byte(b.String()))
}
func main() {
dir := buildSite(map[string]string{
"content/index.md": "# Home\n",
"content/guide/install.md": "# Install\n",
"content/guide/_index.md": "# Guide\n",
}, pageList{})
defer os.RemoveAll(dir)
fmt.Print(read(dir, "pages.txt"))
}
Output: / Home /guide/ Guide /guide/install/ Install
type FrontMatter ¶
type FrontMatter struct {
Title string `yaml:"title" json:"title,omitempty"`
Description string `yaml:"description" json:"description,omitempty"`
Layout string `yaml:"layout" json:"layout,omitempty"`
Date time.Time `yaml:"date" json:"date,omitempty"`
Draft bool `yaml:"draft" json:"draft,omitempty"`
Weight int `yaml:"weight" json:"weight,omitempty"` // nav ordering
TOC *bool `yaml:"toc" json:"toc,omitempty"` // nil = config default
Slug string `yaml:"slug" json:"slug,omitempty"` // overrides URL segment
Aliases []string `yaml:"aliases" json:"aliases,omitempty"` // old URLs -> redirect pages
Params map[string]any `yaml:",inline" json:"params,omitempty"`
}
FrontMatter is the YAML header of a page.
type MarkdownExtender ¶
MarkdownExtender extends the goldmark instance (parsers, AST transformers, renderers). It runs once per build, before parsing.
type NavNode ¶
type NavNode struct {
}
NavNode is an entry in the navigation tree. The tree is shared and must not be modified.
type Ordered ¶
type Ordered interface{ Priority() int }
Ordered sets the order within a phase. Lower runs first; default 100.
type Outputs ¶
type Outputs interface {
// Add writes data to path, relative to outputDir ("sitemap.xml").
// It fails if the path is invalid or already produced.
Add(path string, data []byte) error
// Report records a diagnostic that is not about one page.
Report(d Diagnostic)
}
Outputs collects extra output files and site-wide diagnostics.
type Page ¶
type Page struct {
SourcePath string // relative to its version's content directory, forward slashes
Version string // the page's version; "" on an unversioned site
URL string // "/docs/setup/"
Front FrontMatter // typed front matter
Data map[string]any // plugin-added values, e.g. "readingTime", "toc"
AST ast.Node // goldmark document; read-only for plugins
Source []byte // body without front matter
BodyLine int // file line on which Source starts
HTML []byte // the rendered page, set after the layout runs
Diags Reporter // per-page diagnostics
}
Page is a page being built. A plugin receives only the page it is called for.
type PageInfo ¶
type PageInfo struct {
SourcePath string
Version string // "" on an unversioned site
Title string
Description string
URL string
Date time.Time
LastUpdated time.Time // the file's last commit date, with build.lastUpdated; zero otherwise
Draft bool
Weight int
TitleInBody bool // the body has its own h1, so layouts skip theirs
Aliases []string // old URLs that redirect here
Params map[string]any // front matter keys tryck does not know
Data map[string]any // plugin-added values as of the end of parsing
}
PageInfo is a read-only copy of a page for templates and SiteView. Changing it does not affect the build.
type PageParser ¶
PageParser runs per page and in parallel, after the page's Markdown is parsed. It may modify its own page only, and must not modify p.AST: tryck dev reuses parsed ASTs between builds. Change the document with a MarkdownExtender (an AST transformer) instead.
Example ¶
Values a PageParser puts in p.Data reach layouts as .Page.Data.
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/yuin/goldmark/ast"
"github.com/Pinta365/tryck/pkg/plugin"
"github.com/Pinta365/tryck/pkg/tryck"
)
// buildSite writes files into a new directory, builds it with plugins
// and returns the directory. The output is in dist/.
func buildSite(files map[string]string, plugins ...plugin.Plugin) string {
dir, err := os.MkdirTemp("", "tryck-example")
if err != nil {
panic(err)
}
files["tryck.config.yaml"] = "site:\n title: Example\n baseUrl: https://example.com/\n" + files["tryck.config.yaml"]
for name, body := range files {
p := filepath.Join(dir, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
panic(err)
}
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
panic(err)
}
}
if code := tryck.Run([]string{"build", "--config", filepath.Join(dir, "tryck.config.yaml")}, io.Discard, os.Stderr, plugins...); code != 0 {
panic(fmt.Sprintf("build failed with exit code %d", code))
}
return dir
}
func read(dir, path string) string {
b, err := os.ReadFile(filepath.Join(dir, "dist", filepath.FromSlash(path)))
if err != nil {
panic(err)
}
return string(b)
}
// wordCount stores each page's word count for layouts.
type wordCount struct{}
func (wordCount) Name() string { return "wordCount" }
func (wordCount) Init(map[string]any, plugin.SiteInfo) error { return nil }
// OnPageParsed runs for every page, in parallel. It may set p.Data but
// must not change p.AST.
func (wordCount) OnPageParsed(p *plugin.Page) error {
words := 0
_ = ast.Walk(p.AST, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
if t, ok := n.(*ast.Text); ok && entering {
words += len(strings.Fields(string(t.Segment.Value(p.Source))))
}
return ast.WalkContinue, nil
})
p.Data["words"] = words
return nil
}
func main() {
dir := buildSite(map[string]string{
"layouts/doc.html": `{{ .Page.Title }}: {{ .Page.Data.words }} words`,
"content/intro.md": "# Intro\n\nThree short words.\n",
}, wordCount{})
defer os.RemoveAll(dir)
fmt.Println(read(dir, "intro/index.html"))
}
Output: Intro: 4 words
type PageRenderer ¶
PageRenderer runs per page and in parallel, after the layout has been executed. It may modify p.HTML and p.Data. The site is read-only.
type Plugin ¶
type Plugin interface {
// Name is the plugin's config key under "plugins:", e.g. "readingTime".
Name() string
// Init receives the plugin's own config section (nil if absent) and
// the site settings. It runs once per build before any phase.
Init(cfg map[string]any, site SiteInfo) error
}
Plugin is implemented by every plugin.
Example ¶
A plugin reads its own section of the config in Init.
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/Pinta365/tryck/pkg/plugin"
"github.com/Pinta365/tryck/pkg/tryck"
)
// buildSite writes files into a new directory, builds it with plugins
// and returns the directory. The output is in dist/.
func buildSite(files map[string]string, plugins ...plugin.Plugin) string {
dir, err := os.MkdirTemp("", "tryck-example")
if err != nil {
panic(err)
}
files["tryck.config.yaml"] = "site:\n title: Example\n baseUrl: https://example.com/\n" + files["tryck.config.yaml"]
for name, body := range files {
p := filepath.Join(dir, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
panic(err)
}
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
panic(err)
}
}
if code := tryck.Run([]string{"build", "--config", filepath.Join(dir, "tryck.config.yaml")}, io.Discard, os.Stderr, plugins...); code != 0 {
panic(fmt.Sprintf("build failed with exit code %d", code))
}
return dir
}
func read(dir, path string) string {
b, err := os.ReadFile(filepath.Join(dir, "dist", filepath.FromSlash(path)))
if err != nil {
panic(err)
}
return string(b)
}
// greeter is configured under plugins.greeter in tryck.config.yaml.
type greeter struct{ greeting string }
func (*greeter) Name() string { return "greeter" }
// ConfigKeys makes a typo in the plugin's section a warning.
func (*greeter) ConfigKeys() []string { return []string{"greeting"} }
// Init runs at the start of every build with the plugin's section.
func (g *greeter) Init(cfg map[string]any, site plugin.SiteInfo) error {
g.greeting = "Hello"
if v, ok := cfg["greeting"].(string); ok {
g.greeting = v
}
return nil
}
func (g *greeter) OnBuildComplete(s plugin.SiteView, out plugin.Outputs) error {
return out.Add("greeting.txt", []byte(g.greeting+" from "+s.Config().Title+"\n"))
}
func main() {
dir := buildSite(map[string]string{
"tryck.config.yaml": "plugins:\n greeter:\n greeting: Hej\n",
"content/index.md": "# Home\n",
}, &greeter{})
defer os.RemoveAll(dir)
fmt.Print(read(dir, "greeting.txt"))
}
Output: Hej from Example
type Reporter ¶
type Reporter interface {
Report(d Diagnostic)
}
Reporter receives diagnostics for one page. It is safe for concurrent use.
type SiteInfo ¶
type SiteInfo struct {
Title string
Description string
BaseURL string // always ends in "/"
Language string
Version string // the current version's name; "" on an unversioned site
Dev bool // building for tryck dev
}
SiteInfo holds site-wide settings.
type SiteView ¶
type SiteView interface {
Pages() []*PageInfo // sorted by URL
PageByURL(url string) (*PageInfo, bool)
HasAnchor(url, id string) bool
// HasFile reports whether a site path ("/img/logo.png", "/docs/")
// is served: a page, a copied asset or static file, or a generated
// file added so far.
HasFile(sitePath string) bool
Config() SiteInfo
}
SiteView is a read-only view of the built site. It is safe for concurrent use.
type Stylesheets ¶
type Stylesheets interface {
Stylesheets() []string
}
Stylesheets lists site paths of CSS files a plugin needs on every page, such as "/css/chroma.css". Layouts link them in <head>.