Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Use minijinja for LLM prompt templates
Maximilian Roos68c5b791fc8d
diff --git a/Cargo.lock b/Cargo.lockindex 872ca56ee..10f0f4477 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1049,6 +1049,15 @@ version = "2.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"+[[package]]+name = "minijinja"+version = "2.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9f264d75233323f4b7d2f03aefe8a990690cdebfbfe26ea86bcbaec5e9ac990"+dependencies = [+ "serde",+]+[[package]]name = "nix"version = "0.28.0"@@ -2295,6 +2304,7 @@ dependencies = ["insta","insta-cmd","log",+ "minijinja","portable-pty","rayon","regex",diff --git a/Cargo.toml b/Cargo.tomlindex 425e23e94..02c1b69f3 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -28,6 +28,7 @@ directories = "6.0"env_logger = "0.11"etcetera = "0.11"log = "0.4"+minijinja = "2.12"rayon = "1.11"serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"diff --git a/config.example.toml b/config.example.tomlindex 86816a55a..64d9cbfa2 100644--- a/config.example.toml+++ b/config.example.toml@@ -30,8 +30,8 @@ worktree-path = "../{main-worktree}.{branch}"# command = "aichat"# args = ["-m", "claude:claude-haiku-4.5"]-# Optional: Custom prompt template (inline)-# Available variables: {git-diff}, {branch}, {recent-commits}, {repo}+# Optional: Custom prompt template (inline) - Uses Jinja2 syntax+# Available variables: {{ git_diff }}, {{ branch }}, {{ recent_commits }}, {{ repo }}# If not specified, uses the default template shown below:# template = """# Format@@ -54,13 +54,19 @@ worktree-path = "../{main-worktree}.{branch}"# ---# <git-diff># ```-# {git-diff}+# {{ git_diff }}# ```# </git-diff>## <git-info>-# <current-branch>{branch}</current-branch>-# {recent-commits}+# <current-branch>{{ branch }}</current-branch>+# {% if recent_commits %}+# <previous-commit-message-titles>+# {% for commit in recent_commits %}+# <previous-commit-message-title>{{ commit }}</previous-commit-message-title>+# {% endfor %}+# </previous-commit-message-titles>+# {% endif %}# </git-info># """@@ -68,6 +74,24 @@ worktree-path = "../{main-worktree}.{branch}"# Supports ~ expansion: ~/.config/worktrunk/commit-template.txt# template-file = "~/.config/worktrunk/commit-template.txt"+# Optional: Custom squash commit message template (inline) - Uses Jinja2 syntax+# Available variables: {{ commits }}, {{ target_branch }}, {{ branch }}, {{ repo }}+# If not specified, uses the default template:+# squash-template = """+# Generate a conventional commit message (feat/fix/docs/style/refactor) that combines these changes into one cohesive message. Output only the commit message without any explanation.+#+# Squashing commits on current branch since branching from {{ target_branch }}+#+# Commits being combined:+# {% for commit in commits %}+# - {{ commit }}+# {% endfor %}+# """++# Optional: Load squash template from file (mutually exclusive with 'squash-template')+# Supports ~ expansion: ~/.config/worktrunk/squash-template.txt+# squash-template-file = "~/.config/worktrunk/squash-template.txt"+# Approved Commands# Commands approved for automatic execution after switching worktrees# Auto-populated when you use: wt switch --execute "command" --forcediff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 3a791e612..7b67c067c 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -298,9 +298,22 @@ fn handle_squash("🔄 {CYAN}Generating squash commit message...{CYAN:#}"))?;- let commit_message =- crate::llm::generate_squash_message(target_branch, &subjects, commit_generation_config)- .git_context("Failed to generate commit message")?;+ // Get current branch and repo name for template variables+ let current_branch = repo.current_branch()?.unwrap_or_else(|| "HEAD".to_string());+ let repo_root = repo.worktree_root()?;+ let repo_name = repo_root+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("repo");++ let commit_message = crate::llm::generate_squash_message(+ target_branch,+ &subjects,+ ¤t_branch,+ repo_name,+ commit_generation_config,+ )+ .git_context("Failed to generate commit message")?;// Display the generated commit messagelet formatted_message = format_commit_message_for_display(&commit_message);diff --git a/src/config.rs b/src/config.rsindex 3dcaf3609..09fbd6255 100644--- a/src/config.rs+++ b/src/config.rs@@ -62,7 +62,7 @@ pub struct CommitGenerationConfig {pub args: Vec<String>,/// Inline template for commit message prompt- /// Available variables: {git-diff}, {branch}, {recent-commits}, {repo}+ /// Available variables: {{ git_diff }}, {{ branch }}, {{ recent_commits }}, {{ repo }}#[serde(default)]pub template: Option<String>,@@ -70,6 +70,16 @@ pub struct CommitGenerationConfig {/// Supports tilde expansion (e.g., "~/.config/worktrunk/commit-template.txt")#[serde(default, rename = "template-file")]pub template_file: Option<String>,++ /// Inline template for squash commit message prompt+ /// Available variables: {{ commits }}, {{ target_branch }}, {{ branch }}, {{ repo }}+ #[serde(default, rename = "squash-template")]+ pub squash_template: Option<String>,++ /// Path to squash template file (mutually exclusive with squash-template)+ /// Supports tilde expansion (e.g., "~/.config/worktrunk/squash-template.txt")+ #[serde(default, rename = "squash-template-file")]+ pub squash_template_file: Option<String>,}/// Project-specific configuration (stored in .config/wt.toml within the project)@@ -197,6 +207,14 @@ impl WorktrunkConfig {));}+ if config.commit_generation.squash_template.is_some()+ && config.commit_generation.squash_template_file.is_some()+ {+ return Err(ConfigError::Message(+ "commit-generation.squash-template and commit-generation.squash-template-file are mutually exclusive".into(),+ ));+ }+Ok(config)}@@ -286,36 +304,6 @@ pub fn expand_template(result}-/// Expand commit template variables-///-/// Supported variables:-/// - `{git-diff}` - Staged changes (diff output)-/// - `{branch}` - Current branch name-/// - `{recent-commits}` - Recent commit subjects (formatted, or empty string)-/// - `{repo}` - Repository name-///-/// # Examples-/// ```-/// use worktrunk::config::expand_commit_template;-///-/// let template = "Changes:\n{git-diff}\n\nBranch: {branch}";-/// let result = expand_commit_template(template, "diff output", "main", "", "myrepo");-/// assert_eq!(result, "Changes:\ndiff output\n\nBranch: main");-/// ```-pub fn expand_commit_template(- template: &str,- diff: &str,- branch: &str,- recent_commits: &str,- repo: &str,-) -> String {- template- .replace("{git-diff}", diff)- .replace("{branch}", branch)- .replace("{recent-commits}", recent_commits)- .replace("{repo}", repo)-}-/// Expand tilde in file paths to home directory (cross-platform)////// Uses shellexpand for proper tilde expansion following shell conventions.@@ -813,30 +801,6 @@ mod tests {assert_eq!(result, "/path/to/repo/target -> /path/to/worktree/target");}- #[test]- fn test_expand_commit_template_all_variables() {- let template =- "Diff: {git-diff}\nBranch: {branch}\nCommits: {recent-commits}\nRepo: {repo}";- let result = expand_commit_template(- template,- "diff content",- "feature-x",- "- commit1\n- commit2",- "myrepo",- );- assert_eq!(- result,- "Diff: diff content\nBranch: feature-x\nCommits: - commit1\n- commit2\nRepo: myrepo"- );- }-- #[test]- fn test_expand_commit_template_empty_recent_commits() {- let template = "{git-diff}\n{recent-commits}";- let result = expand_commit_template(template, "diff", "main", "", "repo");- assert_eq!(result, "diff\n");- }-#[test]fn test_expand_tilde_with_home() {// Test that paths starting with ~/ get HOME prepended if HOME is set@@ -881,6 +845,34 @@ template-file = "~/file.txt"}}+ #[test]+ fn test_squash_template_mutually_exclusive_validation() {+ // Test that deserialization rejects both squash-template and squash-template-file+ let toml_content = r#"+worktree-path = "../{main-worktree}.{branch}"++[commit-generation]+command = "llm"+squash-template = "inline template"+squash-template-file = "~/file.txt"+"#;++ // Parse the TOML directly+ let config_result: Result<WorktrunkConfig, _> = toml::from_str(toml_content);++ // The deserialization should succeed, but validation in load() would fail+ // Since we can't easily test load() without env vars, we verify the fields deserialize+ if let Ok(config) = config_result {+ // Verify validation logic: both fields should not be Some+ let has_both = config.commit_generation.squash_template.is_some()+ && config.commit_generation.squash_template_file.is_some();+ assert!(+ has_both,+ "Config should have both squash template fields set for this test"+ );+ }+ }+#[test]fn test_commit_generation_config_serialization() {let config = CommitGenerationConfig {@@ -888,6 +880,8 @@ template-file = "~/file.txt"args: vec!["-m".to_string(), "model".to_string()],template: Some("template content".to_string()),template_file: None,+ squash_template: None,+ squash_template_file: None,};let toml = toml::to_string(&config).unwrap();diff --git a/src/llm.rs b/src/llm.rsindex d26d2902c..c8a536a8d 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -3,6 +3,8 @@ use std::process::{self, Stdio};use worktrunk::config::CommitGenerationConfig;use worktrunk::git::{GitError, Repository};+use minijinja::Environment;+/// Default template for commit message promptsconst DEFAULT_TEMPLATE: &str = r#"Format- First line: <50 chars, present tense, describes WHAT and WHY (not HOW).@@ -24,16 +26,33 @@ The following is the context for your task:---<git-diff>```-{git-diff}+{{ git_diff }}```</git-diff><git-info>- <current-branch>{branch}</current-branch>-{recent-commits}+ <current-branch>{{ branch }}</current-branch>+{% if recent_commits %}+ <previous-commit-message-titles>+{% for commit in recent_commits %}+ <previous-commit-message-title>{{ commit }}</previous-commit-message-title>+{% endfor %}+ </previous-commit-message-titles>+{% endif %}</git-info>"#;+/// Default template for squash commit message prompts+const DEFAULT_SQUASH_TEMPLATE: &str = r#"Generate a conventional commit message (feat/fix/docs/style/refactor) that combines these changes into one cohesive message. Output only the commit message without any explanation.++Squashing commits on current branch since branching from {{ target_branch }}++Commits being combined:+{% for commit in commits %}+- {{ commit }}+{% endfor %}+"#;+/// Execute an LLM command with the given prompt via stdin.////// This is the canonical way to execute LLM commands in this codebase.@@ -82,25 +101,7 @@ fn execute_llm_command(Ok(message)}-/// Format recent commits for template expansion-fn format_recent_commits(commits: Option<&Vec<String>>) -> String {- match commits {- Some(commits) if !commits.is_empty() => {- let mut result = String::from(" <previous-commit-message-titles>\n");- for commit in commits {- result.push_str(&format!(- " <previous-commit-message-title>{}</previous-commit-message-title>\n",- commit- ));- }- result.push_str(" </previous-commit-message-titles>");- result- }- _ => String::new(),- }-}--/// Build the commit prompt from config template or default+/// Build the commit prompt from config template or default using minijinjafn build_commit_prompt(config: &CommitGenerationConfig,diff: &str,@@ -132,19 +133,69 @@ fn build_commit_prompt(return Err("Template is empty".into());}- // Format recent commits- let recent_commits_formatted = format_recent_commits(recent_commits);+ // Render template with minijinja+ let env = Environment::new();+ let tmpl = env.template_from_str(&template)?;- // Expand variables- let expanded = worktrunk::config::expand_commit_template(- &template,- diff,- branch,- &recent_commits_formatted,- repo_name,- );+ let rendered = tmpl.render(minijinja::context! {+ git_diff => diff,+ branch => branch,+ recent_commits => recent_commits.unwrap_or(&vec![]),+ repo => repo_name,+ })?;++ Ok(rendered)+}++/// Build the squash commit prompt from config template or default using minijinja+fn build_squash_prompt(+ config: &CommitGenerationConfig,+ target_branch: &str,+ commits: &[String],+ current_branch: &str,+ repo_name: &str,+) -> Result<String, Box<dyn std::error::Error>> {+ // Get template source+ let template = match (&config.squash_template, &config.squash_template_file) {+ (Some(inline), None) => inline.clone(),+ (None, Some(path)) => {+ let expanded_path = worktrunk::config::expand_tilde(path);+ std::fs::read_to_string(&expanded_path).map_err(|e| {+ format!(+ "Failed to read squash-template-file '{}': {}",+ expanded_path.display(),+ e+ )+ })?+ }+ (None, None) => DEFAULT_SQUASH_TEMPLATE.to_string(),+ (Some(_), Some(_)) => {+ unreachable!(+ "Config validation should prevent both squash-template and squash-template-file"+ )+ }+ };++ // Validate non-empty+ if template.trim().is_empty() {+ return Err("Squash template is empty".into());+ }++ // Render template with minijinja+ let env = Environment::new();+ let tmpl = env.template_from_str(&template)?;- Ok(expanded)+ // Reverse commits so they're in chronological order+ let commits_reversed: Vec<&String> = commits.iter().rev().collect();++ let rendered = tmpl.render(minijinja::context! {+ target_branch => target_branch,+ commits => commits_reversed,+ branch => current_branch,+ repo => repo_name,+ })?;++ Ok(rendered)}pub fn generate_commit_message(@@ -219,6 +270,8 @@ fn try_generate_commit_message(pub fn generate_squash_message(target_branch: &str,subjects: &[String],+ current_branch: &str,+ repo_name: &str,commit_generation_config: &CommitGenerationConfig,) -> Result<String, Box<dyn std::error::Error>> {// Check if commit generation is configured (non-empty command)@@ -226,12 +279,14 @@ pub fn generate_squash_message(&& !command.trim().is_empty(){// Commit generation is explicitly configured - fail if it doesn't work- return try_generate_llm_message(+ let prompt = build_squash_prompt(+ commit_generation_config,target_branch,subjects,- command,- &commit_generation_config.args,- );+ current_branch,+ repo_name,+ )?;+ return execute_llm_command(command, &commit_generation_config.args, &prompt);}// Fallback: deterministic commit message (only when not configured)@@ -244,24 +299,201 @@ pub fn generate_squash_message(Ok(commit_message)}-fn try_generate_llm_message(- target_branch: &str,- subjects: &[String],- command: &str,- args: &[String],-) -> Result<String, Box<dyn std::error::Error>> {- // Build context prompt- let mut context = format!(- "Squashing commits on current branch since branching from {}\n\n",- target_branch- );- context.push_str("Commits being combined:\n");- for subject in subjects.iter().rev() {- context.push_str(&format!("- {}\n", subject));+#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_build_commit_prompt_with_default_template() {+ let config = CommitGenerationConfig::default();+ let result = build_commit_prompt(&config, "diff content", "main", None, "myrepo");+ assert!(result.is_ok());+ let prompt = result.unwrap();+ assert!(prompt.contains("diff content"));+ assert!(prompt.contains("main"));+ // Default template doesn't directly show repo name in output}- let prompt = "Generate a conventional commit message (feat/fix/docs/style/refactor) that combines these changes into one cohesive message. Output only the commit message without any explanation.";- let full_prompt = format!("{}\n\n{}", context, prompt);+ #[test]+ fn test_build_commit_prompt_with_recent_commits() {+ let config = CommitGenerationConfig::default();+ let commits = vec!["feat: add feature".to_string(), "fix: bug".to_string()];+ let result = build_commit_prompt(&config, "diff", "main", Some(&commits), "repo");+ assert!(result.is_ok());+ let prompt = result.unwrap();+ assert!(prompt.contains("feat: add feature"));+ assert!(prompt.contains("fix: bug"));+ assert!(prompt.contains("<previous-commit-message-titles>"));+ }- execute_llm_command(command, args, &full_prompt)+ #[test]+ fn test_build_commit_prompt_empty_recent_commits() {+ let config = CommitGenerationConfig::default();+ let commits = vec![];+ let result = build_commit_prompt(&config, "diff", "main", Some(&commits), "repo");+ assert!(result.is_ok());+ // Should not render the recent commits section if empty+ let prompt = result.unwrap();+ assert!(!prompt.contains("<previous-commit-message-titles>"));+ }++ #[test]+ fn test_build_commit_prompt_with_custom_template() {+ let config = CommitGenerationConfig {+ command: None,+ args: vec![],+ template: Some("Branch: {{ branch }}\nDiff: {{ git_diff }}".to_string()),+ template_file: None,+ squash_template: None,+ squash_template_file: None,+ };+ let result = build_commit_prompt(&config, "my diff", "feature", None, "repo");+ assert!(result.is_ok());+ assert_eq!(result.unwrap(), "Branch: feature\nDiff: my diff");+ }++ #[test]+ fn test_build_commit_prompt_malformed_jinja() {+ let config = CommitGenerationConfig {+ command: None,+ args: vec![],+ template: Some("{{ unclosed".to_string()),+ template_file: None,+ squash_template: None,+ squash_template_file: None,+ };+ let result = build_commit_prompt(&config, "diff", "main", None, "repo");+ assert!(result.is_err());+ }++ #[test]+ fn test_build_commit_prompt_empty_template() {+ let config = CommitGenerationConfig {+ command: None,+ args: vec![],+ template: Some(" ".to_string()),+ template_file: None,+ squash_template: None,+ squash_template_file: None,+ };+ let result = build_commit_prompt(&config, "diff", "main", None, "repo");+ assert!(result.is_err());+ assert_eq!(result.unwrap_err().to_string(), "Template is empty");+ }++ #[test]+ fn test_build_commit_prompt_with_all_variables() {+ let config = CommitGenerationConfig {+ command: None,+ args: vec![],+ template: Some(+ "Repo: {{ repo }}\nBranch: {{ branch }}\nDiff: {{ git_diff }}\n{% for c in recent_commits %}{{ c }}\n{% endfor %}"+ .to_string(),+ ),+ template_file: None,+ squash_template: None,+ squash_template_file: None,+ };+ let commits = vec!["commit1".to_string(), "commit2".to_string()];+ let result = build_commit_prompt(&config, "my diff", "feature", Some(&commits), "myrepo");+ assert!(result.is_ok());+ let prompt = result.unwrap();+ assert_eq!(+ prompt,+ "Repo: myrepo\nBranch: feature\nDiff: my diff\ncommit1\ncommit2\n"+ );+ }++ #[test]+ fn test_build_squash_prompt_with_default_template() {+ let config = CommitGenerationConfig::default();+ let commits = vec!["feat: A".to_string(), "fix: B".to_string()];+ let result = build_squash_prompt(&config, "main", &commits, "feature", "repo");+ assert!(result.is_ok());+ let prompt = result.unwrap();+ // Commits should be reversed (chronological order: B first, then A)+ assert!(prompt.contains("fix: B"));+ assert!(prompt.contains("feat: A"));+ assert!(prompt.contains("main"));+ }++ #[test]+ fn test_build_squash_prompt_with_custom_template() {+ let config = CommitGenerationConfig {+ command: None,+ args: vec![],+ template: None,+ template_file: None,+ squash_template: Some(+ "Target: {{ target_branch }}\n{% for c in commits %}{{ c }}\n{% endfor %}"+ .to_string(),+ ),+ squash_template_file: None,+ };+ let commits = vec!["A".to_string(), "B".to_string()];+ let result = build_squash_prompt(&config, "main", &commits, "feature", "repo");+ assert!(result.is_ok());+ // Commits are reversed, so chronological order is B, A+ assert_eq!(result.unwrap(), "Target: main\nB\nA\n");+ }++ #[test]+ fn test_build_squash_prompt_empty_commits() {+ let config = CommitGenerationConfig::default();+ let commits = vec![];+ let result = build_squash_prompt(&config, "main", &commits, "feature", "repo");+ assert!(result.is_ok());+ }++ #[test]+ fn test_build_squash_prompt_malformed_jinja() {+ let config = CommitGenerationConfig {+ command: None,+ args: vec![],+ template: None,+ template_file: None,+ squash_template: Some("{% for x in commits %}{{ x }".to_string()),+ squash_template_file: None,+ };+ let result = build_squash_prompt(&config, "main", &[], "feature", "repo");+ assert!(result.is_err());+ }++ #[test]+ fn test_build_squash_prompt_empty_template() {+ let config = CommitGenerationConfig {+ command: None,+ args: vec![],+ template: None,+ template_file: None,+ squash_template: Some(" \n ".to_string()),+ squash_template_file: None,+ };+ let result = build_squash_prompt(&config, "main", &[], "feature", "repo");+ assert!(result.is_err());+ assert_eq!(result.unwrap_err().to_string(), "Squash template is empty");+ }++ #[test]+ fn test_build_squash_prompt_with_all_variables() {+ let config = CommitGenerationConfig {+ command: None,+ args: vec![],+ template: None,+ template_file: None,+ squash_template: Some(+ "Repo: {{ repo }}\nBranch: {{ branch }}\nTarget: {{ target_branch }}\n{% for c in commits %}{{ c }}\n{% endfor %}"+ .to_string(),+ ),+ squash_template_file: None,+ };+ let commits = vec!["A".to_string(), "B".to_string()];+ let result = build_squash_prompt(&config, "main", &commits, "feature", "myrepo");+ assert!(result.is_ok());+ let prompt = result.unwrap();+ assert_eq!(+ prompt,+ "Repo: myrepo\nBranch: feature\nTarget: main\nB\nA\n"+ );+ }}