ネイティブプラグインを書く¶
プラグインは 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
サーバーが表示した URL を開くと、本文に「Hello Orbit.」、ページに Orbit のバッジが出ます。CSS は _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 へ戻り、defer による後始末を実行します。組み込みホストでは、ディスクリプターを 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() を返します。Unload は一部だけ読み込まれたセッションにも対応してください。
ロード時は 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 push を一度行います。状態確認と復旧が結果を確定します。ソースや 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 を使います。インストールで追加する独自ディレクティブ、ロール、ビルダーはこのフック API に含まれません。
10. 登録前にプラグインを検査する¶
guidedog plugin check PATH --project=DIR --config=FILE は登録情報を変えずにビルドプラグインを検査します。登録時も同じ検査を行います。新規ロードを二回行い、ソースと HTML の結果の再現性、生成アセット、後始末を調べます。--timeout=SECONDS は要求ごとに既定で 60 秒です。必要なら実際の設定を渡してください。設定の相対パスは --project が基準で、既定は現在のディレクトリです。
検証成功は相互運用の記録で、安全性の証明ではありません。ホストは実行時の応答も検証し、インストールしたプラグインを別プロセスで動かします。クラッシュ、境界違反、停止は診断となり、不完全な世代を公開しません。旧版公開プラグインとの互換性は要件ではありません。直接リンクするコールバックは引き続き信頼するコードです。
汎用検査はパブリッシャーを呼びません。パブリッシャーは専用の Odin テストと、明示的に設定したドライランで検証します。パーサー、ノードモデル、ビルダー自体の変更には別の設計が必要です。モジュール化されたライブラリーとソースは、アプリケーションや fork でも利用できます。