Guidedog Handbuch 1.0.0-beta.16
Sprache
Auf dieser Seite
Guidedog / Dokumentation 1.0.0-beta.16

gd_plugins

Typed build plugins (GDS 0010) and publishers (GDS 0009), linked into an application or run as installed programs behind a bounded JSON Lines protocol.

A Plugin is either build hooks (BuildPlugin: source text, complete HTML pages, generated static assets) or a Publisher (sends a finished site to a destination), never both. A normal build never invokes a publisher.

BuildPlugin    load_plugin  -> PluginSession     process_source / process_html /
                                                 collect_assets; Drop unloads
Publisher      load_publisher -> PublisherSession   plan / publish / status / recover
Snapshot       snapshot(dir)  a frozen, checked copy of a built site; Drop removes it

Plugin authors implement a trait and, for an installed program, serve it with one call, serve (build hooks) or serve_publisher:

use std::borrow::Cow;
use gd_plugins::{BuildPlugin, Hooks, PluginInfo, Problem, SourceInput};

#[derive(Clone, Default)]
struct Shout;

impl BuildPlugin for Shout {
    fn info(&self) -> PluginInfo {
        PluginInfo::new("shout", "Shout", "1.0.0", Hooks { source: true, ..Hooks::NONE })
    }
    fn process_source<'a>(&mut self, input: &SourceInput<'a>)
        -> Result<Cow<'a, str>, Problem> {
        Ok(Cow::Owned(input.text.to_uppercase()))
    }
}

fn main() -> std::process::ExitCode {
    gd_plugins::serve(Shout)
}

Installed programs are recorded in the machine registry (read_machine, register, unregister), pinned by SHA-256, and reached through process_plugin and process_publisher. Nothing here discovers, downloads or starts a program by itself. Failures are Problems with hints, never panics.

Modules

  • gd_plugins::files – Private folders and files, and files replaced in one step: what a host or a publisher needs to keep state (a registry, tokens, a frozen site) that only its user may read.

Structs

pub struct gd_plugins::Asset

One generated file: a relative, portable path such as css/badge.css, and bytes.

Fields

pub path: String

The path below _static/plugins/ID/.

pub data: Vec<u8>

The file’s contents.

Implementations

impl Asset
pub fn new(path: &str, data: impl Into<Vec<u8>>) -> Asset

Makes an asset from a path and bytes.

pub struct gd_plugins::Hooks

Which build hooks a plugin offers.

Fields

pub source: bool

BuildPlugin::process_source.

pub html: bool

BuildPlugin::process_html.

pub assets: bool

BuildPlugin::collect_assets.

Implementations

impl Hooks
pub const NONE: Hooks

No hooks.

pub const ALL: Hooks = Hooks { source: true, html: true, assets: true }

Every hook.

pub fn is_any(self) -> bool

Whether at least one hook is offered.

pub fn names(self) -> impl Iterator<Item = &'static str>

The protocol names of the offered hooks, in the order source, html, assets.

#[non_exhaustive] pub struct gd_plugins::HtmlInput<'a>

One complete rendered HTML page before staging, borrowed for the call.

Hosts make it; it is #[non_exhaustive] so later fields are not a breaking change. Use the constructor, or Default and field assignment.

Fields

pub path: &'a str

The output page’s path.

pub docname: &'a str

The document’s name in the project.

pub language: &'a str

The build’s language.

pub text: &'a str

The complete page.

pub assets_url: &'a str

The URL of this plugin’s assets relative to the page, ending in /.

Implementations

