diff --git a/claude-notes/plans/2026-10-27-lua-api-q1-parity-gh-939-942.md b/claude-notes/plans/2026-10-27-lua-api-q1-parity-gh-939-942.md new file mode 100644 index 0000000000..0bd535197b --- /dev/null +++ b/claude-notes/plans/2026-10-27-lua-api-q1-parity-gh-939-942.md @@ -0,0 +1,417 @@ +--- +title: 'Lua API: Quarto 1 parity gaps from the Connect docs port (GH #939–#942)' +date: 2026-10-27 +description: 'Add quarto.project, quarto.doc.input_file/output_file, a comparable quarto.version (pandoc.types.Version), make QUARTO_PROFILE visible to os.getenv, and turn os.exit into a document-level failure.' +--- + +Epic strand: **bd-pqj37chw**. Children, one per +GitHub issue: + +| GH | strand | what | +|---|---|---| +| [#939](https://github.com/quarto-dev/q2/issues/939) | bd-ip1lrgra (pre-existing, re-scoped) | `quarto.project` table; `QUARTO_PROFILE` via `os.getenv` | +| [#940](https://github.com/quarto-dev/q2/issues/940) | bd-diu7rtes | `quarto.doc.input_file` / `quarto.doc.output_file` | +| [#941](https://github.com/quarto-dev/q2/issues/941) | bd-9u10sb4b | `os.exit` fails the document, not the process | +| [#942](https://github.com/quarto-dev/q2/issues/942) | bd-5qepzwst (pre-existing, re-scoped) | `quarto.version` from the real version, as a `pandoc.types.Version` | + +All four were reported by atheriel while porting the Posit Connect docs +from Quarto 1.9.32 to q2 0.36.0, and all four are things a Quarto 1 Lua +filter does on its first few lines. They share one plan because #939 and +#940 need the same new plumbing (per-document host context into the Lua +environment), #942 is the natural first step (smallest, independent), and +#941 is small and touches the same file. One integration branch, four +sub-task branches, one PR at the end (agreed 2026-10-27: it all ships in +the next release anyway). + +## Reproduction (2026-10-27, `main` at 3f7d4b0e8, q2 0.36.0, macOS) + +All four reproduce exactly as the issues describe. Repro projects are in +the session scratchpad (`r939`, `r940`, `r941`, `r942`); the fixtures +below are the same files and will become the tests. + +- **#939** `q2 render --profile drafts` → `quarto.project: nil`, + `os.getenv("QUARTO_PROFILE")` → `nil`; `QUARTO_PROFILE=drafts q2 render` + → `drafts`. `quarto` keys: `_diagnostics, attribution, base64, + component, config, doc, error, include, json, lmd, log, markdown, + metadata, paths, utils, version, warn`. +- **#940** `quarto.doc.input_file`, `quarto.doc.output_file`, `PANDOC_STATE` + all `nil`. +- **#941** `os.exit(1)` in the `Pandoc` handler for page A: process exits 1 + after printing `filter running on B`, `filter running on A`, `fatal: + validation failed on A`; `_site/` is empty; no summary; the Q-2-12 + parse error in `c.qmd` is never reported. +- **#942** `quarto.version` is a plain table `{0,1,0}`; `>= "1.4"` fails + with `attempt to compare string with table`; `pandoc.types` is `nil`. + `PANDOC_VERSION` has the same problem (plain table `{3,0,0}`), and q2's + own vendored `resources/pandoc-filters/filters/layout/table.lua:155` + does `PANDOC_VERSION < pandoc.types.Version("2.11.3.2")`. + +A side observation: with a filter listed in `_quarto.yml` as `probe.lua`, +`sub/page.qmd` fails with *Failed to read filter `.../sub/probe.lua`*. That +is sibling issue #945 (filter path resolution), not in this plan, but it +means the `offset` tests below must reference the filter as +`/abs/path` or run from a flat project until #945 lands. + +## Where things live today + +- The Lua environment for filters is assembled in one place, + `create_filter_environment_with` (`crates/pampa/src/lua/filter.rs`), + from `(runtime, target_format, script_path, attribution, &LuaOptions)`. + Native uses `Lua::new()` (full stdlib, so `os.exit` is libc `exit`); + WASM uses a restricted stdlib plus synthetic `os`/`io`/`dofile` + (`os_wasm.rs`, `io_wasm.rs`). The shortcode environment + (`LuaShortcodeEngine::new_with`, `shortcode.rs`) builds the same + namespaces from the same `LuaOptions`. +- `LuaOptions` (`crates/pampa/src/lua_options.rs`) is the host → pampa + options bag: `dialects`, `module_roots`, `typst`. quarto-core builds it + in `crate::lmd::lua_options(&project, runtime)` from three call sites: + `UserFiltersStage` (`stage/stages/user_filters.rs:239`), + `ShortcodeResolveTransform` (`transforms/shortcode_resolve.rs:1231`), + and `lmd_execute.rs:752`. The first two have the document in hand + (`ctx.document: DocumentInfo` with `input` absolute, `ctx.output_path()`; + `RenderContext.document` for shortcodes). +- `quarto.version` is set by `register_quarto_version` + (`quarto_api.rs:220`) to the literal `{0,1,0}`. pampa is version `0.0.0`, + but it depends on `quarto-util` (workspace version, 0.36.0), whose + `quarto_util::cli_version()` is already the one source of truth for the + version string, including the nightly `QUARTO_VERSION_OVERRIDE` + (bd-p4ljdp2e). `PANDOC_VERSION`/`PANDOC_API_VERSION` are plain tables + set in `create_filter_environment_with`. +- `quarto.doc` is `register_quarto_doc` (`quarto_doc.rs:187`); it has no + path fields. +- Active profiles: `ctx.project.config.active_config_profiles: + Vec`; `quarto_profile_env_value(&active) -> Option` + is the comma-joined value already handed to the `env` shortcode and to + subprocess spawns (the documented "one deliberate exception" to + real-environment-wins). Profiles resolve for single-file renders too + (`project/mod.rs:2172`). +- Quarto 1 reference: `external-sources/quarto-cli/src/resources/pandoc/datadir/init.lua` + lines 595–715 (`projectDirectory`, `inputFile`, `outputFile`, + `version`), 985–994 (the `quarto.doc.{input,output}_file` and + `quarto.project` table). `project-offset` comes from + `projectOffset()` in `src/project/project-shared.ts:131`: + `relative(dirname(input), projectDir) || "."`, forward slashes. +- Pre-existing strands: bd-ip1lrgra already asks for `quarto.project` + (notes that Q1's type stub says `profiles`, plural, but the runtime + field is `profile`, singular — implement the singular); bd-5qepzwst + already asks for a real `quarto.version`. + +## Design + +### Shared plumbing: a per-document host context in `LuaOptions` + +Add one struct to `pampa::lua_options`, filled by the host, read by the +registrars: + +```rust +/// What the host knows about the document and project a Lua script runs +/// for. Everything Quarto 1 surfaced through `quarto.project` and +/// `quarto.doc.{input,output}_file`. All optional: pampa's own tests and +/// the conformance suite run without a host. +#[derive(Clone, Debug, Default)] +pub struct HostContext { + /// Absolute path of the input being rendered → `quarto.doc.input_file`. + pub input_file: Option, + /// Absolute path of the output → `quarto.doc.output_file`. + pub output_file: Option, + /// `None` for single-file renders (Q1: `quarto.project.directory` is nil + /// outside a project). + pub project: Option, + /// Active profile names → `quarto.project.profile` (a `pandoc.List`). + pub profiles: Vec, + /// The environment `os.getenv` answers from: a snapshot the host took + /// on its own thread before any script ran (real environment, then + /// file-defined `_environment` values for keys the real one lacks, + /// then `QUARTO_PROFILE` forced to the active list). `None` means + /// "no host": `os.getenv` falls through to the stdlib on native and + /// to `runtime.env_get` on WASM, which is today's behavior. + pub env: Option>>, +} + +#[derive(Clone, Debug)] +pub struct HostProject { + pub directory: PathBuf, // absolute + pub output_directory: PathBuf, // absolute (== directory when no output-dir) + pub offset: String, // "." or "../.." — forward slashes +} +``` + +`LuaOptions` gains `pub host: HostContext`. quarto-core's +`lmd::lua_options(project, runtime)` keeps its signature for the +`lmd_execute` caller and gains a sibling +`lua_options_for_document(project, runtime, document: &DocumentInfo, +output: PathBuf)` used by `UserFiltersStage` and +`ShortcodeResolveTransform`. `offset` is computed once there with +`pathdiff::diff_paths(&project.dir, input.parent())` → +`quarto_util::to_forward_slashes`, `"."` when empty — exactly Q1's +`projectOffset`. `output_file` is `ctx.output_path()` (project renders set +`DocumentInfo.output` in `pass2_renderer`, so this is the final path). + +Why `LuaOptions` and not new parameters: `create_filter_environment_with` +and `LuaShortcodeEngine::new_with` already take `&LuaOptions`, every +caller already builds one, and the conformance suite calls the production +constructor directly, so the fields are visible there with no synthetic +registration. Hub-client (WASM) gets the same behavior for free through +`UserFiltersStage`. + +### #939 — `quarto.project` and `QUARTO_PROFILE` + +New `register_quarto_project(lua, &host)` in `quarto_api.rs`, called from +both environments after `register_quarto_api`: + +```lua +quarto.project = { + directory = | nil, + offset = "." | "../.." | nil, + output_directory = | nil, + profile = pandoc.List{ "drafts", ... }, -- always a List, possibly empty +} +``` + +`os.getenv`: install a Rust replacement on the stdlib `os` table (native) +and on the synthetic one (WASM, `os_wasm.rs`), from one shared helper. +When the host supplied `env`, the function is a pure `HashMap` lookup +and never touches libc. The snapshot is built by the host, in +`StageContext::new` right after `load_project_environment` (the one +place that already has the real environment, the file layers, and the +active profiles together), and stored on `StageContext` as +`env_snapshot: Arc>` so cloning it into each +`LuaOptions` is free: + +1. start from the real environment (`std::env::vars_os()`, non-UTF-8 + entries dropped; on WASM `runtime.env_get` has nothing, so this layer + is empty); +2. add each file-defined `_environment` pair whose key the real + environment lacks — the same filter `env_for_subprocess` applies, so + the "real environment wins" rule of `project/environment.rs` holds; +3. set `QUARTO_PROFILE` to `quarto_profile_env_value(&active)` when the + active list is non-empty — the documented deliberate exception where + quarto's own variable beats the inherited one, matching Q1, which + wrote the active list back into the environment. + +Two reasons for a snapshot rather than a lookup at call time. First, +filters run under `tokio::task::block_in_place` on a worker thread, and +the stdlib `os.getenv` is libc `getenv`, which races with any `setenv` +elsewhere in the process (glibc documents this as undefined behavior, +and Rust's `std::env` lock does not cover C code). q2 never mutates its +environment in production, but engines spawn children and link +third-party code, so reading on the orchestrator thread before the +pipeline fans out is the defensive choice (Carlos, 2026-10-27). Second, +every filter and shortcode in a render then sees one consistent +environment. Layer 2 is a small step past the issue: Quarto 1 loaded +`_environment` into the Deno process environment, so pandoc's Lua saw +those variables too; without it a ported filter that reads a file-defined +variable would silently get nil. (Agreed 2026-10-27.) + +The `env` shortcode handler (`EnvShortcodeHandler`) performs the same +three-layer merge at lookup time; switching it to the snapshot is a +one-line follow-up, not part of this plan. + +### #940 — `quarto.doc.input_file` / `quarto.doc.output_file` + +`register_quarto_doc(lua)` gains the `&HostContext` and sets two plain +string fields (absolute paths, as in Q1). Also set them on the shortcode +environment's `quarto.doc` — Q1 shortcode handlers see them, and the +Connect filter's "skip some pages by path" logic is the kind of thing that +moves into a shortcode. + +Also in scope (agreed 2026-10-27): a minimal `PANDOC_STATE` global in +both environments, built from the same `HostContext`: + +```lua +PANDOC_STATE = { + input_files = pandoc.List{ }, -- empty List without a host + output_file = | nil, +} +``` + +Pandoc's `output_file` is the writer's output *name* as given on the +command line; Q1 joined it with the output directory anyway +(`init.lua:669`), so the absolute path is what every Q1 filter ended up +with. The other pandoc fields (`resource_path`, `source_url`, +`user_data_dir`, `request_headers`, `verbosity`, `log`, `trace`) stay nil; +a filter that needs one gets a clear "attempt to index a nil value" at +its own line rather than a plausible-looking wrong default. Not a +registry divergence (`divergences.md`): it is a gap, not a decision +against. + +Optional, cheap once the plumbing exists: `quarto.doc.project_output_file()` +(Q1 `init.lua:1090`, the project-relative output path). Include only if a +Connect filter turns out to use it. + +### #941 — `os.exit` fails the document + +Replace `os.exit` on both `os` tables (shared helper next to the `getenv` +one) with a Rust function that raises `mlua::Error::external(LuaExit { +code })`. Code mapping follows Lua: no arg or `true` → 0, `false` → 1, +number → that number. The second `close` argument is ignored. + +In `apply_lua_filter_with`, when the script load or a handler returns an +error whose chain contains `LuaExit`, map it to a new +`LuaFilterError::Exit { code, filter: PathBuf }` whose `Display` is +`Lua filter called os.exit(); the document was not rendered`. +Everything downstream already does the right thing: `UserFiltersStage` +turns it into a stage error, the orchestrator records "while rendering +``", moves on to the next document, prints the summary, and exits +non-zero because a document failed. The exit code the filter asked for is +reported in the message, not propagated as the process exit status (q2 +has its own contract there, and a render with one failed page is already +non-zero). + +Decisions worth stating explicitly: + +- `os.exit(0)` also fails the document. In Quarto 1 it made pandoc exit + without writing output, which Quarto 1 then reported as a failure, so + this is parity, not a tightening. +- `pcall(os.exit, 1)` will catch the error instead of exiting. Acceptable; + nobody does this on purpose. +- The shortcode environment gets the same override; an `os.exit` there + becomes whatever a thrown error already becomes for a shortcode (an + error diagnostic on the shortcode). +- q2's `error()` is **not** changed to Q1's log-only behavior; the issue + confirms `error()` already behaves well. + +Rule compliance: the WASM `os` table gains `exit` too, so +`crates/pampa/tests/wasm_lua.rs` gets a case (per `.claude/rules/wasm.md`, +`os_wasm.rs` is on the must-update list). + +### #942 — `quarto.version` as a `pandoc.types.Version` + +New `crates/pampa/src/lua/version.rs`: `LuaVersion(Vec)` userdata +with + +- `pandoc.types.Version(spec)` constructor accepting a string (`"1.4"`, + `"0.36.0"`), a number, a sequence table, or another Version; +- `__eq`, `__lt`, `__le` as `add_meta_function` taking `(Value, Value)` + so either operand may be the Version (Lua calls `__le("1.4", v)` for + `v >= "1.4"`; `add_meta_method` would only see the Version-first + case). Comparison is lexicographic on components, shorter prefix is + less (`1.4 < 1.4.1`), matching pandoc; +- `__tostring` → `"0.36.0"`; `__index` for integer keys (components) and + the method `must_be_at_least(other[, msg])`; `__len`. With `__index` + and `__len` present, Lua 5.4's `table.concat` accepts the userdata + (`checktab` with `TAB_R|TAB_L`), so `table.concat(quarto.version, ".")` + keeps working — this is exactly why it works on Q1's pandoc Version. + Pin it with a test; +- `pandoc.utils.type(v)` → `"Version"` (add to `userdata_type_name` in + `utils.rs`). + +Then: + +- `register_quarto_version` builds `quarto.version` from the leading + dotted-numeric prefix of `quarto_util::cli_version()` (Q1's + `leadingDottedNumber`: `"0.37.0-nightly.20261027"` → `0.37.0`; + never falls back to a plain string). +- `PANDOC_VERSION` and `PANDOC_API_VERSION` in + `create_filter_environment_with` (and the shortcode env, if set there) + become Version objects with the same components as today. +- `pandoc.types` becomes a real table (registered from `constructors.rs` + or `types.rs`), holding `Version` and `Version`-related helpers only. + +Check `crates/pampa/tests/lua-conformance/xfail.txt` and +`differential/xfail.txt` for Version/`PANDOC_VERSION` cases: any that +start passing must be removed from the xfail lists (the ratchet reports +them otherwise). + +## Work items + +Order: 942 → plumbing+939 → 940 → 941. Each is a `switch-task` sub-task +branch off one integration branch (`feature/lua-api-q1-parity`). + +- [x] **bd-5qepzwst (#942)** `version.rs`, `pandoc.types.Version`, + `quarto.version`, `PANDOC_VERSION`/`PANDOC_API_VERSION`, `utils.type`, + xfail cleanup. Unit tests in `version.rs`; a `filter.rs` test running + the issue's probe script. +- [x] **bd-ip1lrgra (#939)** `HostContext`/`HostProject` in `LuaOptions`; + `lua_options_for_document` in quarto-core; `register_quarto_project`; + `env_snapshot` on `StageContext`; `os.getenv` override (native + + WASM). Tests: pampa unit tests for the table shape with and without a + project, and for `os.getenv` against a supplied snapshot (hit, miss, + no-snapshot fallthrough); a quarto-core test of the snapshot's three + layers (real wins over file, file fills a gap, `--profile` beats an + inherited `QUARTO_PROFILE`) built without touching the real + environment — inject the real layer the way `merge_env_layers` + already does; a quarto-core integration test + (two-page website, `index.qmd` + `sub/page.qmd`, probe filter writes + `directory`/`offset`/`output_directory`/`profile` and + `os.getenv("QUARTO_PROFILE")` into the document, rendered with + `--profile drafts`) asserting `offset == "."` and `".."` and the + profile list; a single-file render asserting the three nils. Offset + assertions compare forward-slash strings; directory assertions build + expected paths with `Path::join`. +- [x] **bd-diu7rtes (#940)** `quarto.doc.input_file`/`output_file` and the + minimal `PANDOC_STATE` (`input_files`, `output_file`) in filter and + shortcode environments. Tests ride on the #939 fixture (assert both + paths and `PANDOC_STATE.input_files[1] == quarto.doc.input_file`; + output under `_site/sub/page.html` built with `Path::join`). +- [x] **bd-9u10sb4b (#941)** `os.exit` override (native + WASM), + `LuaFilterError::Exit`, `wasm_lua.rs` case. CLI e2e test + `crates/quarto/tests/integration/lua_os_exit_cli.rs` (register in + `main.rs`): the issue's a/b/c project; assert exit status non-zero, + `_site/b.html` exists, `_site/a.html` does not, stderr contains the + `os.exit(1)` message naming `die.lua`, the Q-2-12 diagnostic for + `c.qmd`, and a `Rendered 1 of 3 files` summary. +- [x] **Docs** `docs/guides/authoring/lua-filters.qmd`: a section "Where + the filter is running" (`quarto.project`, `quarto.doc.input_file`, + `quarto.doc.output_file`, `QUARTO_PROFILE`), a paragraph under the + existing version material on `quarto.version` comparisons, and a + short "Failing a render" note (`error`, `quarto.error`, `os.exit`). +- [ ] **Verification** `cargo xtask verify --skip-hub-build`; Windows + cross-check for pampa, quarto-core, quarto + (`cargo clippy -p --all-targets --target x86_64-pc-windows-msvc -- -D warnings`); + WASM Lua tests per `dev-docs/wasm.md`; re-run the four scratchpad + repros by hand and paste the output into the PR. +- [ ] Close the four GitHub issues from the PR; cc atheriel. + +## Out of scope / follow-ups (not filed; say the word) + +- **The rest of `PANDOC_STATE`** (`resource_path`, `verbosity`, `log`, + `trace`, `user_data_dir`, `request_headers`, `source_url`). The minimal + two-field version is in #940; the rest has no q2 equivalent to report. +- **`EnvShortcodeHandler` on the environment snapshot** instead of its + own lookup-time merge (one consistent environment for shortcodes and + filters alike). +- **Exposing the full version string** (nightlies lose + `-nightly.YYYYMMDD` in the numeric Version). Q1 does not expose it + either. +- **Siblings #943–#945** (possessive apostrophes, case-only aliases, + filter path resolution) are separate issues with separate causes. + +## Implementation notes (2026-10-27) + +- Plumbing landed as planned, with one deviation: the environment snapshot + reaches the shortcode transform through a new `RenderContext.env_snapshot` + field (bridged from `StageContext` by `AstTransformsStage` like the other + per-document fields) rather than through the `build_transform_pipeline` + signature, which has some thirty test callers. +- The snapshot's real-environment layer comes from + `SystemRuntime::env_all()`, not `std::env` directly, so the preview + server's `--profile` runtime override is included. `NativeRuntime::env_all` + switched to `vars_os` because `vars()` panics on a non-UTF-8 entry and it + now runs per document. +- `quarto.doc.input_file` / `output_file` and `PANDOC_STATE` are registered + by `host_context.rs` after `register_quarto_doc`, so `quarto_doc.rs` did + not change. +- Windows cross-check (`cargo clippy --target x86_64-pc-windows-msvc`) + cannot run from macOS for pampa, quarto-core or quarto: `aws-lc-sys`, + `wasmtime` and `tree-sitter` build C for the target. The new code uses + no platform APIs; path assertions in the e2e tests use `Path::join`. + Flag for a Windows run in the PR. +- Five quarto-core unit tests fail under plain `cargo test` but pass under + nextest (process isolation); unrelated to this change. + +## Risks + +- `table.concat` on a userdata relies on Lua 5.4 `checktab` metamethod + acceptance; pampa is on `lua54` (vendored). Pinned by test; if it fails, + fall back to a table with a metatable (`__name = "Version"`) instead of + a userdata — `pandoc.utils.type` already reads `__name` from table + metatables. +- `os.getenv` shadowing changes what every filter sees for one variable. + The override only fires when profiles are active, so a render without + `--profile`/`QUARTO_PROFILE` is byte-for-byte unchanged. +- Two more `LuaOptions` fields touch three quarto-core call sites and a + handful of tests that build `LuaOptions {..}` literally + (`placeholder_shortcode.rs:39`); `Default` on `HostContext` keeps the + `with_dialects` constructor and the struct-literal sites compiling with + one added line each. diff --git a/crates/pampa/src/lua/constructors.rs b/crates/pampa/src/lua/constructors.rs index 3d2d1bb343..da8e3bb3cc 100644 --- a/crates/pampa/src/lua/constructors.rs +++ b/crates/pampa/src/lua/constructors.rs @@ -1006,6 +1006,9 @@ pub fn register_pandoc_namespace( // Document + meta constructors (pandoc.Pandoc, pandoc.Meta, pandoc.Meta*) super::pandoc_doc::register_doc_constructors(lua, &pandoc)?; + // pandoc.types.Version (GH #942) + super::version::register_pandoc_types(lua, &pandoc)?; + // Set as global lua.globals().set("pandoc", pandoc)?; diff --git a/crates/pampa/src/lua/filter.rs b/crates/pampa/src/lua/filter.rs index 97fa0e5113..676610ec2e 100644 --- a/crates/pampa/src/lua/filter.rs +++ b/crates/pampa/src/lua/filter.rs @@ -55,6 +55,14 @@ pub enum LuaFilterError { /// /// [`InvalidReturn`]: LuaFilterError::InvalidReturn InvalidScriptReturn(String), + /// The filter called `os.exit(code)` (GH #941). Quarto 1 filters do + /// this to fail a render; here it fails this document only, like + /// `error()`, and the render goes on to the next one. The code is + /// reported, not propagated as the process status. + Exit { + filter: std::path::PathBuf, + code: i64, + }, } impl std::fmt::Display for LuaFilterError { @@ -66,6 +74,12 @@ impl std::fmt::Display for LuaFilterError { LuaFilterError::LuaError(err) => write!(f, "Lua filter error: {}", err), LuaFilterError::InvalidReturn(msg) => write!(f, "Invalid filter return: {}", msg), LuaFilterError::InvalidScriptReturn(msg) => write!(f, "{}", msg), + LuaFilterError::Exit { filter, code } => write!( + f, + "Lua filter {} called os.exit({}); the document was not rendered", + filter.display(), + code + ), } } } @@ -177,6 +191,10 @@ pub fn create_filter_environment_with( #[cfg(not(target_arch = "wasm32"))] let lua = Lua::new(); + // os.exit fails the document, not the process (GH #941). On native this + // replaces the stdlib's libc exit; on WASM it extends the synthetic os. + super::os_exit::install_os_exit(&lua)?; + // Create mediabag for storing media items // In the future, this could be pre-populated from the document or passed in let mediabag = create_shared_mediabag(); @@ -208,6 +226,9 @@ pub fn create_filter_environment_with( // Register quarto.doc namespace (is_format, add_html_dependency, etc.) super::quarto_doc::register_quarto_doc(&lua)?; + // quarto.project and the host's environment for os.getenv (GH #939). + super::host_context::register_host_context(&lua, &options.host)?; + // Push script dir for quarto.utils.resolve_path let script_dir = script_path .parent() @@ -220,20 +241,19 @@ pub fn create_filter_environment_with( // FORMAT - the target output format (html, latex, etc.) lua.globals().set("FORMAT", target_format)?; - // PANDOC_VERSION - version of Pandoc (we emulate 3.x behavior) - // Set as a table with numeric indices for version components - let version_table = lua.create_table()?; - version_table.set(1, 3)?; - version_table.set(2, 0)?; - version_table.set(3, 0)?; - lua.globals().set("PANDOC_VERSION", version_table)?; + // PANDOC_VERSION - version of Pandoc (we emulate 3.x behavior), as a + // pandoc.types.Version so `PANDOC_VERSION < pandoc.types.Version(...)` + // and `PANDOC_VERSION:must_be_at_least(...)` work (GH #942). + lua.globals().set( + "PANDOC_VERSION", + super::version::create_version(&lua, &[3, 0, 0])?, + )?; // PANDOC_API_VERSION - version of the pandoc-types API - let api_version_table = lua.create_table()?; - api_version_table.set(1, 1)?; - api_version_table.set(2, 23)?; - api_version_table.set(3, 1)?; - lua.globals().set("PANDOC_API_VERSION", api_version_table)?; + lua.globals().set( + "PANDOC_API_VERSION", + super::version::create_version(&lua, &[1, 23, 1])?, + )?; // PANDOC_SCRIPT_FILE - path to the current filter script lua.globals().set( @@ -294,6 +314,40 @@ pub async fn apply_lua_filter_with( runtime: Arc, attribution: Option>, options: &crate::lua_options::LuaOptions, +) -> FilterResult { + let result = apply_lua_filter_inner( + pandoc, + context, + filter_path, + target_format, + runtime, + attribution, + options, + ) + .await; + // `os.exit` surfaces as a Lua error wrapping `LuaExit`, whether it was + // raised while the script loaded or inside a handler (GH #941). Name + // it as what it is rather than printing the wrapped error chain. + match result { + Err(LuaFilterError::LuaError(err)) => match super::os_exit::requested_exit(&err) { + Some(code) => Err(LuaFilterError::Exit { + filter: filter_path.to_path_buf(), + code, + }), + None => Err(LuaFilterError::LuaError(err)), + }, + other => other, + } +} + +async fn apply_lua_filter_inner( + pandoc: &Pandoc, + context: &ASTContext, + filter_path: &Path, + target_format: &str, + runtime: Arc, + attribution: Option>, + options: &crate::lua_options::LuaOptions, ) -> FilterResult { // Read filter file via runtime (supports VFS on WASM) let filter_bytes = runtime.file_read(filter_path).map_err(|e| { diff --git a/crates/pampa/src/lua/host_context.rs b/crates/pampa/src/lua/host_context.rs new file mode 100644 index 0000000000..6133149dd6 --- /dev/null +++ b/crates/pampa/src/lua/host_context.rs @@ -0,0 +1,266 @@ +/* + * lua/host_context.rs + * Copyright (c) 2026 Posit, PBC + * + * What a Lua script learns about where it is running, from the host's + * `HostContext` (GH #939, #940): + * + * - `quarto.project` — `directory`, `offset`, `output_directory`, + * `profile`, with Quarto 1's shape (nil paths outside a project, the + * profile list always present); + * - `os.getenv` — answered from the host's environment snapshot when it + * supplied one, so the stdlib's libc `getenv` never runs on a filter + * worker thread and `--profile` is visible as `QUARTO_PROFILE`; + * - `quarto.doc.input_file` / `quarto.doc.output_file` — the absolute + * paths Quarto 1 gave, and the minimal `PANDOC_STATE` (`input_files`, + * `output_file`) built from the same two values. + * + * Registered after `quarto` and `os` exist, in both the filter and the + * shortcode environments. + */ + +use mlua::{Lua, Result, Table, Value}; + +use crate::lua_options::HostContext; + +/// Register everything the host context contributes to the environment. +pub fn register_host_context(lua: &Lua, host: &HostContext) -> Result<()> { + register_quarto_project(lua, host)?; + register_quarto_doc_paths(lua, host)?; + register_pandoc_state(lua, host)?; + install_os_getenv(lua, host)?; + Ok(()) +} + +/// `quarto.doc.input_file` / `quarto.doc.output_file`: absolute paths, as +/// in Quarto 1 (`init.lua`'s `inputFile()` / `outputFile()`). Absent (nil) +/// without a host, never a relative or placeholder path. +fn register_quarto_doc_paths(lua: &Lua, host: &HostContext) -> Result<()> { + let quarto: Table = lua.globals().get("quarto")?; + let doc: Table = quarto.get("doc")?; + if let Some(input) = &host.input_file { + doc.set("input_file", input.to_string_lossy().to_string())?; + } + if let Some(output) = &host.output_file { + doc.set("output_file", output.to_string_lossy().to_string())?; + } + Ok(()) +} + +/// The minimal `PANDOC_STATE`: `input_files` (a `pandoc.List` of the one +/// input, empty without a host) and `output_file`. Pandoc's `output_file` +/// is the writer's output *name* as given on its command line; Quarto 1 +/// joined it with the output directory before any filter saw it +/// (`init.lua`'s `outputFile()`), so the absolute path is what Q1 filters +/// ended up with. The other pandoc fields (`resource_path`, `source_url`, +/// `user_data_dir`, `request_headers`, `verbosity`, `log`, `trace`) have +/// no q2 equivalent and stay nil, so a filter that needs one fails at its +/// own line rather than reading a plausible wrong default. +fn register_pandoc_state(lua: &Lua, host: &HostContext) -> Result<()> { + let state = lua.create_table()?; + let inputs: Vec = host + .input_file + .iter() + .map(|p| p.to_string_lossy().to_string()) + .collect(); + state.set( + "input_files", + super::list::create_string_list_table(lua, &inputs)?, + )?; + if let Some(output) = &host.output_file { + state.set("output_file", output.to_string_lossy().to_string())?; + } + lua.globals().set("PANDOC_STATE", state)?; + Ok(()) +} + +/// `quarto.project`: Quarto 1's table, with nils where Q1 had them. +/// +/// `profile` is a `pandoc.List` so Q1 code can call `:includes("drafts")` +/// on it; it is present (possibly empty) even outside a project, as in Q1 +/// where it came from a filter param rather than the project. +fn register_quarto_project(lua: &Lua, host: &HostContext) -> Result<()> { + let quarto: Table = lua.globals().get("quarto")?; + let project = lua.create_table()?; + if let Some(p) = &host.project { + project.set("directory", p.directory.to_string_lossy().to_string())?; + project.set("offset", p.offset.as_str())?; + project.set( + "output_directory", + p.output_directory.to_string_lossy().to_string(), + )?; + } + project.set( + "profile", + super::list::create_string_list_table(lua, &host.profiles)?, + )?; + quarto.set("project", project)?; + Ok(()) +} + +/// Replace `os.getenv` with a lookup in the host's snapshot. Without a +/// snapshot the table is left alone: the stdlib function on native, the +/// runtime-backed one `os_wasm` installs on WASM. +fn install_os_getenv(lua: &Lua, host: &HostContext) -> Result<()> { + let Some(env) = host.env.clone() else { + return Ok(()); + }; + let os: Table = match lua.globals().get::("os")? { + Value::Table(t) => t, + _ => return Ok(()), + }; + os.set( + "getenv", + lua.create_function(move |_, name: String| Ok(env.get(&name).cloned()))?, + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::lua_options::HostProject; + use std::collections::HashMap; + use std::path::PathBuf; + use std::sync::Arc; + + fn lua_with(host: &HostContext) -> Lua { + let lua = Lua::new(); + let runtime: Arc = + Arc::new(crate::lua::runtime::NativeRuntime::new()); + super::super::constructors::register_pandoc_namespace( + &lua, + runtime, + super::super::mediabag::create_shared_mediabag(), + ) + .unwrap(); + super::super::quarto_api::register_quarto_api(&lua).unwrap(); + // Production order: quarto.doc exists before the host context + // adds its path fields to it. + super::super::quarto_doc::register_quarto_doc(&lua).unwrap(); + register_host_context(&lua, host).unwrap(); + lua + } + + fn eval(lua: &Lua, src: &str) -> T { + lua.load(src).eval().unwrap() + } + + #[test] + fn quarto_project_outside_a_project_has_q1_nils_and_an_empty_profile_list() { + let lua = lua_with(&HostContext::default()); + assert!(eval::(&lua, "return quarto.project.directory == nil")); + assert!(eval::(&lua, "return quarto.project.offset == nil")); + assert!(eval::( + &lua, + "return quarto.project.output_directory == nil" + )); + assert_eq!(eval::(&lua, "return #quarto.project.profile"), 0); + assert_eq!( + eval::(&lua, "return pandoc.utils.type(quarto.project.profile)"), + "List" + ); + } + + #[test] + fn quarto_project_inside_a_project() { + let dir = PathBuf::from("/proj"); + let host = HostContext { + project: Some(HostProject { + directory: dir.clone(), + output_directory: dir.join("_site"), + offset: "..".to_string(), + }), + profiles: vec!["drafts".to_string(), "release".to_string()], + ..Default::default() + }; + let lua = lua_with(&host); + assert_eq!( + eval::(&lua, "return quarto.project.directory"), + dir.to_string_lossy() + ); + assert_eq!(eval::(&lua, "return quarto.project.offset"), ".."); + assert_eq!( + eval::(&lua, "return quarto.project.output_directory"), + dir.join("_site").to_string_lossy() + ); + assert!(eval::( + &lua, + "return quarto.project.profile:includes('drafts') and #quarto.project.profile == 2" + )); + } + + #[test] + fn doc_paths_and_pandoc_state_without_a_host() { + let lua = lua_with(&HostContext::default()); + assert!(eval::(&lua, "return quarto.doc.input_file == nil")); + assert!(eval::(&lua, "return quarto.doc.output_file == nil")); + assert_eq!(eval::(&lua, "return #PANDOC_STATE.input_files"), 0); + assert!(eval::(&lua, "return PANDOC_STATE.output_file == nil")); + } + + #[test] + fn doc_paths_and_pandoc_state_with_a_host() { + let input = PathBuf::from("/proj").join("sub").join("page.qmd"); + let output = PathBuf::from("/proj") + .join("_site") + .join("sub") + .join("page.html"); + let host = HostContext { + input_file: Some(input.clone()), + output_file: Some(output.clone()), + ..Default::default() + }; + let lua = lua_with(&host); + assert_eq!( + eval::(&lua, "return quarto.doc.input_file"), + input.to_string_lossy() + ); + assert_eq!( + eval::(&lua, "return quarto.doc.output_file"), + output.to_string_lossy() + ); + assert!(eval::( + &lua, + "return #PANDOC_STATE.input_files == 1 and PANDOC_STATE.input_files[1] == quarto.doc.input_file" + )); + assert!(eval::( + &lua, + "return PANDOC_STATE.output_file == quarto.doc.output_file" + )); + assert_eq!( + eval::(&lua, "return pandoc.utils.type(PANDOC_STATE.input_files)"), + "List" + ); + } + + #[test] + fn os_getenv_reads_the_snapshot_only() { + let mut env = HashMap::new(); + env.insert("QUARTO_PROFILE".to_string(), "drafts,release".to_string()); + env.insert("FROM_FILE".to_string(), "yes".to_string()); + let host = HostContext { + env: Some(Arc::new(env)), + ..Default::default() + }; + let lua = lua_with(&host); + assert_eq!( + eval::(&lua, "return os.getenv('QUARTO_PROFILE')"), + "drafts,release" + ); + assert_eq!(eval::(&lua, "return os.getenv('FROM_FILE')"), "yes"); + // Not in the snapshot means not visible, even when the real + // process has it: the snapshot is the whole environment. + assert!(eval::(&lua, "return os.getenv('PATH') == nil")); + } + + #[test] + fn os_getenv_without_a_snapshot_is_the_stdlib() { + let lua = lua_with(&HostContext::default()); + // PATH is set in every environment the test suite runs under. + assert!(eval::( + &lua, + "return type(os.getenv('PATH')) == 'string'" + )); + } +} diff --git a/crates/pampa/src/lua/mod.rs b/crates/pampa/src/lua/mod.rs index d5f3235e6e..e519e1ce05 100644 --- a/crates/pampa/src/lua/mod.rs +++ b/crates/pampa/src/lua/mod.rs @@ -14,6 +14,7 @@ mod diagnostics; mod dialect; mod dofile_wasm; mod filter; +mod host_context; mod io_wasm; mod json; mod list; @@ -23,6 +24,7 @@ pub mod mediabag; // quarto.metadata.get and the `meta` proxy (bd-lmd-exploration-jqv2nbl4 spike 6). mod metadata; mod nodes; +mod os_exit; mod os_wasm; mod pandoc_doc; mod path; @@ -36,12 +38,13 @@ mod system; mod text; mod types; mod utils; +mod version; mod walk; #[allow(unused_imports)] pub use crate::dialect::ModuleCompileError; #[allow(unused_imports)] -pub use crate::lua_options::{ExtensionRoot, LuaOptions, ModuleRoots}; +pub use crate::lua_options::{ExtensionRoot, HostContext, HostProject, LuaOptions, ModuleRoots}; #[allow(unused_imports)] pub use dialect::{DialectError, SourceDialect, register_source_dialect}; #[allow(unused_imports)] diff --git a/crates/pampa/src/lua/os_exit.rs b/crates/pampa/src/lua/os_exit.rs new file mode 100644 index 0000000000..e24bc34d2b --- /dev/null +++ b/crates/pampa/src/lua/os_exit.rs @@ -0,0 +1,140 @@ +/* + * lua/os_exit.rs + * Copyright (c) 2026 Posit, PBC + * + * `os.exit` that fails the document instead of the process (GH #941). + * + * Quarto 1 filters call `os.exit(1)` to fail a render: pandoc was a child + * process, so exiting it failed that one document. In q2 the filter runs + * inside the renderer, and the stdlib's `os.exit` is libc `exit`: no page + * is written (not even the ones already rendered), no summary is printed, + * and errors on pages not yet reached are never reported. This module + * replaces `os.exit` on the `os` table — the native stdlib's or the WASM + * synthetic one — with a function that raises a Rust error carrying the + * requested code; `apply_lua_filter` turns it into + * `LuaFilterError::Exit`, which fails the current document the way + * `error()` does. + */ + +use mlua::{Lua, Result, Table, Value}; + +/// The error `os.exit` raises. Carries the status the script asked for; +/// the host reports it in the message rather than exiting with it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LuaExit { + pub code: i64, +} + +impl std::fmt::Display for LuaExit { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "os.exit({})", self.code) + } +} + +impl std::error::Error for LuaExit {} + +/// Lua's own mapping of `os.exit`'s first argument to a status: none or +/// `true` is success (0), `false` is failure (1), a number is itself. +/// Anything else is a Lua type error, as in the stdlib. +fn exit_code(arg: Value) -> Result { + match arg { + Value::Nil => Ok(0), + Value::Boolean(true) => Ok(0), + Value::Boolean(false) => Ok(1), + Value::Integer(n) => Ok(n), + Value::Number(n) if n.fract() == 0.0 => Ok(n as i64), + other => Err(mlua::Error::runtime(format!( + "bad argument #1 to 'exit' (number or boolean expected, got {})", + other.type_name() + ))), + } +} + +/// Replace `os.exit` on the current `os` table. The optional second +/// argument (`close`) is accepted and ignored. A missing `os` table (a +/// restricted state without the synthetic one) is left alone. +pub fn install_os_exit(lua: &Lua) -> Result<()> { + let os: Table = match lua.globals().get::("os")? { + Value::Table(t) => t, + _ => return Ok(()), + }; + os.set( + "exit", + lua.create_function(|_, (code, _close): (Value, Value)| -> Result<()> { + Err(mlua::Error::external(LuaExit { + code: exit_code(code)?, + })) + })?, + )?; + Ok(()) +} + +/// The exit code if `err` is, or wraps, the error `os.exit` raised. mlua +/// nests the external error inside `CallbackError` (one level per Lua → +/// Rust → Lua boundary crossed) and sometimes `WithContext`; walk them. +pub fn requested_exit(err: &mlua::Error) -> Option { + let mut current = err; + loop { + match current { + mlua::Error::ExternalError(e) => { + return e.downcast_ref::().map(|exit| exit.code); + } + mlua::Error::CallbackError { cause, .. } => current = cause, + mlua::Error::WithContext { cause, .. } => current = cause, + _ => return None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lua() -> Lua { + let lua = Lua::new(); + install_os_exit(&lua).unwrap(); + lua + } + + fn code_of(src: &str) -> Option { + let err = lua().load(src).exec().unwrap_err(); + requested_exit(&err) + } + + #[test] + fn exit_raises_with_luas_code_mapping() { + assert_eq!(code_of("os.exit(1)"), Some(1)); + assert_eq!(code_of("os.exit(3, true)"), Some(3)); + assert_eq!(code_of("os.exit()"), Some(0)); + assert_eq!(code_of("os.exit(true)"), Some(0)); + assert_eq!(code_of("os.exit(false)"), Some(1)); + // Raised from inside a Lua function called from Lua: still found. + assert_eq!( + code_of("local function die() os.exit(2) end\nlocal t = { die }\nt[1]()"), + Some(2) + ); + } + + #[test] + fn other_errors_are_not_exits() { + let err = lua().load("error('plain')").exec().unwrap_err(); + assert_eq!(requested_exit(&err), None); + let err = lua().load("os.exit('nope')").exec().unwrap_err(); + assert_eq!(requested_exit(&err), None); + assert!( + err.to_string().contains("bad argument #1 to 'exit'"), + "{err}" + ); + } + + #[test] + fn exit_is_catchable_by_pcall_like_any_error() { + // Documented caveat: pcall(os.exit, 1) catches it. Nobody does this + // on purpose, and it is what a Rust-side error must do. + let caught: bool = lua() + .load("local ok = pcall(os.exit, 1) return ok == false") + .eval() + .unwrap(); + assert!(caught); + } +} diff --git a/crates/pampa/src/lua/os_wasm.rs b/crates/pampa/src/lua/os_wasm.rs index c5d67ae06b..927732295f 100644 --- a/crates/pampa/src/lua/os_wasm.rs +++ b/crates/pampa/src/lua/os_wasm.rs @@ -2,7 +2,8 @@ * os_wasm.rs * * Synthetic `os` table for WASM and test environments. - * Provides os.time(), os.clock(), and os.difftime() backed by SystemRuntime. + * Provides os.time(), os.clock(), os.difftime(), and os.getenv() backed by + * SystemRuntime. */ use std::sync::Arc; @@ -38,6 +39,18 @@ pub fn register_wasm_os(lua: &Lua, runtime: Arc) -> Result<() lua.create_function(|_, (t2, t1): (f64, f64)| Ok(t2 - t1))?, )?; + // os.getenv(name) — the runtime's view of the environment (nothing, on + // wasm32-unknown-unknown). The host's environment snapshot replaces + // this when one is supplied (`host_context::register_host_context`). + let rt = runtime.clone(); + os.set( + "getenv", + lua.create_function(move |_, name: String| { + rt.env_get(&name) + .map_err(|e| mlua::Error::runtime(e.to_string())) + })?, + )?; + lua.globals().set("os", os)?; Ok(()) } diff --git a/crates/pampa/src/lua/quarto_api.rs b/crates/pampa/src/lua/quarto_api.rs index a040371a9b..903cddb8b5 100644 --- a/crates/pampa/src/lua/quarto_api.rs +++ b/crates/pampa/src/lua/quarto_api.rs @@ -215,14 +215,16 @@ fn register_quarto_component(lua: &Lua, quarto: &Table) -> Result<()> { Ok(()) } -/// `quarto.version` — table {0, 1, 0} so extensions can do -/// `table.concat(quarto.version, '.')` to get "0.1.0" +/// `quarto.version` — the version this build reports +/// (`quarto_util::cli_version()`, so a nightly's `QUARTO_VERSION_OVERRIDE` +/// is honored), as a `pandoc.types.Version`: comparable with strings and +/// other Versions (`quarto.version >= "1.4"`), `tostring` gives `"0.36.0"`, +/// and `table.concat(quarto.version, '.')` still works (GH #942). Only the +/// leading dotted-numeric part is carried: `0.37.0-nightly.20261027` is +/// `0.37.0`, as in Quarto 1. fn register_quarto_version(lua: &Lua, quarto: &Table) -> Result<()> { - let version = lua.create_table()?; - version.set(1, 0)?; - version.set(2, 1)?; - version.set(3, 0)?; - quarto.set("version", version)?; + let version = super::version::LuaVersion::leading(quarto_util::cli_version()); + quarto.set("version", super::version::create_version(lua, &version.0)?)?; Ok(()) } @@ -1801,20 +1803,60 @@ mod tests { // ========================================================================= #[test] - fn test_quarto_version_is_table() { + fn test_quarto_version_is_a_pandoc_version() { let lua = create_test_lua(); - let result: String = lua.load(r#"return type(quarto.version)"#).eval().unwrap(); - assert_eq!(result, "table"); + let result: String = lua + .load(r#"return pandoc.utils.type(quarto.version)"#) + .eval() + .unwrap(); + assert_eq!(result, "Version"); } #[test] - fn test_quarto_version_concat() { + fn test_quarto_version_tracks_the_build_version() { let lua = create_test_lua(); - let result: String = lua + let expected = super::super::version::LuaVersion::leading(quarto_util::cli_version()); + let expected = expected + .0 + .iter() + .map(|n| n.to_string()) + .collect::>() + .join("."); + assert_ne!(expected, "0.1.0", "the hard-coded placeholder must be gone"); + let shown: String = lua + .load(r#"return tostring(quarto.version)"#) + .eval() + .unwrap(); + assert_eq!(shown, expected); + // Q1-era extensions build the string this way; it must keep working + // on the userdata (GH #942). + let concat: String = lua .load(r#"return table.concat(quarto.version, '.')"#) .eval() .unwrap(); - assert_eq!(result, "0.1.0"); + assert_eq!(concat, expected); + } + + #[test] + fn test_quarto_version_compares_with_strings() { + let lua = create_test_lua(); + // The probe from GH #942, which used to fail with "attempt to + // compare string with table". + let ok: bool = lua + .load(r#"return (quarto.version >= "1.4") == false and quarto.version >= "0.1""#) + .eval() + .unwrap(); + assert!(ok); + let wrapped: String = lua + .load(r#"return tostring(pandoc.types.Version(quarto.version))"#) + .eval() + .unwrap(); + assert_eq!( + wrapped, + lua.load(r#"return tostring(quarto.version)"#) + .eval::() + .unwrap() + ); } // ========================================================================= diff --git a/crates/pampa/src/lua/shortcode.rs b/crates/pampa/src/lua/shortcode.rs index 7c7a92db97..f1437e4e75 100644 --- a/crates/pampa/src/lua/shortcode.rs +++ b/crates/pampa/src/lua/shortcode.rs @@ -120,6 +120,10 @@ impl LuaShortcodeEngine { #[cfg(not(target_arch = "wasm32"))] let lua = Lua::new(); + // os.exit raises instead of exiting the process (GH #941); a + // handler that calls it fails like one that calls error(). + super::os_exit::install_os_exit(&lua).map_err(LuaShortcodeError::LuaError)?; + let mediabag = create_shared_mediabag(); register_pandoc_namespace(&lua, runtime.clone(), mediabag) .map_err(LuaShortcodeError::LuaError)?; @@ -144,6 +148,10 @@ impl LuaShortcodeEngine { // Register quarto.doc namespace (is_format, add_html_dependency, etc.) super::quarto_doc::register_quarto_doc(&lua).map_err(LuaShortcodeError::LuaError)?; + // quarto.project and the host's environment for os.getenv (GH #939). + super::host_context::register_host_context(&lua, &options.host) + .map_err(LuaShortcodeError::LuaError)?; + lua.globals() .set("FORMAT", target_format) .map_err(LuaShortcodeError::LuaError)?; diff --git a/crates/pampa/src/lua/utils.rs b/crates/pampa/src/lua/utils.rs index e9437ad47a..9f3212ed4d 100644 --- a/crates/pampa/src/lua/utils.rs +++ b/crates/pampa/src/lua/utils.rs @@ -348,6 +348,9 @@ fn userdata_type_name(ud: &AnyUserData) -> Option { if ud.is::() { return Some("Null".to_string()); } + if ud.is::() { + return Some("Version".to_string()); + } ud.metatable() .ok() .and_then(|mt| mt.get::("__name").ok()) diff --git a/crates/pampa/src/lua/version.rs b/crates/pampa/src/lua/version.rs new file mode 100644 index 0000000000..7e2c6b5e11 --- /dev/null +++ b/crates/pampa/src/lua/version.rs @@ -0,0 +1,341 @@ +/* + * lua/version.rs + * Copyright (c) 2026 Posit, PBC + * + * `pandoc.types.Version`: pandoc's comparable version object, and the + * values built from it — `quarto.version`, `PANDOC_VERSION`, + * `PANDOC_API_VERSION`. + * + * Quarto 1 filters do `quarto.version >= "1.4"`, + * `PANDOC_VERSION < pandoc.types.Version("2.11.3.2")`, and + * `PANDOC_VERSION:must_be_at_least("2.1")`; they also do + * `table.concat(quarto.version, ".")`, which works on pandoc's userdata + * because Lua 5.4's `table.concat` accepts any value with `__index` and + * `__len` metamethods (`checktab`, `TAB_R | TAB_L`). GH #942. + */ + +use mlua::{AnyUserData, Lua, MetaMethod, Result, Table, UserData, UserDataMethods, Value}; + +/// A dotted-integer version, compared lexicographically on its +/// components with a shorter prefix ordering first (`1.4 < 1.4.1`), as +/// pandoc's `Version` (Haskell's `Data.Version`) does. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct LuaVersion(pub Vec); + +impl LuaVersion { + /// The leading dotted-integer prefix of a version string: the part a + /// `Version` can hold. `"0.37.0-nightly.20261027"` → `0.37.0`; + /// `"1.9.13+test.20260910"` → `1.9.13`. A string with no leading + /// digit yields `0`, never an error — callers such as + /// `register_quarto_version` must always produce a Version (Q1's + /// `leadingDottedNumber` has the same contract). + pub fn leading(s: &str) -> Self { + let mut parts = Vec::new(); + for piece in s.split('.') { + let digits: String = piece.chars().take_while(|c| c.is_ascii_digit()).collect(); + if digits.is_empty() { + break; + } + // Digit-only strings of plausible length always parse; a + // pathological run of digits saturates rather than panics. + parts.push(digits.parse::().unwrap_or(u64::MAX)); + if digits.len() != piece.len() { + // "0-nightly" — the component ended at a non-digit, so + // nothing after it is part of the version. + break; + } + } + if parts.is_empty() { + parts.push(0); + } + LuaVersion(parts) + } + + /// Parse a strict version spec string: one or more `.`-separated + /// non-negative integers and nothing else. + fn parse_strict(s: &str) -> Option { + if s.is_empty() { + return None; + } + s.split('.') + .map(|p| { + if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) { + None + } else { + p.parse::().ok() + } + }) + .collect::>>() + .map(LuaVersion) + } + + /// Coerce a Lua value into a version the way `pandoc.types.Version` + /// does: a Version, a version string, a non-negative integer, or a + /// sequence of non-negative integers. + fn from_value(value: &Value) -> Result { + match value { + Value::UserData(ud) => ud + .borrow::() + .map(|v| v.clone()) + .map_err(|_| version_expected(value)), + Value::String(s) => { + let s = s.to_str()?; + LuaVersion::parse_strict(&s).ok_or_else(|| { + mlua::Error::runtime(format!( + "could not parse '{}' as a version: expected dot-separated integers", + &*s + )) + }) + } + Value::Integer(n) if *n >= 0 => Ok(LuaVersion(vec![*n as u64])), + Value::Number(n) if *n >= 0.0 && n.fract() == 0.0 => Ok(LuaVersion(vec![*n as u64])), + Value::Table(t) => { + let mut parts = Vec::new(); + for item in t.clone().sequence_values::() { + match item? { + Value::Integer(n) if n >= 0 => parts.push(n as u64), + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => parts.push(n as u64), + other => { + return Err(mlua::Error::runtime(format!( + "version component must be a non-negative integer, got {}", + other.type_name() + ))); + } + } + } + Ok(LuaVersion(parts)) + } + _ => Err(version_expected(value)), + } + } + + fn display(&self) -> String { + self.0 + .iter() + .map(|n| n.to_string()) + .collect::>() + .join(".") + } +} + +fn version_expected(value: &Value) -> mlua::Error { + mlua::Error::runtime(format!( + "Version expected, got {} (a version string, integer, or sequence of integers)", + value.type_name() + )) +} + +impl UserData for LuaVersion { + fn add_methods>(methods: &mut M) { + methods.add_meta_method(MetaMethod::ToString, |_, this, ()| Ok(this.display())); + methods.add_meta_method(MetaMethod::Len, |_, this, ()| Ok(this.0.len() as i64)); + // Lua 5.4 only consults `__eq` when both operands are userdata, so + // `v == "1.4"` is always false, exactly as in pandoc. + methods.add_meta_method(MetaMethod::Eq, |_, this, other: Value| { + Ok(match &other { + Value::UserData(ud) => ud.borrow::().is_ok_and(|o| *o == *this), + _ => false, + }) + }); + // `__lt`/`__le` as meta *functions*: for `v >= "1.4"` Lua calls + // `__le("1.4", v)`, with the string first, so the Version is not + // always the receiver. + methods.add_meta_function(MetaMethod::Lt, |_, (a, b): (Value, Value)| { + Ok(LuaVersion::from_value(&a)? < LuaVersion::from_value(&b)?) + }); + methods.add_meta_function(MetaMethod::Le, |_, (a, b): (Value, Value)| { + Ok(LuaVersion::from_value(&a)? <= LuaVersion::from_value(&b)?) + }); + // Integer keys index the components (1-based, as a Lua sequence); + // `must_be_at_least` is the one method. Done inside `__index` + // rather than `add_method` so this metamethod owns the lookup — + // `table.concat` needs it present alongside `__len`. + methods.add_meta_method(MetaMethod::Index, |lua, this, key: Value| match key { + Value::Integer(i) => Ok(match usize::try_from(i) { + Ok(i) if i >= 1 && i <= this.0.len() => Value::Integer(this.0[i - 1] as i64), + _ => Value::Nil, + }), + Value::Number(n) if n.fract() == 0.0 => { + let i = n as i64; + Ok(match usize::try_from(i) { + Ok(i) if i >= 1 && i <= this.0.len() => Value::Integer(this.0[i - 1] as i64), + _ => Value::Nil, + }) + } + Value::String(s) if s.to_str().is_ok_and(|s| &*s == "must_be_at_least") => { + Ok(Value::Function(lua.create_function( + |_, (this, expected, message): (AnyUserData, Value, Option)| { + let actual = this.borrow::()?; + let expected = LuaVersion::from_value(&expected)?; + if *actual < expected { + let message = message.unwrap_or_else(|| { + "expected version %s or newer, got %s".to_string() + }); + // pandoc formats the message with string.format; + // the two `%s` are expected then actual. + let message = message.replacen("%s", &expected.display(), 1).replacen( + "%s", + &actual.display(), + 1, + ); + return Err(mlua::Error::runtime(message)); + } + Ok(()) + }, + )?)) + } + _ => Ok(Value::Nil), + }); + } +} + +/// Wrap components as a `Version` userdata. +pub fn create_version(lua: &Lua, components: &[u64]) -> Result { + lua.create_userdata(LuaVersion(components.to_vec())) +} + +/// Register `pandoc.types` with its `Version` constructor. +pub fn register_pandoc_types(lua: &Lua, pandoc: &Table) -> Result<()> { + let types = lua.create_table()?; + types.set( + "Version", + lua.create_function(|lua, spec: Value| { + lua.create_userdata(LuaVersion::from_value(&spec)?) + })?, + )?; + pandoc.set("types", types)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lua() -> Lua { + let lua = Lua::new(); + let pandoc = lua.create_table().unwrap(); + register_pandoc_types(&lua, &pandoc).unwrap(); + lua.globals().set("pandoc", pandoc).unwrap(); + lua.globals() + .set("V", create_version(&lua, &[0, 36, 0]).unwrap()) + .unwrap(); + lua + } + + fn eval(lua: &Lua, src: &str) -> T { + lua.load(src).eval().unwrap() + } + + #[test] + fn leading_prefix() { + assert_eq!(LuaVersion::leading("0.36.0").0, vec![0, 36, 0]); + assert_eq!( + LuaVersion::leading("0.37.0-nightly.20261027").0, + vec![0, 37, 0] + ); + assert_eq!( + LuaVersion::leading("1.9.13+test.20260910").0, + vec![1, 9, 13] + ); + assert_eq!(LuaVersion::leading("1.4").0, vec![1, 4]); + assert_eq!(LuaVersion::leading("unknown").0, vec![0]); + assert_eq!(LuaVersion::leading("").0, vec![0]); + } + + #[test] + fn tostring_and_concat() { + let lua = lua(); + assert_eq!(eval::(&lua, "return tostring(V)"), "0.36.0"); + // The whole point of __index + __len: Lua 5.4's table.concat + // accepts the userdata, so Q1-era code keeps working. + assert_eq!( + eval::(&lua, "return table.concat(V, '.')"), + "0.36.0" + ); + assert_eq!(eval::(&lua, "return #V"), 3); + assert_eq!(eval::(&lua, "return V[2]"), 36); + assert!(eval::(&lua, "return V[4] == nil")); + assert_eq!(eval::(&lua, "return type(V)"), "userdata"); + } + + #[test] + fn comparisons_with_strings_either_side() { + let lua = lua(); + assert!(eval::(&lua, "return V >= '0.36'")); + assert!(eval::(&lua, "return V > '0.36'")); + assert!(eval::(&lua, "return V < '1.4'")); + assert!(eval::(&lua, "return '1.4' > V")); + assert!(eval::(&lua, "return '0.36.0' <= V")); + assert!(!eval::(&lua, "return V >= '1.4'")); + assert!(eval::( + &lua, + "return V == pandoc.types.Version('0.36.0')" + )); + assert!(eval::( + &lua, + "return V ~= pandoc.types.Version('0.36')" + )); + // Lua never calls __eq for mixed types; pandoc behaves the same. + assert!(!eval::(&lua, "return V == '0.36.0'")); + // Shorter prefix orders first, as in Data.Version. + assert!(eval::( + &lua, + "return pandoc.types.Version('1.4') < pandoc.types.Version('1.4.0')" + )); + } + + #[test] + fn constructor_accepts_pandoc_shapes() { + let lua = lua(); + assert_eq!( + eval::(&lua, "return tostring(pandoc.types.Version('2.11.3.2'))"), + "2.11.3.2" + ); + assert_eq!( + eval::(&lua, "return tostring(pandoc.types.Version(3))"), + "3" + ); + assert_eq!( + eval::(&lua, "return tostring(pandoc.types.Version({1, 23, 1}))"), + "1.23.1" + ); + assert_eq!( + eval::(&lua, "return tostring(pandoc.types.Version(V))"), + "0.36.0" + ); + let err = lua + .load("return pandoc.types.Version('1.2-beta')") + .eval::() + .unwrap_err() + .to_string(); + assert!(err.contains("could not parse '1.2-beta'"), "{err}"); + let err = lua + .load("return pandoc.types.Version(true)") + .eval::() + .unwrap_err() + .to_string(); + assert!(err.contains("Version expected, got boolean"), "{err}"); + } + + #[test] + fn must_be_at_least() { + let lua = lua(); + lua.load("V:must_be_at_least('0.36')").exec().unwrap(); + lua.load("V:must_be_at_least(V)").exec().unwrap(); + let err = lua + .load("V:must_be_at_least('1.4')") + .exec() + .unwrap_err() + .to_string(); + assert!( + err.contains("expected version 1.4 or newer, got 0.36.0"), + "{err}" + ); + let err = lua + .load("V:must_be_at_least('1.4', 'need %s, have %s')") + .exec() + .unwrap_err() + .to_string(); + assert!(err.contains("need 1.4, have 0.36.0"), "{err}"); + } +} diff --git a/crates/pampa/src/lua_options.rs b/crates/pampa/src/lua_options.rs index 32869ec1de..ed92f7309a 100644 --- a/crates/pampa/src/lua_options.rs +++ b/crates/pampa/src/lua_options.rs @@ -12,11 +12,55 @@ //! Feature-independent (like `dialect.rs`) so `unified_filter` can carry it //! whether or not the `lua-filter` feature is on. +use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use crate::dialect::SourceDialect; +/// What the host knows about the document and project a Lua script runs +/// for: everything Quarto 1 surfaced through `quarto.project`, +/// `quarto.doc.input_file` / `quarto.doc.output_file`, `PANDOC_STATE`, +/// and the environment `os.getenv` reads (GH #939, #940). All optional: +/// pampa's own tests and the Lua conformance suite run without a host, +/// and then these registrations produce the Quarto 1 "outside a project" +/// shape (nil directory, empty profile list). +#[derive(Clone, Debug, Default)] +pub struct HostContext { + /// Absolute path of the input being rendered → `quarto.doc.input_file`. + pub input_file: Option, + /// Absolute path of the output → `quarto.doc.output_file`. + pub output_file: Option, + /// `None` for single-file renders (Q1: `quarto.project.directory` is + /// nil outside a project). + pub project: Option, + /// Active profile names → `quarto.project.profile` (a `pandoc.List`). + pub profiles: Vec, + /// The environment `os.getenv` answers from: a snapshot the host took + /// on its own thread before any script ran (the real environment, + /// then file-defined `_environment` values for keys the real one + /// lacks, then `QUARTO_PROFILE` forced to the active list). `None` + /// means "no host": `os.getenv` is left to the stdlib on native and + /// to the runtime on WASM. A snapshot keeps the stdlib's libc + /// `getenv` off filter worker threads, where it would race any + /// `setenv` elsewhere in the process. + pub env: Option>>, +} + +/// The project a document renders inside, as `quarto.project` reports it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HostProject { + /// Project root, absolute. + pub directory: PathBuf, + /// Resolved output directory, absolute (the project root itself when + /// the project declares no `output-dir`). + pub output_directory: PathBuf, + /// Relative path from the document's directory back to the project + /// root, forward slashes, `"."` when they coincide — Q1's + /// `projectOffset`. + pub offset: String, +} + /// A directory `require("/module")` and `quarto.include` may resolve /// into by name: an extension's directory, addressed by the extension's /// name (bd-76ogq4ew, phase 3). @@ -61,6 +105,8 @@ pub struct LuaOptions { /// rasterizes with it, bd-gebcr1sa). `None` when there is none, which /// is always the case in WASM. pub typst: Option, + /// The document, project, and environment the scripts run for. + pub host: HostContext, } impl LuaOptions { @@ -70,6 +116,7 @@ impl LuaOptions { dialects, module_roots: ModuleRoots::default(), typst: None, + host: HostContext::default(), } } } @@ -87,6 +134,7 @@ impl std::fmt::Debug for LuaOptions { ) .field("module_roots", &self.module_roots) .field("typst", &self.typst) + .field("host", &self.host) .finish() } } diff --git a/crates/pampa/tests/wasm_lua.rs b/crates/pampa/tests/wasm_lua.rs index 1b8bb4f4ef..262581eec0 100644 --- a/crates/pampa/tests/wasm_lua.rs +++ b/crates/pampa/tests/wasm_lua.rs @@ -559,7 +559,8 @@ end // Test 6: Synthetic os module is registered in filter execution // ============================================================================ -/// Verify that the synthetic os module (os.time, os.clock, os.difftime) is +/// Verify that the synthetic os module (os.time, os.clock, os.difftime, +/// os.getenv) is /// registered when filters execute on wasm32. #[wasm_bindgen_test] async fn synthetic_os_available_in_filters() { @@ -579,6 +580,13 @@ function Para(el) assert(type(os.time) == "function", "os.time should be a function") assert(type(os.clock) == "function", "os.clock should be a function") assert(type(os.difftime) == "function", "os.difftime should be a function") + -- os.getenv is runtime-backed (nothing in the browser) and is what + -- the host's environment snapshot replaces (GH #939). + assert(type(os.getenv) == "function", "os.getenv should be a function") + assert(os.getenv("QUARTO_PROFILE") == nil, "no environment in the browser") + -- os.exit is the document-failing replacement, not absent (GH #941). + assert(type(os.exit) == "function", "os.exit should be a function") + assert(pcall(os.exit, 1) == false, "os.exit should raise, not return") return el end "# diff --git a/crates/quarto-core/src/lmd/dialect.rs b/crates/quarto-core/src/lmd/dialect.rs index ea804c87d2..5bd9200f12 100644 --- a/crates/quarto-core/src/lmd/dialect.rs +++ b/crates/quarto-core/src/lmd/dialect.rs @@ -19,7 +19,7 @@ use std::path::Path; use std::sync::Arc; use pampa::dialect::{DialectError, SourceDialect}; -use pampa::lua_options::{ExtensionRoot, LuaOptions, ModuleRoots}; +use pampa::lua_options::{ExtensionRoot, HostContext, HostProject, LuaOptions, ModuleRoots}; use super::desugar::{DesugarOptions, EmitMode, LmdError, desugar_lua_with}; @@ -88,13 +88,88 @@ pub fn lua_options( .collect(), }, typst: crate::render::find_typst(runtime), + host: HostContext::default(), } } +/// [`lua_options`] plus what the scripts of one document may ask about +/// where they run: `quarto.project`, `quarto.doc.input_file` / +/// `output_file`, `PANDOC_STATE`, and the environment `os.getenv` +/// answers from (GH #939, #940). `env_snapshot` is +/// [`crate::stage::StageContext::env_snapshot`]; `None` leaves `os.getenv` +/// to the stdlib. +pub fn lua_options_for_document( + project: &crate::project::ProjectContext, + runtime: &dyn quarto_system_runtime::SystemRuntime, + document: &crate::project::DocumentInfo, + output_file: std::path::PathBuf, + env_snapshot: Option>, +) -> LuaOptions { + let mut options = lua_options(project, runtime); + options.host = HostContext { + input_file: Some(document.input.clone()), + output_file: Some(output_file), + project: host_project(project, &document.input), + profiles: project + .config + .active_config_profiles + .iter() + .map(|p| p.name.clone()) + .collect(), + env: env_snapshot, + }; + options +} + +/// `quarto.project`'s paths for `input`, or `None` for a single-file +/// render (Q1: `quarto.project.directory` is nil outside a project). +/// `offset` is Q1's `projectOffset`: the relative path from the input's +/// directory back to the project root, forward slashes, `"."` when +/// they coincide. +fn host_project(project: &crate::project::ProjectContext, input: &Path) -> Option { + if project.is_single_file { + return None; + } + let input_dir = input.parent().unwrap_or(Path::new(".")); + let offset = pathdiff::diff_paths(&project.dir, input_dir) + .filter(|p| !p.as_os_str().is_empty()) + .map_or_else(|| ".".to_string(), |p| quarto_util::to_forward_slashes(&p)); + Some(HostProject { + directory: project.dir.clone(), + output_directory: project.output_dir.clone(), + offset, + }) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn host_project_offset_is_q1_project_offset() { + let dir = std::path::PathBuf::from("/proj"); + let project = crate::project::ProjectContext { + dir: dir.clone(), + output_dir: dir.join("_site"), + is_single_file: false, + ..Default::default() + }; + let root = host_project(&project, &dir.join("index.qmd")).unwrap(); + assert_eq!(root.offset, "."); + assert_eq!(root.directory, dir); + assert_eq!(root.output_directory, dir.join("_site")); + let nested = host_project(&project, &dir.join("a").join("b").join("p.qmd")).unwrap(); + assert_eq!(nested.offset, "../..", "forward slashes on every platform"); + + let single = crate::project::ProjectContext { + dir: dir.clone(), + output_dir: dir.clone(), + is_single_file: true, + ..Default::default() + }; + assert!(host_project(&single, &dir.join("doc.qmd")).is_none()); + } + #[test] fn compiles_a_module_keeping_its_lines() { let src = diff --git a/crates/quarto-core/src/lmd/mod.rs b/crates/quarto-core/src/lmd/mod.rs index 1199077ff5..c38f01c3dd 100644 --- a/crates/quarto-core/src/lmd/mod.rs +++ b/crates/quarto-core/src/lmd/mod.rs @@ -50,7 +50,7 @@ pub use desugar::{ DesugarOptions, EmitMode, FragmentKind, LmdError, desugar_lua, desugar_lua_expr, desugar_lua_expr_with, desugar_lua_with, }; -pub use dialect::{LmdDialect, dialects, lua_options}; +pub use dialect::{LmdDialect, dialects, lua_options, lua_options_for_document}; pub(crate) use emit::inline_lmd_source; /// The language tag an lmd cell carries: `` ```{lmd} `` parses to a diff --git a/crates/quarto-core/src/project/environment.rs b/crates/quarto-core/src/project/environment.rs index 05587c9188..fed92ad5ea 100644 --- a/crates/quarto-core/src/project/environment.rs +++ b/crates/quarto-core/src/project/environment.rs @@ -316,6 +316,43 @@ pub fn load_project_environment( env_map } +/// The map [`snapshot_environment`] produces: what `SystemRuntime::env_all` +/// returns, so no re-hashing between the two. +pub type EnvSnapshot = std::collections::HashMap; + +/// The environment Lua scripts see through `os.getenv` (GH #939): one +/// map, taken on the host's thread before any script runs, so the +/// stdlib's libc `getenv` never has to run on a filter worker thread +/// (where it would race any `setenv` elsewhere in the process) and every +/// script in a render sees the same environment. Layers, lowest first: +/// +/// 1. `real_env` — the process environment as the runtime reports it +/// (`SystemRuntime::env_all`, so a preview server's `--profile` +/// override is included); +/// 2. file-defined `_environment` pairs for keys the real environment +/// lacks — the same filter [`env_for_subprocess`] applies, so the +/// real environment keeps winning; +/// 3. `QUARTO_PROFILE` forced to `quarto_profile` when profiles are +/// active — the one deliberate exception +/// ([`crate::project::project_profile::quarto_profile_env_value`]): +/// Q1 wrote the normalized active list back into its environment. +pub fn snapshot_environment( + mut real_env: EnvSnapshot, + project_env: &LinkedHashMap, + quarto_profile: Option<&str>, +) -> EnvSnapshot { + for (k, v) in project_env { + real_env.entry(k.clone()).or_insert_with(|| v.clone()); + } + if let Some(profile) = quarto_profile { + real_env.insert( + super::project_profile::QUARTO_PROFILE_VAR.to_string(), + profile.to_string(), + ); + } + real_env +} + /// The subset of the project env map to pass to a spawned subprocess: /// every pair whose key is **not** set in the real process environment. /// Children inherit the real environment on spawn, so applying these @@ -880,6 +917,30 @@ fn resolve_name( mod tests { use super::*; + #[test] + fn snapshot_layers_real_env_file_values_and_profile() { + let mut real = std::collections::HashMap::new(); + real.insert("SHADOWED".to_string(), "real".to_string()); + real.insert("QUARTO_PROFILE".to_string(), "stale".to_string()); + let mut files = LinkedHashMap::new(); + files.insert("SHADOWED".to_string(), "file".to_string()); + files.insert("ONLY_IN_FILE".to_string(), "file".to_string()); + + let snap = snapshot_environment(real.clone(), &files, Some("drafts,release")); + assert_eq!(snap["SHADOWED"], "real", "real environment wins"); + assert_eq!(snap["ONLY_IN_FILE"], "file", "file fills the gap"); + assert_eq!( + snap["QUARTO_PROFILE"], "drafts,release", + "the active list replaces an inherited QUARTO_PROFILE" + ); + + let snap = snapshot_environment(real, &files, None); + assert_eq!( + snap["QUARTO_PROFILE"], "stale", + "no active profiles: the inherited value stands" + ); + } + fn no_lookup(_: &str) -> Option { None } diff --git a/crates/quarto-core/src/render.rs b/crates/quarto-core/src/render.rs index bf05f7b526..3cbf225d43 100644 --- a/crates/quarto-core/src/render.rs +++ b/crates/quarto-core/src/render.rs @@ -243,6 +243,13 @@ pub struct RenderContext<'a> { /// Bridged to/from `StageContext` by `AstTransformsStage`. pub includes: PandocIncludes, + /// The environment Lua shortcode handlers see through `os.getenv` + /// (GH #939): [`crate::stage::StageContext::env_snapshot`], bridged + /// one-way by `AstTransformsStage`. `None` when a `RenderContext` is + /// built directly (unit tests, out-of-band drivers); the Lua `os` + /// table is then left as the stdlib / runtime provides it. + pub env_snapshot: Option>, + /// Diagnostics (warnings, errors, info) collected during transforms pub diagnostics: Vec, @@ -606,6 +613,7 @@ impl<'a> RenderContext<'a> { binaries, options: RenderOptions::default(), includes: PandocIncludes::default(), + env_snapshot: None, diagnostics: Vec::new(), ref_type_registry: None, crossref_index: None, diff --git a/crates/quarto-core/src/stage/context.rs b/crates/quarto-core/src/stage/context.rs index 559cd0df86..8e84769688 100644 --- a/crates/quarto-core/src/stage/context.rs +++ b/crates/quarto-core/src/stage/context.rs @@ -102,6 +102,13 @@ pub struct StageContext { /// (Q1 parity: env files are project-scoped). pub project_env: hashlink::LinkedHashMap, + /// The environment Lua filters and shortcodes see through + /// `os.getenv`, taken once here — on the thread that builds the + /// context, before any script runs — by + /// [`crate::project::environment::snapshot_environment`] (GH #939). + /// Shared with the per-document `LuaOptions` by `Arc`. + pub env_snapshot: Arc, + // === Mutable state === /// Artifact store for dependencies and intermediates pub artifacts: ArtifactStore, @@ -445,6 +452,14 @@ impl StageContext { &active_profile_names, &mut startup_diagnostics, ); + let env_snapshot = Arc::new(crate::project::environment::snapshot_environment( + runtime.env_all().unwrap_or_default(), + &project_env, + crate::project::project_profile::quarto_profile_env_value( + &project.config.active_config_profiles, + ) + .as_deref(), + )); Ok(Self { runtime, @@ -456,6 +471,7 @@ impl StageContext { extensions, variables, project_env, + env_snapshot, artifacts: ArtifactStore::new(), includes: PandocIncludes::default(), diagnostics: startup_diagnostics, diff --git a/crates/quarto-core/src/stage/stages/ast_transforms.rs b/crates/quarto-core/src/stage/stages/ast_transforms.rs index c81908cf5b..36f3110b29 100644 --- a/crates/quarto-core/src/stage/stages/ast_transforms.rs +++ b/crates/quarto-core/src/stage/stages/ast_transforms.rs @@ -222,6 +222,9 @@ impl PipelineStage for AstTransformsStage { // Transfer mutable state to the RenderContext render_ctx.artifacts = std::mem::take(&mut ctx.artifacts); render_ctx.includes = std::mem::take(&mut ctx.includes); + // The environment Lua shortcodes read via os.getenv (GH #939); + // read-only, so the Arc is cloned rather than moved. + render_ctx.env_snapshot = Some(ctx.env_snapshot.clone()); render_ctx.ref_type_registry = ctx.ref_type_registry.take(); render_ctx.crossref_index = ctx.crossref_index.take(); render_ctx.observer = ctx.observer.clone(); diff --git a/crates/quarto-core/src/stage/stages/user_filters.rs b/crates/quarto-core/src/stage/stages/user_filters.rs index 4691c47772..ab6b0b53c5 100644 --- a/crates/quarto-core/src/stage/stages/user_filters.rs +++ b/crates/quarto-core/src/stage/stages/user_filters.rs @@ -235,8 +235,15 @@ impl PipelineStage for UserFiltersStage { .parent() .map_or_else(|| std::path::PathBuf::from("."), |p| p.to_path_buf()); // The lmd dialect and the project's module roots, for the filters' - // `require` (bd-76ogq4ew). - let lua_options = crate::lmd::lua_options(&ctx.project, ctx.runtime.as_ref()); + // `require` (bd-76ogq4ew), plus this document's place in the + // project for quarto.project / quarto.doc.input_file (GH #939, #940). + let lua_options = crate::lmd::lua_options_for_document( + &ctx.project, + ctx.runtime.as_ref(), + &ctx.document, + ctx.output_path(), + Some(ctx.env_snapshot.clone()), + ); // The Lua filter future is !Send (mlua::Lua is !Send), but this // pipeline stage runs under #[async_trait] which requires Send on native. diff --git a/crates/quarto-core/src/transforms/shortcode_resolve.rs b/crates/quarto-core/src/transforms/shortcode_resolve.rs index 891e75eff9..5316e412d1 100644 --- a/crates/quarto-core/src/transforms/shortcode_resolve.rs +++ b/crates/quarto-core/src/transforms/shortcode_resolve.rs @@ -1228,7 +1228,13 @@ impl AstTransform for ShortcodeResolveTransform { && let Some(runtime) = self.runtime.as_ref() { let runtime = runtime.clone(); - let lua_options = crate::lmd::lua_options(ctx.project, runtime.as_ref()); + let lua_options = crate::lmd::lua_options_for_document( + ctx.project, + runtime.as_ref(), + ctx.document, + ctx.output_path(), + ctx.env_snapshot.clone(), + ); match pampa::lua::LuaShortcodeEngine::new_with( &self.target_format, runtime, diff --git a/crates/quarto-system-runtime/src/native.rs b/crates/quarto-system-runtime/src/native.rs index 4d8152b43c..2c46896666 100644 --- a/crates/quarto-system-runtime/src/native.rs +++ b/crates/quarto-system-runtime/src/native.rs @@ -349,7 +349,11 @@ impl SystemRuntime for NativeRuntime { } fn env_all(&self) -> RuntimeResult> { - let mut vars: HashMap = std::env::vars().collect(); + // `vars_os`, not `vars`: the latter panics on a non-UTF-8 entry, + // and this now runs for every rendered document (GH #939). + let mut vars: HashMap = std::env::vars_os() + .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))) + .collect(); vars.extend(self.env_overrides.iter().cloned()); Ok(vars) } diff --git a/crates/quarto/tests/integration/lua_host_context_cli.rs b/crates/quarto/tests/integration/lua_host_context_cli.rs new file mode 100644 index 0000000000..939475fcd4 --- /dev/null +++ b/crates/quarto/tests/integration/lua_host_context_cli.rs @@ -0,0 +1,252 @@ +/* + * tests/integration/lua_host_context_cli.rs + * Copyright (c) 2026 Posit, PBC + * + * What a Lua filter or shortcode learns about where it is running + * (GH #939, #940): `quarto.project`, `quarto.doc.input_file` / + * `output_file`, `PANDOC_STATE`, and `os.getenv` over the host's + * environment snapshot (`--profile` visible as `QUARTO_PROFILE`, + * `_environment` values visible, real environment winning). + * + * End to end through the `q2` binary because the values under test are + * assembled from the project context, the document, the resolved output + * path, and the CLI flags — exactly the plumbing a unit test would stub. + */ + +use std::collections::HashMap; +use std::path::Path; +use std::process::Command; + +use tempfile::TempDir; + +const Q2_BIN: &str = env!("CARGO_BIN_EXE_q2"); + +/// A filter that appends a code block of `key=value` lines describing +/// where it runs. `tostring` so nils print as `nil`. +const PROBE_LUA: &str = r#" +function Pandoc(doc) + local function line(k, v) return k .. "=" .. tostring(v) end + local lines = { + line("directory", quarto.project.directory), + line("offset", quarto.project.offset), + line("output_directory", quarto.project.output_directory), + line("profile", table.concat(quarto.project.profile, ",")), + line("profile_type", pandoc.utils.type(quarto.project.profile)), + line("QUARTO_PROFILE", os.getenv("QUARTO_PROFILE")), + line("Q2_TEST_REAL", os.getenv("Q2_TEST_REAL")), + line("Q2_TEST_FILE_ONLY", os.getenv("Q2_TEST_FILE_ONLY")), + line("Q2_TEST_UNSET", os.getenv("Q2_TEST_UNSET")), + line("input_file", quarto.doc.input_file), + line("output_file", quarto.doc.output_file), + line("state_input", PANDOC_STATE.input_files[1]), + line("state_output", PANDOC_STATE.output_file), + } + doc.blocks:insert(pandoc.CodeBlock(table.concat(lines, "\n"), pandoc.Attr("probe"))) + return doc +end +"#; + +/// A shortcode handler reporting the same things from the shortcode +/// environment. +const WHEREAMI_LUA: &str = r#" +return { + ["whereami"] = function(args, kwargs, meta) + return pandoc.Str("SC-OFFSET=" .. tostring(quarto.project.offset) + .. ";SC-PROFILE=" .. tostring(os.getenv("QUARTO_PROFILE"))) + end +} +"#; + +/// The `key=value` lines of the probe's code block in a rendered page. +fn probe_values(html: &str) -> HashMap { + let start = html + .find("id=\"probe\"") + .unwrap_or_else(|| panic!("no probe block in:\n{html}")); + let body = &html[start..]; + let open = body.find('>').unwrap() + 1; + let close = body.find("").unwrap(); + body[open..close] + .lines() + .filter_map(|l| { + let text = strip_tags(l); + let (k, v) = text.split_once('=')?; + Some((k.to_string(), v.to_string())) + }) + .collect() +} + +/// The syntax highlighter may wrap lines in spans; drop any tags. +fn strip_tags(s: &str) -> String { + let mut out = String::new(); + let mut in_tag = false; + for c in s.chars() { + match c { + '<' => in_tag = true, + '>' => in_tag = false, + c if !in_tag => out.push(c), + _ => {} + } + } + html_escape_undo(&out) +} + +fn html_escape_undo(s: &str) -> String { + s.replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") + .replace("&", "&") +} + +fn write(root: &Path, rel: &str, content: &str) { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, content).unwrap(); +} + +fn q2(root: &Path, args: &[&str]) -> std::process::Output { + Command::new(Q2_BIN) + .current_dir(root) + .args(args) + .env_remove("QUARTO_PROFILE") + .env_remove("Q2_TEST_FILE_ONLY") + .env_remove("Q2_TEST_UNSET") + .env("Q2_TEST_REAL", "real") + .output() + .expect("q2 runs") +} + +#[test] +fn website_pages_see_project_paths_profiles_and_environment() { + let dir = TempDir::new().unwrap(); + let root = dir.path(); + // The filter is named by absolute path: a relative `probe.lua` resolves + // against each page's own directory today (GH #945), which is not what + // this test is about. + let probe = root.join("probe.lua"); + write(root, "probe.lua", PROBE_LUA); + write(root, "whereami.lua", WHEREAMI_LUA); + write( + root, + "_quarto.yml", + &format!( + "project:\n type: website\nprofile:\n group:\n - [drafts, release]\nfilters:\n - {}\n", + probe.display() + ), + ); + write( + root, + "_environment", + "Q2_TEST_REAL=file\nQ2_TEST_FILE_ONLY=file\n", + ); + write( + root, + "index.qmd", + "---\ntitle: Index\nshortcodes: [whereami.lua]\n---\n\n{{< whereami >}}\n", + ); + write(root, "sub/page.qmd", "---\ntitle: Sub\n---\n\nhello\n"); + + let out = q2(root, &["render", "--profile", "drafts"]); + assert!( + out.status.success(), + "render failed:\n{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + + let index_html = std::fs::read_to_string(root.join("_site").join("index.html")).unwrap(); + let index = probe_values(&index_html); + let sub = probe_values( + &std::fs::read_to_string(root.join("_site").join("sub").join("page.html")).unwrap(), + ); + + // quarto.project: the same project from both pages, offsets differ. + assert_eq!(index["offset"], "."); + assert_eq!(sub["offset"], ".."); + assert_eq!(index["directory"], sub["directory"]); + assert!( + Path::new(&index["directory"]).is_absolute(), + "{}", + index["directory"] + ); + assert_eq!( + Path::new(&index["output_directory"]), + Path::new(&index["directory"]).join("_site") + ); + assert_eq!(index["profile"], "drafts"); + assert_eq!(index["profile_type"], "List"); + + // os.getenv over the snapshot: --profile is QUARTO_PROFILE, the real + // environment beats `_environment`, `_environment` fills gaps, and an + // unset variable is nil. + assert_eq!(index["QUARTO_PROFILE"], "drafts"); + assert_eq!(index["Q2_TEST_REAL"], "real"); + assert_eq!(index["Q2_TEST_FILE_ONLY"], "file"); + assert_eq!(index["Q2_TEST_UNSET"], "nil"); + + // quarto.doc.input_file / output_file and the minimal PANDOC_STATE: + // absolute, per page, consistent with quarto.project. Built with + // Path::join, never literal separators (Windows). + let dir = Path::new(&index["directory"]); + assert_eq!(Path::new(&index["input_file"]), dir.join("index.qmd")); + assert_eq!( + Path::new(&sub["input_file"]), + dir.join("sub").join("page.qmd") + ); + assert_eq!( + Path::new(&index["output_file"]), + dir.join("_site").join("index.html") + ); + assert_eq!( + Path::new(&sub["output_file"]), + dir.join("_site").join("sub").join("page.html") + ); + assert_eq!(sub["state_input"], sub["input_file"]); + assert_eq!(sub["state_output"], sub["output_file"]); + + // The shortcode environment sees the same things. + assert!( + index_html.contains("SC-OFFSET=.;SC-PROFILE=drafts"), + "{index_html}" + ); +} + +#[test] +fn single_file_render_has_q1_nils_and_no_profiles() { + let dir = TempDir::new().unwrap(); + let root = dir.path(); + write(root, "probe.lua", PROBE_LUA); + write( + root, + "doc.qmd", + "---\ntitle: Doc\nfilters: [probe.lua]\n---\n\nhello\n", + ); + + let out = q2(root, &["render", "doc.qmd"]); + assert!( + out.status.success(), + "render failed:\n{}", + String::from_utf8_lossy(&out.stderr) + ); + let doc = probe_values(&std::fs::read_to_string(root.join("doc.html")).unwrap()); + assert_eq!(doc["directory"], "nil"); + assert_eq!(doc["offset"], "nil"); + assert_eq!(doc["output_directory"], "nil"); + assert_eq!(doc["profile"], ""); + assert_eq!(doc["profile_type"], "List"); + assert_eq!(doc["QUARTO_PROFILE"], "nil"); + assert_eq!(doc["Q2_TEST_REAL"], "real"); + // No project, no `_environment`: file-only variables do not exist. + assert_eq!(doc["Q2_TEST_FILE_ONLY"], "nil"); + // Paths are still known outside a project. + let input = Path::new(&doc["input_file"]); + assert!( + input.is_absolute() && input.ends_with("doc.qmd"), + "{input:?}" + ); + assert_eq!( + Path::new(&doc["output_file"]), + input.with_file_name("doc.html") + ); + assert_eq!(doc["state_input"], doc["input_file"]); +} diff --git a/crates/quarto/tests/integration/lua_os_exit_cli.rs b/crates/quarto/tests/integration/lua_os_exit_cli.rs new file mode 100644 index 0000000000..1d01e2a66f --- /dev/null +++ b/crates/quarto/tests/integration/lua_os_exit_cli.rs @@ -0,0 +1,116 @@ +/* + * tests/integration/lua_os_exit_cli.rs + * Copyright (c) 2026 Posit, PBC + * + * `os.exit(1)` in a Lua filter fails the document, not the process + * (GH #941). The scenario from the issue: a three-page website whose + * filter exits on page A, where page C also has a parse error. Before the + * fix the process died at A: nothing in `_site/`, no summary, and C's + * error never reported. + */ + +use std::path::Path; +use std::process::Command; + +use tempfile::TempDir; + +const Q2_BIN: &str = env!("CARGO_BIN_EXE_q2"); + +const DIE_LUA: &str = r#" +function Pandoc(doc) + local title = pandoc.utils.stringify(doc.meta.title) + if title == "A" then + io.stderr:write("fatal: validation failed on A\n") + os.exit(1) + end + return doc +end +"#; + +fn write(root: &Path, rel: &str, content: &str) { + std::fs::write(root.join(rel), content).unwrap(); +} + +#[test] +fn os_exit_fails_one_document_and_the_render_goes_on() { + let dir = TempDir::new().unwrap(); + let root = dir.path(); + write(root, "die.lua", DIE_LUA); + write( + root, + "_quarto.yml", + "project:\n type: website\nfilters:\n - die.lua\n", + ); + write(root, "a.qmd", "---\ntitle: A\n---\n\npage a\n"); + write(root, "b.qmd", "---\ntitle: B\n---\n\npage b\n"); + write(root, "c.qmd", "---\ntitle: C\n---\n\n*unclosed emphasis\n"); + + let out = Command::new(Q2_BIN) + .current_dir(root) + .args(["render"]) + .output() + .expect("q2 runs"); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + let all = format!("{stdout}\n{stderr}"); + + // The render as a whole still fails... + assert!(!out.status.success(), "expected a non-zero exit:\n{all}"); + assert!( + out.status.code().is_some(), + "the process must exit, not die of a signal: {:?}", + out.status + ); + + // ...but only page A is lost: B rendered, and C's own error was + // reached and reported. + let site = root.join("_site"); + assert!(site.join("b.html").is_file(), "b.html missing:\n{all}"); + assert!( + !site.join("a.html").exists(), + "a.html must not render:\n{all}" + ); + assert!( + all.contains("Q-2-12"), + "c.qmd's parse error not reported:\n{all}" + ); + + // A's failure names the filter and the exit code, and the filter's + // own stderr output came through first. + assert!(all.contains("fatal: validation failed on A"), "{all}"); + assert!( + all.contains("die.lua called os.exit(1); the document was not rendered"), + "{all}" + ); + assert!(all.contains("a.qmd"), "the failing page is named:\n{all}"); + + // And the summary is printed. + assert!(all.contains("Rendered 1 of 3 files"), "{all}"); +} + +#[test] +fn os_exit_zero_also_fails_the_document() { + // Quarto 1 parity: pandoc exiting 0 without output was still a + // failed render. The code is reported so the author sees what ran. + let dir = TempDir::new().unwrap(); + let root = dir.path(); + write(root, "stop.lua", "function Pandoc(doc) os.exit() end\n"); + write( + root, + "doc.qmd", + "---\ntitle: D\nfilters: [stop.lua]\n---\n\nhello\n", + ); + let out = Command::new(Q2_BIN) + .current_dir(root) + .args(["render", "doc.qmd"]) + .output() + .expect("q2 runs"); + let all = format!( + "{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + assert!(!out.status.success(), "{all}"); + assert!(!root.join("doc.html").exists(), "{all}"); + assert!(all.contains("stop.lua called os.exit(0)"), "{all}"); +} diff --git a/crates/quarto/tests/integration/main.rs b/crates/quarto/tests/integration/main.rs index 4917e22940..74f65a701a 100644 --- a/crates/quarto/tests/integration/main.rs +++ b/crates/quarto/tests/integration/main.rs @@ -24,6 +24,8 @@ pub mod get_config_cli; pub mod json_errors; pub mod jupyter_kernel_cleanup_e2e; pub mod lmd_snapshots; +pub mod lua_host_context_cli; +pub mod lua_os_exit_cli; pub mod metadata_flag_cli_e2e; pub mod nested_projects_cli; pub mod nightly_gate; diff --git a/crates/quarto/tests/smoke-all/extensions/builtin-version-shortcode/test.qmd b/crates/quarto/tests/smoke-all/extensions/builtin-version-shortcode/test.qmd index 4669cae472..7b39a28e55 100644 --- a/crates/quarto/tests/smoke-all/extensions/builtin-version-shortcode/test.qmd +++ b/crates/quarto/tests/smoke-all/extensions/builtin-version-shortcode/test.qmd @@ -6,7 +6,9 @@ _quarto: html: dom-parity: true noErrors: true + # The real build version (GH #942), not the former {0,1,0} placeholder. ensureFileRegexMatches: + - ["The current version is \\d+\\.\\d+\\.\\d+\\."] - ["0\\.1\\.0"] --- diff --git a/docs/guides/authoring/lua-filters.qmd b/docs/guides/authoring/lua-filters.qmd index 41635ba17a..802b8c921a 100644 --- a/docs/guides/authoring/lua-filters.qmd +++ b/docs/guides/authoring/lua-filters.qmd @@ -344,3 +344,88 @@ Quarto 1 accepts several other fields on a dependency: `meta`, `links`, yet, and warns once per dependency that names one, so a filter carried over from Quarto 1 tells you what was dropped rather than failing. Any other field is a typo and raises an error. + +## Where the filter is running + +A filter often needs to know which file it is processing and where the +project is, for example to build a link from the current page to a file at +the project root. Quarto 2 provides the same values Quarto 1 did: + +``` lua +quarto.doc.input_file -- absolute path of the file being rendered +quarto.doc.output_file -- absolute path its output will be written to +quarto.project.directory -- project root (nil outside a project) +quarto.project.output_directory -- resolved output directory (nil outside a project) +quarto.project.offset -- relative path from this file's directory back + -- to the project root: "." or "../..", forward + -- slashes (nil outside a project) +quarto.project.profile -- pandoc.List of active profile names, possibly empty +``` + +So a page at `guides/intro.qmd` links to `appendix.qmd` at the root with: + +``` lua +local href = quarto.project.offset .. "/appendix.html" +``` + +`PANDOC_STATE.input_files` (a one-element list holding `input_file`) and +`PANDOC_STATE.output_file` are set too, for filters written against pandoc's +API. The other `PANDOC_STATE` fields have no equivalent here and are `nil`. + +### Environment variables and profiles + +`os.getenv` sees the environment the render started with, plus the variables +your project's `_environment` files define (a real environment variable +always wins over a file). `QUARTO_PROFILE` is the active profile list, so a +filter sees `--profile drafts` the same way it sees +`QUARTO_PROFILE=drafts`: + +``` lua +if os.getenv("QUARTO_PROFILE") == "drafts" then ... end +-- or, without string handling: +if quarto.project.profile:includes("drafts") then ... end +``` + +The environment is read once, before any filter runs, and every filter and +shortcode in the render sees the same values. + +## Checking versions + +`quarto.version` is the version of Quarto you are running, as a pandoc +`Version` object. It compares with strings and with other versions, prints +with `tostring`, and still works with `table.concat`: + +``` lua +if quarto.version < "0.36" then + quarto.log.warning("this filter needs Quarto 0.36 or newer") +end +print(tostring(quarto.version)) -- "0.36.0" +print(table.concat(quarto.version, ".")) -- "0.36.0" +quarto.version:must_be_at_least("0.36") -- raises if older +``` + +`pandoc.types.Version` builds one from a string, a number or a list of +integers, and `PANDOC_VERSION` / `PANDOC_API_VERSION` are `Version` objects +as well. Quarto 2 releases are numbered `0.x` for now, so a filter that must +tell the two apart can test `quarto.version < "1"`: true here, false on +Quarto 1. + +## Failing a render + +Three ways to stop, from gentlest to bluntest: + +- `quarto.error(message, element)` reports an error diagnostic pointing at + the source location of `element`. The document fails; the rest of the + project still renders. +- `error(message)` fails the document with a plain Lua error. The rest of + the project still renders and the summary lists the failure. +- `os.exit(code)` also fails the document. Quarto 1 filters use it because + there pandoc was a separate process; in Quarto 2 the filter runs inside + the renderer, so `os.exit` is intercepted rather than ending the process. + The failure message names the filter and the code; the remaining + documents render, errors on them are still reported, and the render as a + whole exits non-zero. `os.exit(0)` counts as a failure too, since no + output was produced. + +Prefer `quarto.error` in new code: it is the only one that points the author +at a location in their document.