编写原生插件¶
插件为 Guidedog 增加服务。构建插件可以转换源文本、修改已渲染的 HTML 页面,或提供静态文件。发布器把完成的网站发送到目标位置。这些服务都使用普通的 Odin 过程表。
本章实现一个产品标牌插件。它替换源文本中的 {{product}},在 HTML 页面上添加标签,并提供相应的 CSS。随后以 GitHub Pages 为例,说明同一套插件基础如何支持会影响外部系统的服务。
1. 理解接口边界¶
plugins.Plugin 描述插件。source、html 和 assets 过程都是可选的。过程为 nil 表示不提供该服务。load 准备私有状态,unload 关闭资源。构建由宿主负责。
源钩子在每份主 RST 或 Markdown 文档解析前执行,也适用于 PDF 和文本构建。include 仍由引擎读取。HTML 钩子接收完整页面,包括自动索引和附加页面。生成资源只用于 HTML,位于 _static/plugins/ID/。主机在插件初始化期间、读取文档之前收集一次资源,之后本次构建的资源固定不变;源钩子和 HTML 钩子不能再追加资源。
插件表只能包含构建钩子或发布器,不能同时包含两者。普通构建无法调用发布服务。安装的插件是受信任的原生程序,需要显式注册并固定可执行文件的 SHA-256。注册并不是沙箱。
2. 编译可运行的示例¶
从源码检出目录的根目录开始。按照仓库的构建说明编译 Guidedog,然后在本教程中使用这个宿主。示例包位于 examples/build-plugin/badge,可执行程序的入口在它的上一级目录。
在 macOS 或 Linux 上运行:
odin build examples/build-plugin -vet -strict-style -out:build/product-badge
build/guidedog quickstart build/plugin-tutorial -q -p Orbit -a Team
在 Windows 上,在 PowerShell 中运行以下命令:
odin build examples/build-plugin -vet -strict-style -out:build/product-badge.exe
build/guidedog.exe quickstart build/plugin-tutorial -q -p Orbit -a Team
第一条命令编译出可执行文件,第二条创建文档项目。配置完成后再注册插件。使用已打包插件的人不需要 Odin 编译器。
3. 为项目选择插件¶
将 build/plugin-tutorial/conf.toml 替换为:
project = "Orbit"
plugins = ["product-badge"]
plugin_timeout = 60
[plugin_configs]
product-badge = "badge.toml"
创建 build/plugin-tutorial/badge.toml:
product = "Orbit"
将 build/plugin-tutorial/index.rst 替换为:
Welcome
=======
Hello {{product}}.
配置路径相对于项目配置目录。插件按照 plugins 中的顺序运行。仅仅注册程序不会运行它。
写好配置后再注册插件。注册时先在子进程中检查构建插件,通过后才记录校验值。在 macOS 或 Linux 上:
build/guidedog plugin register product-badge ./build/product-badge \
--project=build/plugin-tutorial --config=badge.toml
在 Windows 上,用一条 PowerShell 命令:
build/guidedog.exe plugin register product-badge ./build/product-badge.exe --project=build/plugin-tutorial --config=badge.toml
4. 构建并查看结果¶
在 macOS 或 Linux 上运行:
build/guidedog build html build/plugin-tutorial -W
build/guidedog serve build/plugin-tutorial
在 Windows 上运行:
build/guidedog.exe build html build/plugin-tutorial -W
build/guidedog.exe serve build/plugin-tutorial
打开服务器打印的网址。页面会显示“Hello Orbit.”和 Orbit 徽章,样式表为 _static/plugins/product-badge/banner.css。将配置名称改为 Comet 后重建,正文和徽章都会变化。随后不改动再构建,便不会重写输出文件。
5. 阅读实现¶
下面的完整包就是第 2 步编译的源码。下载 badge.odin 和 main.odin,保留一份本地副本。请保留目录结构,或按自己的项目调整相对导入路径。
// A build plugin: typed source and HTML hooks, plus a generated CSS asset.
// Compile from the checkout root:
// odin build examples/build-plugin -out:build/product-badge
package product_badge
import "core:fmt"
import "core:strings"
import "../../../lib/plugins"
import "../../../lib/toml"
Settings :: struct { product: string }
// plugin describes services. Nil procedures mean services this plugin does not offer.
plugin :: proc() -> plugins.Plugin {
return {id = "product-badge", name = "Product badge", version = "1.0.0",
api = plugins.PLUGIN_API_VERSION, load = load, source = source,
html = html, assets = assets}
}
load :: proc(ctx: ^plugins.Plugin_Load_Context) -> plugins.Problem {
text, problem := plugins.read_plugin_config(ctx)
if problem.exit != 0 do return problem
root, error := toml.parse(text)
path := ctx.session.options.config
if error.line != 0 do return {"badge.toml", "Cannot read the badge settings",
fmt.aprintf("%s:%d", path, error.line), error.message,
"Write product = \"Orbit\" in this TOML file.", 2}
product := toml.get(&root, "product")
if product == nil || product.kind != .String || len(product.text) == 0 ||
len(product.text) > 256 || strings.contains_any(product.text, "\r\n\x00") {
return {"badge.product", "The product name is missing or invalid", path,
"product must be a nonempty string on one line, at most 256 bytes long.",
"Set product = \"Orbit\" in this file.", 2}
}
settings, err := new(Settings, ctx.allocator)
if err != nil do return plugins.memory()
settings.product = product.text // the session owns the configuration's parsed text.
ctx.session.data = settings
return {}
}
source :: proc(ctx: ^plugins.Source_Context) -> plugins.Problem {
settings := (^Settings)(ctx.session.data)
marker :: "{{product}}"
count := strings.count(ctx.input.text, marker)
growth := len(settings.product) - len(marker)
if growth > 0 && count > (plugins.MAX_PLUGIN_TEXT - len(ctx.input.text)) / growth {
return {"badge.source-size", "The expanded source would be too large", ctx.input.path,
"Replacing every product marker would exceed the 8 MiB source limit.",
"Use fewer markers, a shorter product name, or split the document.", 2}
}
text, _ := strings.replace_all(ctx.input.text, "{{product}}", settings.product,
ctx.allocator)
if plugins.memory_refused(ctx.allocator) do return plugins.memory()
ctx.text = text
return {}
}
html :: proc(ctx: ^plugins.Html_Context) -> plugins.Problem {
settings := (^Settings)(ctx.session.data)
if !strings.contains(ctx.input.text, "</head>") ||
!strings.contains(ctx.input.text, "</body>") {
return {"badge.html", "The badge needs a complete HTML page", ctx.input.path,
"The selected template has no closing head or body tag.",
"Add </head> and </body> to the template, or disable product-badge for this build.", 2}
}
label := escape_html(settings.product)
css := fmt.aprintf("<link rel=\"stylesheet\" href=\"%sbanner.css\">\n</head>",
ctx.input.assets_url)
badge := fmt.aprintf("<aside class=\"product-badge\" aria-label=\"Product\">%s</aside>" +
"\n</body>", label)
growth := len(css) + len(badge) - len("</head></body>")
if growth > plugins.MAX_PLUGIN_TEXT - len(ctx.input.text) do return {
"badge.html-size", "The badge would exceed the HTML limit", ctx.input.path,
"This page has no room for the generated label and stylesheet link.",
"Split this page or shorten the configured product name.", 2}
head := replace_once(ctx.input.text, "</head>", css)
ctx.text = replace_once(head, "</body>", badge)
if plugins.memory_refused(ctx.allocator) do return plugins.memory()
return {}
}
replace_once :: proc(text, marker, replacement: string) -> string {
at := strings.last_index(text, marker)
return strings.concatenate({text[:at], replacement, text[at + len(marker):]})
}
CSS :: ".product-badge { border-inline-start: 3px solid #216553; " +
"padding: .5rem 1rem; margin: 1rem; font-weight: 700; }\n"
assets :: proc(ctx: ^plugins.Assets_Context) -> plugins.Problem {
files, err := make([]plugins.Plugin_Asset, 1, ctx.allocator)
if err != nil do return plugins.memory()
files[0] = {path = "banner.css", data = transmute([]u8)string(CSS)}
ctx.assets = files // collect_assets returns its own copy, including the static bytes.
return {}
}
escape_html :: proc(text: string) -> string {
escaped, _ := strings.replace_all(text, "&", "&")
escaped, _ = strings.replace_all(escaped, "<", "<")
escaped, _ = strings.replace_all(escaped, ">", ">")
return escaped
}
plugin() 是公开的描述符。load 读取有大小限制的 UTF-8 配置,检查类型和长度,并在会话中分配 Settings。源文本钩子先检查展开后的大小,再分配内存。它会替换所有标记,包括代码块中的标记。这是文本转换,不是标记语言解析。
HTML 钩子对标签文字做转义,把它插在最后一个 body 结束标签前。它使用宿主提供的 assets_url,保证嵌套页面也能正确链接 CSS。这个小示例要求 head 和 body 的结束标签使用小写字面形式。需要改写任意 HTML 的插件应使用合适的解析器,并说明自身的接口约定。
资源钩子用 ctx.allocator 分配结果数组。CSS 字节是静态数据。SDK 把路径和字节都复制到拥有独立内存的结果中。不要返回指向回调局部数组的切片。会话状态不能保留钩子输入或钩子结果的内存。
可执行程序的包装层通过标准流提供同一个描述符:
// Compile from the checkout root. This entry point adapts an ordinary Odin package
// to the installed-plugin protocol; embedded applications import badge directly.
package main
import "core:fmt"
import "core:os"
import "../../lib/plugins"
import "badge"
run :: proc() -> int {
if len(os.args) == 2 && os.args[1] == plugins.PROTOCOL_FLAG {
return plugins.serve_plugin(badge.plugin(), os.stdin, os.stdout)
}
fmt.eprintln("Run this plugin through guidedog build with plugins = [\"product-badge\"].")
return 2
}
main :: proc() { os.exit(run()) }
serve_plugin 负责协商和分发。协议输出写到 stdout,给人看的日志写到 stderr。在调用 os.exit 前先返回 main,让延迟清理正常执行。嵌入式宿主则在 project.Load_Options.plugins 中传入描述符,并在项目配置中选择其 ID。
6. 明确所有权与缓存¶
| 所有者 | 创建 | 释放 |
|---|---|---|
Plugin_Session |
load_plugin |
unload_plugin |
Text_Result |
process_source 或 process_html |
release_text |
Assets_Result |
collect_assets |
release_assets |
清理函数接受零值、失败值和已释放的所有者。用回调的分配器分配返回数据。检查分配错误;调用隐藏分配错误的辅助函数后,检查 plugins.memory_refused(ctx.allocator)。分配被拒绝时返回 plugins.memory()。卸载过程必须能处理只加载了一部分的会话。
加载时使用 read_plugin_config 和 read_plugin_file。它们记录实际读取字节的指纹,并声明文件依赖。整个构建期间保持已加载状态不变。如果自行读取其他文件,请把路径写入 session.dependencies,并把已加载值的指纹追加到 session.cache_key。用到的环境变量值也应追加进去。不要清除 SDK 辅助函数记录的指纹,也不要依赖未声明的可变数据。
宿主把身份、配置、依赖、缓存键、构建器、语言和生成资源纳入缓存失效判断。每次构建都有独立会话。读取线程按顺序调用回调,所以回调不必支持并发。进程请求的超时无法中断原生回调。已安装程序的每个完整请求都有时限,包括管道写入。
每次钩子调用的文本上限为 8 MiB。每个插件最多提供 256 个资源,字节总量不超过 16 MiB。路径必须是可移植的相对路径。重复名称、仅大小写不同的名称、路径穿越以及与项目文件的冲突都会被拒绝。--untrusted 禁用构建插件。子进程内存不计入宿主的构建预算;原生插件仍须检查分配结果和自身的限制。
7. 解释并测试错误¶
返回的 Problem 要有错误代码、标题、相关路径、原因、具体修正方法和非零退出状态。例如 product = 42 无效,标牌插件会说明需要字符串,并建议改为 product = "Orbit"。展开后的标记语言诊断会注明输入经过插件展开,并显示真实片段,不会把展开后的行号冒充为原文件行号。
既要直接测试包,也要通过可执行文件测试。覆盖配置变化、无改动重建、嵌套链接、无效标记语法、资源冲突、取消、超时和内存分配拒绝。构建失败必须保留上一版网站。仓库的集成测试编译本章这个示例,并检查 HTML、目录式 HTML、单页 HTML、纯文本和失败的输出代次。
8. 添加发布服务¶
GitHub Pages 使用同样的显式描述符基础:
package main
import "core:fmt"
import "guidedog:pages"
import "guidedog:plugins"
main :: proc() {
descriptor := plugins.publisher_plugin(pages.publisher())
fmt.println(descriptor.id)
}
它的 Publisher 提供 load、plan、publish、status 和 recover。会话拥有配置和凭据,快照拥有已检查的网站文件,计划将快照与目标的基准状态比较,结果报告已验证的结局。每个所有者都用对应的 SDK 过程释放。
从 examples/pages-publisher/main.odin 跟进到 lib/pages:配置和机器绑定确定权限;规划读取目标;发布先写入持久日志,再进行一次条件式 Git 推送;状态查询和恢复确定最终结果。源文本或 HTML 回调不会因此获得发布权限。
远端接受请求不等于部署已经上线。Accepted 和 Pending 返回 6;结果不明的写入返回 Unknown 和 7,并给出查询状态或恢复的方向。不要盲目重试不确定的写入。完整操作见 发布到 GitHub Pages,API 参考见 Publisher。
9. 对接口约定进行版本管理与分发¶
构建插件 API 1.0 使用 guidedog-build-plugin 1.0 协议。发布器 SDK 1.1 保留 guidedog-publisher 1.0 协议,并接受 SDK 1.0 发布器。两者是独立约定;旧宿主会拒绝构建插件,而不是把它当作发布器。产品版本与接口版本也彼此独立。
每次重新编译后都应明确注册可执行文件。guidedog plugin inspect ID 显示类型和声明的钩子。公共目录只介绍插件,不会下载、安装或运行它们。自定义标记语言读取器和渲染器仍使用编译进程序的 core.Registry API。通过安装添加自定义指令、角色和构建器不属于本构建钩子接口。
10. 注册前检查插件¶
guidedog plugin check PATH --project=DIR --config=FILE 检查构建插件,但不修改注册表。注册时也会执行相同检查:两次全新加载、重复的源文本和 HTML 结果、资源验证及清理。--timeout=SECONDS 默认给每个进程请求 60 秒。插件需要配置时,请提供真实配置。相对配置路径以 --project 为基准;默认是当前目录。
检查通过只说明能互操作,不是安全性证明。Guidedog 仍会验证每次运行响应,安装的插件在独立进程中执行。崩溃、越界或进程停滞会转为诊断,不能发布不完整的输出。兼容旧版发布器已不再是发布要求;跨进程检查验证互操作性,直接链接的原生回调仍属于受信任代码。
通用检查不会调用发布器。发布器应通过自己的 Odin 测试和明确配置的演练来验证。修改解析器、节点模型或构建器本身需要单独设计;模块化库和源码仍可用于应用集成或 fork。