impl<'a> HtmlInput<'a>
pub fn new(path: &'a str, docname: &'a str, language: &'a str, text: &'a str, assets_url: &'a str) -> HtmlInput<'a>

Describes one rendered page; assets_url is relative to it and ends in /.

pub struct gd_plugins::LoadContext<'a>

What BuildPlugin::load gets: the session’s options, and the dependency files and cache key that identify what it loaded. Both only grow: helpers append the fingerprints of the bytes they read, and nothing can erase them.

Implementations

impl<'a> LoadContext<'a>
pub fn options(&self) -> &PluginOptions

The session’s options.

pub fn dependencies(&self) -> &[String]

The dependency files declared so far.

pub fn cache_key(&self) -> &str

The cache key so far.

pub fn add_cache_key(&mut self, text: &str)

Appends text to the cache key: a fingerprint of anything loaded that is not a declared file, such as a selected environment value.

pub fn declare_dependency(&mut self, path: &str) -> Result<(), Problem>

Declares a file read by other means; the host hashes it before reusing output. Fails beyond 256 files or for an empty, overlong or NUL-holding path.

pub fn read_config(&mut self) -> Result<String, Problem>

Reads the configuration file (options.config, at most 1 MiB of UTF-8), declares it and adds its fingerprint to the cache key.

pub fn read_file(&mut self, path: &str) -> Result<String, Problem>

Reads a UTF-8 load input of at most 8 MiB, declares it and adds its fingerprint to the cache key. A relative path resolves from options.project. Fingerprinting the bytes actually read keeps old state from pairing with a newer file.

pub struct gd_plugins::PluginInfo

A build plugin’s identity: an ID (see crate::is_valid_id), a display name of at most 256 bytes, a product version of at most 64 bytes, the interface version it was built against, and its hooks.

Fields

pub id: String

The ID a project selects in conf.toml.

pub name: String

The name people see.

pub version: String

The plugin’s own release version.

pub api: Version

The build-plugin interface version, normally PLUGIN_API_VERSION.

pub hooks: Hooks

The hooks it offers.

Implementations

impl PluginInfo
pub fn new(id: &str, name: &str, version: &str, hooks: Hooks) -> PluginInfo

Describes a plugin built against PLUGIN_API_VERSION.

#[non_exhaustive] pub struct gd_plugins::PluginOptions

A build session’s settings. Paths are at most MAX_PATH bytes; builder and language names at most 64.

Hosts make it; it is #[non_exhaustive] so later fields are not a breaking change. Use the constructor, or Default and field assignment.

Fields

pub config: String

The plugin’s configuration file, from [plugin_configs]; may be empty.

pub project: String

The project folder; relative input paths resolve from it.

pub builder: String

The builder, such as html.

pub language: String

The build’s language.

pub request_timeout: Duration

Bounds each whole request to an installed program; zero means one minute. Linked plugins have no forced deadline.

pub cancel: Cancel

Stops the build between and during requests.

Implementations

impl PluginOptions
pub fn new(config: &str, project: &str, builder: &str, language: &str) -> PluginOptions

Options for one build: the plugin’s configuration file, the project folder, the builder and the language; the default timeout and no cancellation.

#[non_exhaustive] pub struct gd_plugins::SourceInput<'a>

One complete primary document before parsing, borrowed for the call. Includes are read by the engine later and do not pass through a source hook.

Hosts make it; it is #[non_exhaustive] so later fields are not a breaking change. Use the constructor, or Default and field assignment.

Fields

pub path: &'a str

The document’s file path.

pub docname: &'a str

The document’s name in the project, such as guide/install.

pub format: SourceFormat

Its markup.

pub language: &'a str

The build’s language, such as en.

pub text: &'a str

The complete text.

Implementations

impl<'a> SourceInput<'a>
pub fn new(path: &'a str, docname: &'a str, format: SourceFormat, language: &'a str, text: &'a str) -> SourceInput<'a>

Describes one primary document.

pub struct gd_plugins::PluginSession

One loaded build plugin, private to one build. It owns copied options, the plugin’s state, and the dependency files and cache key that identify what was loaded. Every hook call checks its input and the plugin’s reply. Dropping the session unloads the plugin (and ends its program, for an installed one).

Concurrency. A host opens one session per selected plugin per build; its state, cache key and dependencies belong to that build. Hooks take &mut self, so calls are serialized: call from one thread, or put the sessions in a Mutex shared by the reading workers (the session is Send, so Mutex<PluginSession> is Sync). A plugin therefore never needs synchronization of its own.

fn shared_by_workers<T: Send + Sync>() {}
shared_by_workers::<std::sync::Mutex<Vec<gd_plugins::PluginSession>>>();
shared_by_workers::<gd_plugins::Registry>();

Implementations

impl PluginSession
pub fn load(plugin: &Plugin, options: &PluginOptions) -> Result<PluginSession, Problem>

Starts a fresh plugin value and loads it with a copy of options. Fails for a publisher, invalid options, a load problem, or cancellation; a failed load is unloaded before this returns.

pub fn info(&self) -> &PluginInfo

The plugin’s identity and hooks, as read before load.

pub fn options(&self) -> &PluginOptions

The options the session was loaded with.

pub fn dependencies(&self) -> &[String]

The files load read; the host hashes them before reusing output.

pub fn cache_key(&self) -> &str

The fingerprint of everything else load used.

pub fn process_source<'a>(&mut self, input: &SourceInput<'a>) -> Result<Cow<'a, str>, Problem>

Runs the source hook on one primary document. Without a source hook the text is returned unchanged. Fails on input or output over 8 MiB, overlong names, a hook problem (with the plugin and stage named), or cancellation.

pub fn process_html<'a>(&mut self, input: &HtmlInput<'a>) -> Result<Cow<'a, str>, Problem>

Runs the HTML hook on one complete rendered page, as PluginSession::process_source does for source text.

pub fn collect_assets(&mut self) -> Result<Vec<Asset>, Problem>

Collects the plugin’s generated files, checked: at most 256 files and 16 MiB, portable relative paths, no duplicates ignoring case, no file used as a folder. The host stages them under _static/plugins/ID/.

Trait Implementations

impl std::fmt::Debug for PluginSession
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
pub struct gd_plugins::Cancel

A cancellation request a caller can raise while a plugin works. The default never cancels. Clones share one probe; the SDK polls it between and during requests.

Cancellation asks a plugin to stop; it cannot undo a write a target accepted.

Implementations

impl Cancel
pub fn from_flag(flag: Arc<AtomicBool>) -> Cancel

A probe that reads flag, which a signal handler or another thread may set.

