Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(templates): add the tojson filter for structured vars (#4524)

Maximilian Roosd890a16645fd
diff --git a/Cargo.toml b/Cargo.toml
index 2178e6fb2..12f5f17a6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -198,9 +198,11 @@ tracing-subscriber = { version = "0.3.17", default-features = false, features =
# Only enable needed features; macros and multi-template loading remain disabled.
# `unstable_machinery` supplies syntax analysis for migrations and diagnostics;
# `debug` supplies error source spans, including release builds.
+# `json` supplies the `tojson` filter for passing structured vars to commands.
minijinja = { version = "3.0", default-features = false, features = [
"builtins",
"debug",
+ "json",
"serde",
"std_collections",
"unstable_machinery",
diff --git a/docs/src/content/docs/hook.md b/docs/src/content/docs/hook.md
index b6de07fef..e73907239 100644
--- a/docs/src/content/docs/hook.md
+++ b/docs/src/content/docs/hook.md
@@ -191,6 +191,14 @@ Variables use dot access and the `default` filter for missing keys. JSON object/
dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.config.port | default('3000') }}"
```
+The `tojson` filter renders a whole object or array as JSON, for commands that take JSON input:
+
+```toml
+# .config/wt.toml
+[post-start]
+seed = "curl -X POST localhost:3000/seed -d {{ vars.config | tojson }}"
+```
+
## Worktrunk filters
Templates support Jinja2 filters for transforming values:
diff --git a/plugins/worktrunk/skills/worktrunk/reference/hook.md b/plugins/worktrunk/skills/worktrunk/reference/hook.md
index 337412e38..7352a9ed4 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/hook.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/hook.md
@@ -185,6 +185,14 @@ Variables use dot access and the `default` filter for missing keys. JSON object/
dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.config.port | default('3000') }}"
```
+The `tojson` filter renders a whole object or array as JSON, for commands that take JSON input:
+
+```toml
+# .config/wt.toml
+[post-start]
+seed = "curl -X POST localhost:3000/seed -d {{ vars.config | tojson }}"
+```
+
## Worktrunk filters
Templates support Jinja2 filters for transforming values:
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 337412e38..7352a9ed4 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -185,6 +185,14 @@ Variables use dot access and the `default` filter for missing keys. JSON object/
dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.config.port | default('3000') }}"
```
+The `tojson` filter renders a whole object or array as JSON, for commands that take JSON input:
+
+```toml
+# .config/wt.toml
+[post-start]
+seed = "curl -X POST localhost:3000/seed -d {{ vars.config | tojson }}"
+```
+
## Worktrunk filters
Templates support Jinja2 filters for transforming values:
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index ab614935b..f544976c7 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1815,6 +1815,14 @@ Variables use dot access and the `default` filter for missing keys. JSON object/
dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.config.port | default('3000') }}"
```
+The `tojson` filter renders a whole object or array as JSON, for commands that take JSON input:
+
+```toml
+# .config/wt.toml
+[post-start]
+seed = "curl -X POST localhost:3000/seed -d {{ vars.config | tojson }}"
+```
+
## Worktrunk filters
Templates support Jinja2 filters for transforming values:
diff --git a/src/commands/list/custom_columns.rs b/src/commands/list/custom_columns.rs
index e3485cf09..0003a11fa 100644
--- a/src/commands/list/custom_columns.rs
+++ b/src/commands/list/custom_columns.rs
@@ -315,8 +315,10 @@ mod tests {
max_width: 40,
priority: 9,
},
+ // A header that looks like a file extension renders raw, not
+ // JSON-quoted as MiniJinja's name-based autoescape would.
ResolvedCustomColumn {
- name: "Tag".to_string(),
+ name: "json".to_string(),
template: "{{ branch }}!".to_string(),
max_width: 40,
priority: 9,
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 2123592cb..9589544ec 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -18,8 +18,8 @@ use std::hash::{Hash, Hasher};
use std::sync::Arc;
use color_print::cformat;
-use minijinja::value::{Enumerator, Object, ObjectRepr, Serde, StringInput};
-use minijinja::{Environment, ErrorKind, State, UndefinedBehavior, Value};
+use minijinja::value::{Enumerator, Kwargs, Object, ObjectRepr, Serde, StringInput};
+use minijinja::{AutoEscape, Environment, ErrorKind, State, UndefinedBehavior, Value};
use regex::Regex;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
@@ -909,6 +909,10 @@ pub fn template_environment(repo: &Repository) -> Environment<'static> {
// SemiStrict: errors on undefined variable use (printing, iteration) but allows
// truthiness checks ({% if var %}). This catches typos while supporting optional vars.
env.set_undefined_behavior(UndefinedBehavior::SemiStrict);
+ // MiniJinja picks HTML or JSON escaping from the template name's extension,
+ // and our names are config keys (a custom column named `json` or `html`),
+ // not file names.
+ env.set_auto_escape_callback(|_| AutoEscape::None);
// Register custom filters
env.add_filter("sanitize", |state: &State, value: Value| {
@@ -943,6 +947,17 @@ pub fn template_environment(repo: &Repository) -> Environment<'static> {
)
});
env.add_filter("codename", codename_filter);
+ // MiniJinja's `tojson` writes an undefined value as `null`. Fail on it as
+ // printing does, so a missing `vars` key errors instead of sending `null`.
+ env.add_filter(
+ "tojson",
+ |state: &State, value: Value, indent: Option<Value>, kwargs: Kwargs| {
+ if value.is_undefined() {
+ StringInput::new(state, &value)?;
+ }
+ minijinja::filters::tojson(&value, indent, kwargs)
+ },
+ );
// Register worktree_path_of_branch function for looking up branch worktree paths.
// Returns raw paths — shell escaping is applied by the formatter at output time.
@@ -2955,6 +2970,28 @@ mod tests {
.unwrap(),
"fallback"
);
+
+ // `tojson` errors on a missing key, as printing it does, rather than
+ // writing `null`
+ let err = expand_template(
+ "{{ vars.config.missing | tojson }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap_err();
+ // MiniJinja names the undefined expression only in debug builds (see
+ // the undefined-diagnostics test); accept either form.
+ assert!(
+ [
+ "Failed to expand test: undefined value: `vars.config.missing` is undefined @ line 1",
+ "Failed to expand test: undefined value @ line 1",
+ ]
+ .contains(&err.message.as_str()),
+ "got: {}",
+ err.message
+ );
}
#[test]
diff --git a/tests/integration_tests/doc_templates.rs b/tests/integration_tests/doc_templates.rs
index 9fe0f227f..aa4b3daeb 100644
--- a/tests/integration_tests/doc_templates.rs
+++ b/tests/integration_tests/doc_templates.rs
@@ -546,6 +546,37 @@ fn test_doc_example_dev_server(repo: TestRepo) {
);
}
+#[rstest]
+fn test_doc_example_vars_tojson(repo: TestRepo) {
+ // From docs/src/content/docs/hook.md, "Template variables":
+ // seed = "curl -X POST localhost:3000/seed -d {{ vars.config | tojson }}"
+ //
+ // `tojson` writes `'`, `<`, `>` and `&` as `\u` escapes, which JSON
+ // parsers decode back.
+ repo.run_git(&[
+ "config",
+ "worktrunk.state.main.vars.config",
+ r#"{"port": 3000, "name": "it's"}"#,
+ ]);
+
+ let repository = Repository::at(repo.root_path()).unwrap();
+ let mut vars = HashMap::new();
+ vars.insert("branch", "main");
+
+ let result = expand_template(
+ "curl -X POST localhost:3000/seed -d {{ vars.config | tojson }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &repository,
+ "test",
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ r#"curl -X POST localhost:3000/seed -d '{"name": "it\u0027s", "port": 3000}'"#
+ );
+}
+
#[rstest]
fn test_doc_example_worktree_path_sanitize(repo: TestRepo) {
// From docs/src/content/docs/tips-patterns.md, "Bare repository layout":