pub fn from_fn(probe: impl Fn() -> bool + Send + Sync + 'static) -> Cancel

A probe that calls probe; it must be cheap, as it is polled often.

pub fn is_cancelled(&self) -> bool

Whether cancellation has been requested.

Trait Implementations

impl fmt::Debug for Cancel
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
pub struct gd_plugins::BuildRequest

What a contributed command asks the host to build: a Guidedog project with one builder into a folder, with settings overridden as -D does, the site’s public URL, and warnings as errors when strict. The default builds HTML.

Fields

pub project: PathBuf

The project folder (where conf.toml is).

pub output: PathBuf

The folder the output is written to.

pub builder: String

The builder, as guidedog build names it (html, dirhtml, singlehtml, pdf, text); empty for html.

pub overrides: Vec<String>

Settings that replace conf.toml’s, each name=value as -D takes them.

pub base_url: String

The site’s public URL (html_baseurl); empty to keep the project’s.

pub strict: bool

Build with warnings as errors.

pub now: String

Fixed RFC 3339 publication clock; empty uses the host’s build clock.

pub preview: bool

Include withheld pages in a separate preview publication.

pub struct gd_plugins::CommandContext<'h>

Everything a contributed command may use: the host’s streams, questions to the person, the host’s build, and plain facts about the run in public fields.

Fields

pub dir: PathBuf

The working folder the command was started in.

pub config: String

The plugin’s configuration file, when the project names one (conf.toml’s plugin_configs); empty for the plugin’s own default.

pub host_program: String

The host program, for a command that must start it (such as a watch loop).

pub interactive: bool

A person may be asked: input and error output are a terminal.

pub color: bool

The person asked for colors on the terminal.

pub json: bool

The person asked for JSON reports (--diagnostics=json).

pub quiet: bool

The person asked for no success messages (-q).

pub cancel: Cancel

Set when the person asks the command to stop (Ctrl+C).

Implementations

impl<'h> CommandContext<'h>
pub fn new(host: &'h mut dyn CommandHost) -> CommandContext<'h>

A context over host, in the current folder, not interactive, with no colors, no configuration and no cancellation; the host sets the fields it knows.

pub fn streams(&mut self) -> (&mut dyn Write, &mut dyn Write)

The host’s standard output and standard error.

pub fn print(&mut self, text: &str)

Writes text to standard output. A closed output is not the command’s problem.

pub fn eprint(&mut self, text: &str)

Writes text to standard error.

pub fn flush(&mut self)

Flushes both streams, before another program writes to the same terminal.

pub fn ask(&mut self, question: &str) -> Option<String>

Shows question on standard error and returns the person’s answer, trimmed; None when no person may be asked or the input ended.

pub fn confirm(&mut self, question: &str) -> bool

Asks a yes-or-no question; anything but y or yes, or no person, is no.

pub fn build_project(&mut self, request: &BuildRequest) -> Result<(), Problem>

Has the host build request’s project; see CommandHost::build_project.

Trait Implementations

impl fmt::Debug for CommandContext<'_>
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
pub struct gd_plugins::CommandInfo

A command a plugin adds to the host’s command line. Its path is the words that name it: ["pages", "workflow"] is guidedog pages workflow, and ["publish", "pages"] is the target pages of guidedog publish.

Fields

pub path: Vec<String>

The words that name the command: 1 to 4 lowercase words.

pub summary: String

One line saying what it does, for the host’s command list.

pub help: String

What --help shows after the usage line: plain text, lines of at most 80 characters.

pub options: Vec<CommandOption>

The options it takes, for its help and the host’s suggestions.

Implementations

impl CommandInfo
pub fn new(name: &str, summary: &str) -> CommandInfo

A command named by the words of name ("pages workflow"), with its summary.

pub fn with_help(mut self, help: &str) -> CommandInfo

The command with help as its help text.

pub fn with_option(mut self, option: CommandOption) -> CommandInfo

The command with option added to its options.

pub fn name(&self) -> String

The command’s name: its words joined by spaces, such as pages workflow.

pub struct gd_plugins::CommandOption

An option a contributed command takes, as its help shows it.

Fields

pub name: String

The option as written, such as --write or -o.

pub value: String

The placeholder of its value, such as DIR; empty for a switch.

pub summary: String

One line saying what it does.

Implementations

impl CommandOption
pub fn switch(name: &str, summary: &str) -> CommandOption

A switch, such as --write.

pub fn with_value(name: &str, value: &str, summary: &str) -> CommandOption

An option that takes a value, such as --project DIR.

pub fn takes_value(&self) -> bool

Whether the option takes a value.

pub struct gd_plugins::Machine

The registry’s entries.

Fields

pub entries: Vec<MachineEntry>

Every registered program, in registration order.

Implementations

impl Machine
pub fn find(&self, id: &str) -> Option<&MachineEntry>

The entry with the ID id.

#[non_exhaustive] pub struct gd_plugins::MachineEntry

One registered program, as inspect_entry describes it and the registry keeps it.

Fields

pub id: String

The plugin’s ID.

pub name: String

Its display name.

pub version: String

Its product version.

pub path: String

The program’s absolute path.

pub sha256: String

The program’s SHA-256 in hexadecimal.

pub protocol: Version

The protocol version selected when it was registered.

pub capabilities: Capabilities

A publisher’s optional operations.

pub registered: String

The date it was registered, YYYY-MM-DD.

pub protocol_name: String

BUILD_PROTOCOL_NAME for a build plugin; empty for a publisher.

pub hooks: Vec<String>

A build plugin’s hook names; empty for a publisher.

pub commands: Vec<CommandInfo>

The commands the program contributes to the command line; empty for none.

pub command_protocol: Version

The command protocol version selected when it was registered; 0.0 when it contributes no command.

Implementations

impl MachineEntry
pub fn is_build(&self) -> bool

Whether the entry is a build plugin’s.

pub struct gd_plugins::Problem(_)

A failure: a stable code ("pages.credential"), a title, the path or name it concerns, what went wrong, a hint that says what to do, and the exit status a command returns for it (always nonzero for a real problem).

Exit statuses beyond 0 are 1 (failed, nothing published), 2 (usage or configuration), 3 (memory or a limit), 4 (files or processes), EXIT_ACCEPTED, EXIT_UNKNOWN and 130 (cancelled).

The fields live in a ProblemData box, so Result<T, Problem> stays one pointer wide; read and write them directly (p.code, p.exit = 2) through Deref.

Implementations

impl Problem
pub fn new(code: &str, title: &str, message: &str) -> Problem

Starts a problem with exit status 1 and no path or hint; chain Problem::hint, Problem::path and Problem::exit to complete it.

pub fn hint(mut self, hint: &str) -> Problem

Sets the hint and returns the problem, for chaining.

pub fn path(mut self, path: &str) -> Problem

Sets the path the problem concerns and returns it, for chaining.

pub fn exit(mut self, exit: i32) -> Problem

Sets the exit status and returns the problem, for chaining.

pub fn memory() -> Problem

plugins.memory (exit 3): memory, or a buffer driven by input size, was refused.

pub fn report(&self) -> Report

Converts the problem into an Elm-style report for gd_report::render_text.

Trait Implementations

impl std::ops::Deref for Problem
type Target = ProblemData
fn deref(&self) -> &ProblemData
impl std::ops::DerefMut for Problem
fn deref_mut(&mut self) -> &mut ProblemData
impl fmt::Display for Problem
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl std::error::Error for Problem
impl From<ProblemData> for Problem
fn from(data: ProblemData) -> Problem
pub struct gd_plugins::ProblemData

The fields of a Problem. Build one with struct-update syntax and convert it with .into(), or start from Problem::new.

Fields

pub code: String

A stable identifier such as "plugins.timeout".

pub title: String

A short sentence naming what failed.

pub path: String

The path or name the problem concerns; may be empty.

pub message: String

The plain explanation.

pub hint: String

What to do about it.

pub exit: i32

The exit status a command returns for this problem.

pub struct gd_plugins::Capabilities

A publisher’s optional operations.

Fields

pub status: bool

Publisher::status.

pub recover: bool

Publisher::recover.

Implementations

impl Capabilities
pub fn names(self) -> impl Iterator<Item = &'static str>

The protocol names of the capabilities, in the order status, recover.

pub fn from_names<'a>(names: impl IntoIterator<Item = &'a str>) -> Capabilities

The capabilities names lists; unknown names are ignored.

pub fn is_subset_of(self, other: Capabilities) -> bool

Whether every capability of self is also in other.

pub struct gd_plugins::Change

One file publishing adds, changes or removes.

Fields

pub path: String

The file’s path in the site.

pub kind: ChangeKind

What happens to it.

#[non_exhaustive] pub struct gd_plugins::LoadOptions

A publisher session’s settings. The default is a real (not dry) run with the publisher’s own wait and a five-minute request limit for programs. It is #[non_exhaustive]: use LoadOptions::new or Default, then assign fields.

Fields

pub config: String

The publisher’s configuration file, such as pages.toml.

pub dry_run: bool

The session only plans: it never writes to the target.

pub wait_seconds: i64

How long publish waits for a deployment to be confirmed: 0, the publisher’s default; below 0, not at all (the outcome is then at most Accepted).

pub cancel: Cancel

Asks the publisher to stop; it cannot undo a write the target accepted.

pub request_timeout: Duration

Bounds each whole exchange with a program; zero means five minutes.

Implementations

impl LoadOptions
pub fn new(config: &str) -> LoadOptions

Options for a real run with the configuration file config.

pub struct gd_plugins::Loaded

What Publisher::load returns: the source, and the target described for people, such as "github.com/owner/repo, branch gh-pages".

Fields

pub source: Source

What to publish.

pub target: String

Where it goes.

pub struct gd_plugins::Outcome

The outcome of publish, status or recover: a state, the operation’s ID, the generation it concerns (hexadecimal), the URL the site is seen at, and, unless the outcome is verified, a problem that explains it.

Fields

pub state: State

Where the publication stands.

pub operation: String

The operation’s ID, for status and recover.

pub generation: String

The generation’s digest in hexadecimal.

pub url: String

Where the site is seen.

pub problem: Option<Problem>

Why the outcome is not verified.

Implementations

impl Outcome
pub fn failed(problem: Problem) -> Outcome

A Failed outcome with problem.

pub fn exit_status(&self) -> i32

The exit status a command returns: 0 when verified (Live, Unchanged), EXIT_ACCEPTED for Accepted or Pending, EXIT_UNKNOWN for Unknown, and the problem’s status (at least 1) otherwise.

pub struct gd_plugins::Plan

What publishing a snapshot to a session’s target would do. A plan is published only by the session that made it, with the snapshot it was made from.

Fields

pub target: String

The target, for people.

pub baseline: String

The target state compared with, as the publisher names it; empty for none.

pub unchanged: bool

The target already holds the generation; changes is then empty.

pub changes: Vec<Change>

The changes, in the publisher’s order.

pub summary: String

What a person should see first, such as the account.

pub data: Option<Box<dyn Any + Send>>

The publisher’s own data for publish; see Plan::data_as.

Implementations

impl Plan
pub fn generation(&self) -> [u8; 32]

The generation the plan publishes: the snapshot’s digest.

pub fn generation_hex(&self) -> String

The generation in lowercase hexadecimal.

pub fn id(&self) -> &str

The plan’s name in its session, for the process protocol; may be empty.

pub fn data_as<T: 'static>(&self) -> Option<&T>

The publisher’s data, if it is a T.

Trait Implementations

impl fmt::Debug for Plan
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
pub struct gd_plugins::PublisherInfo

A publisher’s identity: ID, name, product version, the interface version it was built against, and its optional operations.

Fields

pub id: String

The ID users select, such as pages.

pub name: String

The name people see.

pub version: String

The publisher’s own release version.

pub api: Version

The publisher interface version, normally API_VERSION.

pub capabilities: Capabilities

Its optional operations.

Implementations

impl PublisherInfo
pub fn new(id: &str, name: &str, version: &str, capabilities: Capabilities) -> PublisherInfo

Describes a publisher built against API_VERSION.

pub struct gd_plugins::Source

What a session publishes: a Guidedog project to build as HTML (with warnings as errors when strict), or a folder holding a site already built; exactly one of project and site is set. base_url is where the site is seen.

Fields

pub project: String

A project folder to build.

pub site: String

A built site’s folder.

pub base_url: String

The site’s public URL.

pub strict: bool

Build with warnings as errors.

pub struct gd_plugins::Plugin

A plugin an application offers: build hooks or a publisher, never both. It makes a fresh plugin value for every session, so sessions never share state.

Implementations

impl Plugin
pub fn build<P: BuildPlugin + Clone + Sync + 'static>(prototype: P) -> Plugin

Offers build hooks. Each session starts from a clone of prototype, the unloaded plugin, and its info is read once, here.

pub fn publisher<P: Publisher + Clone + Sync + 'static>(prototype: P) -> Plugin

Offers a publisher. Each session starts from a clone of prototype.

pub fn commands(&self) -> &[CommandInfo]

The commands the plugin adds to the host’s command line, in its order.

pub fn run_command(&self, ctx: &mut CommandContext<'_>, name: &str, args: &[String]) -> Result<i32, Problem>

Runs the contributed command name (its words joined by spaces, such as pages workflow) with args, the words after its name, and returns its exit status. A linked plugin runs it on a fresh value; an installed program is started with crate::COMMAND_FLAG on the host’s terminal. Fails when the plugin contributes no such command, or the command or its program fails.

pub fn id(&self) -> &str

The plugin’s ID.

pub fn build_info(&self) -> Option<&PluginInfo>

The build plugin’s identity and hooks; None for a publisher.

pub fn publisher_info(&self) -> Option<&PublisherInfo>

The publisher’s identity and capabilities; None for build hooks.

pub fn is_publisher(&self) -> bool

Whether this plugin is a publisher.

pub fn executable(&self) -> &str

The installed program it runs, for crate::process_plugin and crate::process_publisher; empty for a linked plugin.

pub fn identity(&self, host_build: &str) -> String

The plugin’s identity for build cache keys: what must change for outputs it produced to be rebuilt. For an installed program it is the registered program’s SHA-256, which pins its exact code. For a linked plugin it is the SHA-256 of its ID, product version and interface version together with host_build, the host program’s own build identity (its version and commit, or its executable’s digest), since the plugin’s code is part of the host. Lowercase hexadecimal.

pub fn validate(&self) -> Result<(), Problem>

Checks the plugin’s metadata without running any of its hooks.

Trait Implementations

impl fmt::Debug for Plugin
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
pub struct gd_plugins::Registry

The plugins an application offers, checked when it is made: every plugin is valid (its commands included) and has its own ID. Running nothing, it never executes a plugin’s hooks.

Implementations

impl Registry
pub fn new(plugins: Vec<Plugin>) -> Result<Registry, Problem>

Makes a registry of plugins; fails on the first invalid or repeated one.

pub fn find(&self, id: &str) -> Option<&Plugin>

The plugin with exactly the ID id.

pub fn plugins(&self) -> &[Plugin]

Every plugin, in the order given.

pub fn commands(&self) -> impl Iterator<Item = (&Plugin, &CommandInfo)>

Every contributed command with the plugin that runs it, in the plugins‘ order.

pub struct gd_plugins::PublisherSession

One publisher, loaded with its configuration and target. Dropping the session unloads the publisher (and ends its program, for an installed one). One session runs one operation at a time; it is Send, so a caller-owned worker may hold it.

Implementations

impl PublisherSession
pub fn load(plugin: &Plugin, options: &LoadOptions) -> Result<PublisherSession, Problem>

Starts a fresh publisher value and has it read its configuration and target. Fails for a build plugin or a load problem; a failed load is unloaded before this returns.

pub fn info(&self) -> &PublisherInfo

The publisher’s identity and capabilities.

pub fn options(&self) -> &LoadOptions

The options the session was loaded with.

pub fn source(&self) -> &Source

What the configuration says to publish.

pub fn target(&self) -> &str

The target, described for people.

pub fn plan(&mut self, snapshot: &Snapshot) -> Result<Plan, Problem>

Compares snapshot with the target and returns what publishing it would change. It only reads the target. A plan that calls the target unchanged yet lists changes breaks the contract.

pub fn publish(&mut self, snapshot: &Snapshot, plan: &Plan) -> Outcome

Publishes plan, made by this session from snapshot, after checking the snapshot’s files again. A dry-run session never publishes. An outcome that names another generation, or no operation, is Unknown, never success.

pub fn status(&mut self, operation: &str) -> Outcome

Reads the outcome of operation again ("" for the last one), writing nothing.

pub fn recover(&mut self) -> Outcome

Settles an operation interrupted at the target’s boundary: reads what the target holds and finishes or reports the operation, never forcing the target back.

Trait Implementations

impl std::fmt::Debug for PublisherSession
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
pub struct gd_plugins::Entry

One file of a snapshot: its path from the root with / between folders, its size, and the SHA-256 of its contents. Schema 1 publishes every file as a regular, non-executable file.

Fields

pub path: String

The path from the root.

pub size: u64

The size in bytes.

pub digest: [u8; 32]

The SHA-256 of the contents.

pub struct gd_plugins::Snapshot

A complete, checked site: its folder, its files in the order of their paths‘ bytes, their total size, and its digest, which names the generation. Dropping a snapshot that is not borrowed removes its private folder.

Implementations

impl Snapshot
pub fn root(&self) -> &Path

The folder holding the site’s files.

pub fn entries(&self) -> &[Entry]

The files, sorted by path bytes.

pub fn bytes(&self) -> u64

The total size in bytes.

pub fn digest(&self) -> [u8; 32]

The generation’s digest.

pub fn mode(&self) -> SnapshotMode

How the snapshot holds its files.

pub fn verify(&self) -> Result<(), Problem>

Reads the folder again and checks it holds exactly these files with these contents. A frozen site that changed is refused before anything is published.

Trait Implementations

impl Drop for Snapshot
fn drop(&mut self)
#[non_exhaustive] pub struct gd_plugins::SnapshotOptions

Bounds and placement of a snapshot. Zero bounds mean the defaults: 100,000 files, files under 100 MiB, and 1 GiB in all.

It is #[non_exhaustive]: use SnapshotOptions::new or Default, then assign.

Fields

pub mode: SnapshotMode

How the snapshot holds its files.

pub temp_dir: Option<PathBuf>

Copy: where the private folder is made; None: the system’s temporary folder.

pub max_files: usize

The most files.

pub max_file_bytes: u64

The largest file, in bytes.

pub max_bytes: u64

The most bytes in all.

pub no_index: bool

Accept a site without index.html at its root.

Implementations

impl SnapshotOptions
pub fn new(mode: SnapshotMode) -> SnapshotOptions

Default bounds, held as mode says.

#[non_exhaustive] pub struct gd_plugins::Handshake

The first line a plugin program writes: the protocol, the highest minor version of each major version it speaks, the interface version it was built against, what it is, its capabilities (publishers), the snapshot schemas it reads (publishers), its hooks (build plugins), and, optionally, the commands it contributes with the command protocol versions it speaks.

Fields

pub protocol: String

PROTOCOL_NAME or BUILD_PROTOCOL_NAME.

pub versions: Vec<Version>

The protocol versions spoken.

pub api: Version

The interface version built against.

pub id: String

The plugin’s ID.

pub name: String

Its display name.

pub version: String

Its product version.

pub capabilities: Vec<String>

A publisher’s optional operations.

pub snapshot_schemas: Vec<i64>

The snapshot schemas a publisher reads.

pub hooks: Vec<String>

A build plugin’s hooks.

pub commands: Vec<CommandInfo>

The commands the plugin adds to the host’s command line (optional; a host that does not know them ignores them).

pub command_versions: Vec<Version>

The command protocol versions it speaks; set when commands is not empty.

Implementations

impl Handshake
pub fn is_build(&self) -> bool

Whether this is a build plugin’s handshake.

pub struct gd_plugins::Version

A major and minor version. A minor version adds only optional things to its major version; a major version changes or removes something.

Fields

pub major: u16

Incompatible changes.

pub minor: u16

Optional additions.

Implementations

impl Version
pub const fn new(major: u16, minor: u16) -> Version

Makes a version from its two numbers.

pub fn is_compatible_with(self, host: Version) -> bool

Whether code built against self can serve a host speaking host: the same major version and a minor version the host knows.

Trait Implementations

impl std::fmt::Display for Version
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result

Enums

pub enum gd_plugins::SourceFormat

The markup of a source document.

Variants

Rst

reStructuredText.

Markdown

CommonMark or MyST Markdown.

Implementations

impl SourceFormat
pub fn name(self) -> &'static str

The protocol name: "rst" or "markdown".

pub fn from_name(name: &str) -> Option<SourceFormat>

The format the protocol calls name.

pub enum gd_plugins::ChangeKind

What publishing a file does to the target.

Variants

Added

A new file.

Changed

A file with other contents.

Removed

A file the generation no longer has.

Implementations

impl ChangeKind
pub fn name(self) -> &'static str

The protocol’s name: "added", "changed" or "removed".

pub fn from_name(name: &str) -> Option<ChangeKind>

The kind the protocol calls name.

pub enum gd_plugins::State

Where a publication stands.

Variants

NotStarted

No outcome: the publisher reported nothing.

Unchanged

The target already holds this generation; nothing was written.

Accepted

The host accepted the generation; its deployment is not confirmed.

Pending

The deployment of the generation is under way.

Live

The generation is confirmed live.

Failed

Nothing was published, or the deployment failed.

Unknown

The outcome is not known: inspect it before writing again.

Implementations

impl State
pub fn name(self) -> &'static str

The protocol’s name, such as "live".

pub fn from_name(name: &str) -> Option<State>

The state the protocol calls name.

pub enum gd_plugins::SnapshotMode

How a snapshot holds its files.

Variants

Copy

Copies the folder into a private folder, which dropping the snapshot removes.

Borrow

Checks the folder where it is; the caller keeps it, unchanged.

Adopt

Checks a private folder where it is; dropping the snapshot removes it.

Traits

pub trait gd_plugins::BuildPlugin: Send

Build hooks: transformations of source text and complete HTML pages, and generated static files. Every hook has a default meaning „service absent“ (text passes through unchanged; no assets); PluginInfo::hooks declares which ones a plugin offers.

A plugin value is one session’s state: BuildPlugin::load prepares it, the hooks read it, and dropping the value unloads it (close files or children in Drop). Hooks run one at a time; a plugin needs no synchronization of its own. Linked plugins are trusted code: a panic or a hang in a hook reaches the host. Run an untrusted plugin as a program instead (crate::process_plugin).

fn info(&self) -> PluginInfo

What the plugin is and which hooks it offers. It must not change over the value’s life; the SDK reads it once, before load.

fn load(&mut self, ctx: &mut LoadContext<'_>) -> Result<(), Problem>

Prepares the session: reads configuration through ctx (which fingerprints what it reads) and keeps what the hooks need in self. The default does nothing.

fn process_source<'a>(&mut self, input: &SourceInput<'a>) -> Result<Cow<'a, str>, Problem>

Returns the complete replacement of a primary source document, before parsing. Borrow input.text when nothing changes. The default returns it unchanged.

fn process_html<'a>(&mut self, input: &HtmlInput<'a>) -> Result<Cow<'a, str>, Problem>

Returns the complete replacement of a rendered HTML page, before staging. The default returns it unchanged.

fn collect_assets(&mut self) -> Result<Vec<Asset>, Problem>

Returns generated files, staged under _static/plugins/ID/. Paths are relative and portable; the same loaded settings must give the same files in the same order. The default returns none.

fn commands(&self) -> Vec<CommandInfo>

The commands the plugin adds to the host’s command line; constant over the value’s life. The default adds none.

fn run_command(&mut self, ctx: &mut CommandContext<'_>, name: &str, args: &[String]) -> Result<i32, Problem>

Runs the contributed command name (its words joined by spaces, as CommandInfo::name gives them) with the arguments after its name, and returns the exit status. Runs on a fresh, unloaded value. The default refuses.

Implementors

impl BuildPlugin for Box<dyn BuildPlugin>
impl BuildPlugin for Fixture
impl BuildPlugin for Linked
impl BuildPlugin for Paths
impl BuildPlugin for ProcessPlugin
pub trait gd_plugins::CommandHost

What a host offers a contributed command. guidedog implements it over its own terminal and engine; the SDK implements it over a program’s standard streams when a command runs as an installed program (crate::serve_command).

fn streams(&mut self) -> (&mut dyn Write, &mut dyn Write)

The command’s standard output and standard error, together, since a command often writes to both at once.

fn read_line(&mut self) -> Option<String>

Reads one line the person typed, without its line break; None at the end of the input.

fn build_project(&mut self, request: &BuildRequest) -> Result<(), Problem>

Builds request’s project, as guidedog build does; the build’s report goes to the host’s error stream. Fails when the build fails or the host builds nothing.

Implementors

impl CommandHost for NoHost
impl CommandHost for StdHost
pub trait gd_plugins::Publisher: Send

A publisher sends a complete, frozen site to a destination such as GitHub Pages.

The value is one session’s state: Publisher::load reads the configuration and names the target, the other methods work on it, and dropping the value unloads it (release locks, children and secrets in Drop). The SDK wrappers in crate::PublisherSession hold every result to the contract, so a publisher that reports no outcome, or the wrong generation, never passes for success.

fn info(&self) -> PublisherInfo

What the publisher is and its optional operations; constant over its life.

fn load(&mut self, options: &LoadOptions) -> Result<Loaded, Problem>

Reads the configuration (options.config) and returns what to publish and where. A dry-run session must not take locks or credentials it does not need.

fn plan(&mut self, snapshot: &Snapshot, plan: &mut Plan) -> Result<(), Problem>

Compares snapshot with the target, reading only, and fills in plan, whose generation is already the snapshot’s digest.

fn publish(&mut self, snapshot: &Snapshot, plan: &Plan) -> Outcome

Carries out plan, made by this session from snapshot, which the SDK has checked again, and returns the verified outcome.

fn status(&mut self, operation: &str) -> Outcome

Reads the outcome of operation again ("": the last one), writing nothing. Called only when Capabilities::status is declared.

fn recover(&mut self) -> Outcome

Settles an operation interrupted at the target’s boundary. Called only when Capabilities::recover is declared.

fn commands(&self) -> Vec<CommandInfo>

The commands the publisher adds to the host’s command line, such as a guided publish target; constant over the value’s life. The default adds none.

fn run_command(&mut self, ctx: &mut CommandContext<'_>, name: &str, args: &[String]) -> Result<i32, Problem>

Runs the contributed command name (its words joined by spaces) with the arguments after its name, and returns the exit status. Runs on a fresh, unloaded value. The default refuses.

Implementors

impl Publisher for Box<dyn Publisher>
impl Publisher for Nothing
impl Publisher for ProcessPublisher
impl Publisher for Test

Functions

pub fn gd_plugins::load_plugin(registry: &Registry, id: &str, options: &PluginOptions) -> Result<PluginSession, Problem>

Loads the build plugin id of registry with options: the one-call path to PluginSession::load. Fails when the registry has no such build plugin.

pub fn gd_plugins::check_plugin(plugin: &Plugin, options: &PluginOptions) -> Result<(), Problem>

Exercises a build plugin’s declared hooks: two fresh loads, each running every hook twice on representative documents and checking the results repeat, then unloading. It never invokes a publisher. Passing shows interoperability, not safety: a linked plugin runs in this process; check an installed program through crate::process_plugin for crash isolation.

pub fn gd_plugins::config_dir() -> Result<PathBuf, Problem>

The folder of Guidedog’s machine state: $GUIDEDOG_CONFIG_DIR, or a guidedog folder in the user’s configuration folder. Fails when the system names none.

pub fn gd_plugins::inspect_entry(path: &str) -> Result<MachineEntry, Problem>

Describes the program at path as a registry entry: checks that path is an absolute path to a native program (not a script), takes its SHA-256, and runs it in protocol mode to read its handshake. Running it runs its code: call it only for a program the user chose.

pub fn gd_plugins::machine_path() -> Result<PathBuf, Problem>

The registry’s file: MACHINE_FILE in config_dir.

pub fn gd_plugins::read_machine(path: &Path) -> Result<Machine, Problem>

Reads the registry at path; a missing file is an empty registry. Fails for a file over 1 MiB, invalid TOML, another schema, or a malformed or repeated entry.

pub fn gd_plugins::register(path: &Path, entry: &MachineEntry) -> Result<(), Problem>

Adds entry to the registry at path, which it creates, with its folder, readable only by the user. Refuses an incomplete entry and an ID registered already.

pub fn gd_plugins::unregister(path: &Path, id: &str) -> Result<(), Problem>

Removes the entry id from the registry at path. It removes nothing else: not the program, a site, nor a stored credential.

pub fn gd_plugins::verify_entry(entry: &MachineEntry) -> Result<(), Problem>

Checks that the program entry names is still the one registered: it exists and has the registered SHA-256.

pub fn gd_plugins::process_plugin(entry: &MachineEntry) -> Result<Plugin, Problem>

A build plugin that runs the registered program entry, one program a session: load starts it and checks its identity and hooks against the entry, dropping the session ends it. Verify the entry (crate::verify_entry) before offering it. Fails for a publisher’s entry or undeclared hook names.

pub fn gd_plugins::build_command(program: &str, request: &BuildRequest) -> Command

The guidedog build -b BUILDER PROJECT OUTPUT that carries out request, with its settings, clock and switches as arguments, and its streams left as the caller sets them. program names the Guidedog program. Borrows both; starts nothing.

pub fn gd_plugins::build_with_program(program: &str, request: &BuildRequest) -> Result<(), Problem>

Builds request’s project by starting program (a guidedog) with build -b BUILDER PROJECT OUTPUT; its report and output go to standard error, so that a command’s standard output stays its result. Fails when program is empty or cannot start, or the build fails.

pub fn gd_plugins::serve_command(plugin: &Plugin, request: &str) -> u8

Runs the command a host’s request (the argument after COMMAND_FLAG) names, with plugin, on the program’s standard streams, and returns the exit status. A problem is reported on standard error, as the request asks (text or JSON). A project build asked of the host runs the host program the request names.

let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() == 2 && args[0] == gd_plugins::COMMAND_FLAG {
    std::process::exit(i32::from(gd_plugins::serve_command(&plugin(), &args[1])));
}
pub fn gd_plugins::inspect_program(executable: &str, timeout: Duration) -> Result<Handshake, Problem>

Runs the program at executable in protocol mode, reads its handshake, and ends it, waiting at most timeout. Running it runs its code: call it only for a program the user chose.

pub fn gd_plugins::process_publisher(entry: &MachineEntry) -> Result<Plugin, Problem>

A publisher that runs the registered program entry in protocol mode, one program a session: load starts it and checks its handshake against the entry, dropping the session ends it. Verify the entry (crate::verify_entry) before offering it. Fails for a build plugin’s entry.

pub fn gd_plugins::select_build_plugin(linked: &Registry, id: &str, machine_file: &Path) -> Result<Plugin, Problem>

Finds the build plugin id as a build does: in linked, the plugins compiled into this program, and otherwise in the machine registry at machine_file, which is read only then. A registered program is verified against its SHA-256 before it is offered. Fails when neither has the ID, when the ID names a publisher, or when the registry or the program cannot be trusted.

pub fn gd_plugins::serve<P: BuildPlugin + 'static>(mut plugin: P) -> ExitCode

The whole main of a build-plugin program: when started with PROTOCOL_FLAG, it serves plugin over standard input and output until the host unloads it, and returns the program’s exit status; when started with crate::COMMAND_FLAG, it runs the contributed command the request names (crate::serve_command); otherwise it writes a one-line usage note to standard error and returns 2. Keep protocol output on stdout: log to stderr only.

fn main() -> std::process::ExitCode {
    gd_plugins::serve(Badge)
}
pub fn gd_plugins::serve_plugin(plugin: &Plugin) -> ExitCode

The whole main of a plugin crate’s program, serving the same Plugin a custom host links: build hooks as serve does, a publisher as crate::serve_publisher does. One implementation, two deployments:

// In the plugin crate's src/main.rs; its lib.rs exposes `pub fn plugin() -> Plugin`.
fn main() -> std::process::ExitCode {
    gd_plugins::serve_plugin(&badge::plugin())
}
pub fn gd_plugins::serve_streams<P: BuildPlugin + 'static>(plugin: P, mut input: impl BufRead, output: impl Write) -> u8

Serves plugin over input and output: writes the handshake, then answers the host’s requests until it unloads the plugin or closes input. Returns the exit status: 0 after unload or a closed input, 1 when the host broke the protocol or output failed, 2 for invalid plugin metadata.

pub fn gd_plugins::serve_publisher<P: Publisher + 'static>(mut publisher: P) -> ExitCode

The whole main of a publisher program: when started with crate::PROTOCOL_FLAG, it serves publisher over standard input and output until the host unloads it; started with crate::COMMAND_FLAG, it runs the contributed command the request names; otherwise it writes a one-line usage note to standard error and returns 2.

pub fn gd_plugins::serve_publisher_streams<P: Publisher + 'static>(publisher: P, mut input: impl BufRead, output: impl Write) -> u8

Serves publisher over input and output: writes the handshake, then answers requests until the host unloads it or closes input. Returns 0 then, 1 when the host broke the protocol or output failed, and 2 for invalid publisher metadata. The server keeps only the current session, snapshot and plan.

pub fn gd_plugins::load_publisher(registry: &Registry, id: &str, options: &LoadOptions) -> Result<PublisherSession, Problem>

Loads the publisher id of registry: the one-call path to PublisherSession::load. Fails when the registry has no such publisher.

pub fn gd_plugins::digest_hex(digest: &[u8; 32]) -> String

A digest in lowercase hexadecimal.

pub fn gd_plugins::snapshot(dir: impl AsRef<Path>, options: &SnapshotOptions) -> Result<Snapshot, Problem>

Freezes the site in dir: every regular file below it, checked and digested, held as options.mode says. Refuses a symbolic link or special file, a name Git or a static host cannot serve, two names that differ only in case, a site over the limits, and one without index.html (unless no_index). A refusal leaves no private folder behind.

pub fn gd_plugins::select_version(h: &Handshake) -> Option<Version>

The protocol version a host and the program whose handshake is h share: the same major version, at the lower minor version; None when they share none.

pub fn gd_plugins::is_valid_id(id: &str) -> bool

Whether id can name a plugin: 2 to 32 lowercase ASCII letters, digits and hyphens, starting with a letter.

Constants

pub const gd_plugins::MAX_COMMANDS: usize = 32

The most commands one plugin may contribute.

pub const gd_plugins::CONFIG_VARIABLE: &str = "GUIDEDOG_CONFIG_DIR"

When set, names the folder of Guidedog’s machine state instead of the user’s configuration folder, for tests and portable installations.

pub const gd_plugins::MACHINE_FILE: &str = "plugins.toml"

The registry’s file name in config_dir.

pub const gd_plugins::EXIT_ACCEPTED: i32 = 6

Exit status of a publication the host accepted but has not confirmed live yet.

pub const gd_plugins::EXIT_UNKNOWN: i32 = 7

Exit status of an outcome that is not known; inspect it with status or recover.

pub const gd_plugins::COMMAND_FLAG: &str = "--guidedog-command"

The argument that starts a plugin program to run one contributed command; the next argument is the request, one JSON object.

pub const gd_plugins::COMMAND_PROTOCOL_NAME: &str = "guidedog-command"

The command protocol’s name in a request.

pub const gd_plugins::COMMAND_PROTOCOL_VERSION: Version = Version { major: 1, minor: 0 }

The command protocol’s version: a handshake lists the versions it speaks in command_versions beside its commands.

pub const gd_plugins::DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(5 * 60)

Bounds a publisher request, including its write and response, when the options leave it zero.

pub const gd_plugins::HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10)

Bounds the wait for a program’s handshake.

pub const gd_plugins::MAX_BUILD_PLUGINS: usize = 64

The most build plugins one build may select.

pub const gd_plugins::API_VERSION: Version = Version { major: 1, minor: 1 }

The version of the publisher interface (Publisher).

pub const gd_plugins::PLUGIN_API_VERSION: Version = Version { major: 1, minor: 0 }

The version of the build-plugin interface (BuildPlugin).

pub const gd_plugins::PROTOCOL_VERSION: Version = Version { major: 1, minor: 0 }

The publisher process protocol’s version.

pub const gd_plugins::BUILD_PROTOCOL_VERSION: Version = Version { major: 1, minor: 0 }

The build-plugin process protocol’s version.

pub const gd_plugins::PROTOCOL_FLAG: &str = "--guidedog-protocol"

The argument that starts a plugin program in protocol mode.

pub const gd_plugins::PROTOCOL_NAME: &str = "guidedog-publisher"

The publisher protocol’s name in a handshake.

pub const gd_plugins::BUILD_PROTOCOL_NAME: &str = "guidedog-build-plugin"

The build-plugin protocol’s name in a handshake.

pub const gd_plugins::SNAPSHOT_SCHEMA: i64 = 1

The version of the snapshot manifest and its digest.

pub const gd_plugins::MAX_REQUEST: usize = 1024 * 1024

The largest request line a publisher program reads (1 MiB).

pub const gd_plugins::MAX_RESPONSE: usize = 64 * 1024 * 1024

The largest response line or handshake a host reads (64 MiB).

pub const gd_plugins::MAX_PLUGIN_TEXT: usize = 8 * 1024 * 1024

The largest source or HTML text a hook receives or returns (8 MiB).

pub const gd_plugins::MAX_PLUGIN_ASSETS: usize = 256

The most generated assets one plugin may return.

pub const gd_plugins::MAX_PLUGIN_ASSET_BYTES: usize = 16 * 1024 * 1024

The most generated asset bytes one plugin may return (16 MiB).

pub const gd_plugins::MAX_PATH: usize = 1024

The longest path a plugin input, dependency or published file may have, in bytes.